Support turbo2.
[vuplus_dvbapp] / lib / python / Plugins / SystemPlugins / TransCodingSetup / plugin.py
1 from Screens.Screen import Screen
2 from Components.ConfigList import ConfigListScreen
3 from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigSelection, ConfigInteger, integer_limits
4 from Components.ActionMap import ActionMap
5 from Screens.MessageBox import MessageBox
6 from Components.Sources.StaticText import StaticText
7 from Plugins.Plugin import PluginDescriptor
8 from Tools.Directories import fileExists
9 from enigma import eTimer, getDesktop
10 from os import system as os_system, path as os_path, listdir as os_listdir
11 from __init__ import _
12
13 class TconfigSelection(ConfigSelection):
14         def __init__(self, encoder, choices, default = None):
15                 self.encoder = encoder
16                 ConfigSelection.__init__(self, choices, default)
17
18 class TconfigInteger(ConfigInteger):
19         def __init__(self, encoder, default, limits = integer_limits):
20                 self.encoder = encoder
21                 ConfigInteger.__init__(self, default, limits)
22
23 def getModel():
24         filename = "/proc/stb/info/vumodel"
25         if fileExists(filename):
26                 return file(filename).read().strip()
27         return ""
28
29 def getProcValue(procPath):
30         fd = open(procPath,'r')
31         curValue = fd.read().strip(' ').strip('\n')
32         fd.close()
33 #       print "[TranscodingSetup] get %s from %s" % (curValue, procPath)
34         return curValue
35
36 def setProcValue(procPath, value):
37 #       print "[TranscodingSetup] set %s to %s" % (procPath, value)
38         fd = open(procPath,'w')
39         fd.write(value)
40         fd.close()
41
42 def getProcPath(encoder, configName):
43         _configName = {
44                 "bitrate"               :       "bitrate",
45                 "framerate"             :       "framerate",
46                 "resolution"    :       "display_format",
47                 "aspectratio"   :       "aspectratio",
48                 "audiocodec"    :       "audio_codec",
49                 "videocodec"    :       "video_codec",
50                 "gopframeb"     :       "gop_frameb",
51                 "gopframep"     :       "gop_framep",
52                 "level"                 :       "level",
53                 "profile"               :       "profile",
54                 "width"                 :       "width",
55                 "height"                :       "height",
56                 "framerate_choices"             :       "framerate_choices",
57                 "resolution_choices"    :       "resolution_choices",
58                 "aspectratio_choices"   :       "aspectratio_choices",
59                 "resolution_choices"    :       "display_format_choices",
60                 "audiocodec_choices"    :       "audio_codec_choices",
61                 "videocodec_choices"    :       "video_codec_choices",
62                 "level_choices"         :       "level_choices",
63                 "profile_choices"       :       "profile_choices",
64         }.get(configName)
65         return "/proc/stb/encoder/%s/%s" % (encoder, _configName)
66
67 def checkSupportAdvanced():
68         if fileExists( getProcPath(0, "aspectratio") ):
69                 return True
70         return False
71
72 def getChoices(configName):
73         choices = []
74         proc_path = getProcPath(encoder, configName)
75         if fileExists(proc_path):
76                 data = getProcValue(proc_path)
77                 if data is not None:
78                         for choice in data.split(' '):
79                                 choices.append( (choice, _(choice)) )
80         return choices
81
82 def getDefault(choices, value):
83         for choice in choices:
84                 if choice[0] == value:
85                         return value
86         return choices[0][0]
87
88 def getAspectratioChoices():
89         choices = []
90         proc_path = getProcPath(encoder, "aspectratio_choices")
91         if fileExists(proc_path):
92                 data = getProcValue(proc_path)
93                 if data is not None:
94                         for choice in data.split(' '):
95                                 try:
96                                         k,v = choice.split(':')
97                                         choices.append( (k, _(v)) )
98                                 except:
99                                         continue
100         return choices
101
102 config.plugins.transcodingsetup = ConfigSubsection()
103 config.plugins.transcodingsetup.transcoding = ConfigSelection(default = "enable", choices = [ ("enable", _("enable")), ("disable", _("disable"))] )
104 config.plugins.transcodingsetup.port = ConfigSelection(default = "8002", choices = [ ("8001", "8001"), ("8002", "8002")] )
105
106 def getAttr(attr, encoder):
107         return getattr(config.plugins.transcodingsetup, encoder == '0' and attr or "%s_%s"%(attr, encoder))
108
109 def hasAttr(attr, encoder):
110         return hasattr(config.plugins.transcodingsetup, encoder == '0' and attr or "%s_%s"%(attr, encoder))
111
112 def setAttr(attr, encoder, value):
113         setattr(config.plugins.transcodingsetup, encoder == '0' and attr or "%s_%s"%(attr, encoder), value)
114
115 def createTransCodingConfig(encoder):
116         if fileExists( getProcPath(encoder ,"bitrate") ):
117                 vumodel = getModel()
118                 if vumodel in ("solo2", "solose"):
119                         choice = TconfigInteger(encoder, default = 400000, limits = (50000, 1000000))
120                 else:
121                         choice = TconfigInteger(encoder, default = 2000000, limits = (100000, 10000000))
122                 setAttr("bitrate", encoder, choice)
123
124         if fileExists( getProcPath(encoder ,"framerate") ):
125                 framerate_choices = getChoices("framerate_choices")
126                 if (len(framerate_choices) == 0):
127                         framerate_choices = [ ("23976", _("23976")), ("24000", _("24000")), ("25000", _("25000")), ("29970", _("29970")), ("30000", _("30000")), ("50000", _("50000")), ("59940", _("59940")), ("60000", _("60000"))]
128                 choice = TconfigSelection(encoder, default = getDefault(framerate_choices, "30000"), choices = framerate_choices )
129                 setAttr("framerate", encoder, choice)
130
131         if checkSupportAdvanced() and (hasAttr("bitrate", encoder) or hasAttr("framerate", encoder)):
132                 choice = TconfigSelection(encoder, default = "Off", choices = [ ("On", _("On")), ("Off", _("Off")) ] )
133                 setAttr("automode", encoder, choice)
134
135         if fileExists( getProcPath(encoder, "resolution") ):
136                 resolutaion_choices = getChoices("resolution_choices")
137                 if (len(resolutaion_choices) == 0):
138                         resolutaion_choices = [ ("480p", _("480p")), ("576p", _("576p")), ("720p", _("720p")), ("320x240", _("320x240")), ("160x120", _("160x120")) ]
139                 choice = TconfigSelection(encoder, default = getDefault(resolutaion_choices, "480p"), choices = resolutaion_choices )
140                 setAttr("resolution", encoder, choice)
141
142         if fileExists( getProcPath(encoder, "aspectratio") ):
143                 aspectratio_choices = getAspectratioChoices()
144                 if len(aspectratio_choices) == 0:
145                         aspectratio_choices = [ ("0", _("auto")), ("1", _("4x3")), ("2", _("16x9")) ]
146                 choice = TconfigSelection(encoder, default = "1", choices = aspectratio_choices )
147                 setAttr("aspectratio", encoder, choice)
148
149         if fileExists( getProcPath(encoder, "audiocodec") ):
150                 audiocodec_choices = getChoices("audiocodec_choices")
151                 if len(audiocodec_choices) == 0:
152                         audiocodec_choices = [("mpg", _("mpg")), ("mp3", _("mp3")), ("aac", _("aac")), ("aac+", _("aac+")), ("aac+loas", _("aac+loas")), ("aac+adts", _("aac+adts")), ("ac3", _("ac3"))]
153                 choice = TconfigSelection(encoder, default = getDefault(audiocodec_choices, "aac"), choices = audiocodec_choices )
154                 setAttr("audiocodec", encoder, choice)
155
156         if fileExists( getProcPath(encoder, "videocodec") ):
157                 videocodec_choices = getChoices("videocodec_choices")
158                 if len(videocodec_choices) == 0:
159                         _choices = [ ("h264", _("h264")) ]
160                 choice = TconfigSelection(encoder, default = getDefault(videocodec_choices, "h264"), choices = videocodec_choices )
161                 setAttr("videocodec", encoder, choice)
162
163         if fileExists( getProcPath(encoder, "gopframeb") ):
164                 choice = TconfigInteger(encoder, default = 0, limits = (0, 60))
165                 setAttr("gopframeb", encoder, choice)
166
167         if fileExists( getProcPath(encoder, "gopframep") ):
168                 choice = TconfigInteger(encoder, default = 29, limits = (0, 60))
169                 setAttr("gopframep", encoder, choice)
170
171         if fileExists( getProcPath(encoder, "level") ):
172                 level_choices = getChoices("level_choices")
173                 if (len(level_choices) == 0):
174                         level_choices = [("1.0", _("1.0")), ("2.0", _("2.0")),
175                                 ("2.1", _("2.1")), ("2.2", _("2.2")), ("3.0", _("3.0")), ("3.1", _("3.1")),
176                                 ("3.2", _("3.2")), ("4.0", _("4.0")), ("4.1", _("4.1")), ("4.2", _("4.2")),
177                                 ("5.0", _("5.0")), ("low", _("low")), ("main", _("main")), ("high", _("high"))]
178                 choice = TconfigSelection(encoder, default = getDefault(level_choices, "3.1"), choices = level_choices )
179                 setAttr("level", encoder, choice)
180
181         if fileExists( getProcPath(encoder, "profile") ):
182                 profile_choices = getChoices("profile_choices")
183                 if (len(profile_choices) == 0):
184                         profile_choices = [("baseline", _("baseline")), ("simple", _("simple")), ("main", _("main")), ("high", _("high")), ("advanced simple", _("advancedsimple"))]
185                 choice = TconfigSelection(encoder, default = getDefault(profile_choices, "baseline"), choices = profile_choices )
186                 setAttr("profile", encoder, choice)
187
188 # check encoders
189 encoders = []
190 encoderPath = "/proc/stb/encoder"
191 for encoder in os_listdir(encoderPath):
192         encPath = os_path.join(encoderPath, encoder)
193         if not os_path.isdir(encPath):
194                 continue
195         if fileExists(os_path.join(encPath, "bitrate")):
196                 encoders.append(encoder)
197                 createTransCodingConfig(encoder)
198
199 if len(encoders) > 1:
200         encoders.sort()
201         choices = []
202         for encoder in encoders:
203                 choices.append((encoder, encoder))
204         config.plugins.transcodingsetup.encoder = ConfigSelection(default = '0', choices = choices )
205
206 transcodingsetupinit = None
207 class TranscodingSetupInit:
208         def __init__(self):
209                 self.pluginsetup = None
210                 config.plugins.transcodingsetup.port.addNotifier(self.setPort)
211
212                 for encoder in encoders:
213                         if hasAttr("automode", encoder):
214                                 if getAttr("automode", encoder).value == "On":
215                                         getAttr("automode", encoder).addNotifier(self.setAutomode)
216
217                                         if hasAttr("bitrate", encoder):
218                                                 getAttr("bitrate", encoder).addNotifier(self.setBitrate, False)
219
220                                         if hasAttr("framerate", encoder):
221                                                 getAttr("framerate", encoder).addNotifier(self.setFramerate, False)
222
223                                 else: # autoMode Off
224                                         getAttr("automode", encoder).addNotifier(self.setAutomode, False)
225                                         if hasAttr("bitrate", encoder):
226                                                 getAttr("bitrate", encoder).addNotifier(self.setBitrate)
227
228                                         if hasAttr("framerate", encoder):
229                                                 getAttr("framerate", encoder).addNotifier(self.setFramerate)
230
231                         else:
232                                 if hasAttr("bitrate", encoder):
233                                         getAttr("bitrate", encoder).addNotifier(self.setBitrate)
234
235                                 if hasAttr("framerate", encoder):
236                                         getAttr("framerate", encoder).addNotifier(self.setFramerate)
237
238                         if hasAttr("resolution", encoder):
239                                 getAttr("resolution", encoder).addNotifier(self.setResolution)
240
241                         if hasAttr("aspectratio", encoder):
242                                 getAttr("aspectratio", encoder).addNotifier(self.setAspectRatio)
243
244                         if hasAttr("audiocodec", encoder):
245                                 getAttr("audiocodec", encoder).addNotifier(self.setAudioCodec)
246
247                         if hasAttr("videocodec", encoder):
248                                 getAttr("videocodec", encoder).addNotifier(self.setVideoCodec)
249
250                         if hasAttr("gopframeb", encoder):
251                                 getAttr("gopframeb", encoder).addNotifier(self.setGopFrameB)
252
253                         if hasAttr("gopframep", encoder):
254                                 getAttr("gopframep", encoder).addNotifier(self.setGopFrameP)
255
256                         if hasAttr("level", encoder):
257                                 getAttr("level", encoder).addNotifier(self.setLevel)
258
259                         if hasAttr("profile", encoder):
260                                 getAttr("profile", encoder).addNotifier(self.setProfile)
261
262         def setConfig(self, procPath, value):
263                 if not fileExists(procPath):
264                         return -1
265                 if isinstance(value, str):
266                         value = value.strip(' ').strip('\n')
267                 else:
268                         value = str(value)
269                 try:
270                         oldValue = getProcValue(procPath)
271                         if oldValue != value:
272 #                               print "[TranscodingSetup] set %s "%procPath, value
273                                 setProcValue(procPath, value)
274                                 setValue = getProcValue(procPath)
275                                 if value != setValue:
276                                         print "[TranscodingSetup] set failed. (%s > %s)" % ( value, procPath )
277                                         return -1
278
279                         # Set bitrate "-1" when automode is "ON" and display_format is changed.
280                         # At custom mode, set display_format -> width -> height -> bitrate (-1)
281                         setname = procPath.split('/')[-1]
282                         encoder = procPath.split('/')[-2]
283                         if (setname == "display_format" and value != "custom") or (setname == "height"):
284                                 if hasAttr("automode", encoder) and getAttr("automode", encoder).value == "On":
285                                         if hasAttr("bitrate", encoder):
286                                                 setProcValue(getProcPath(encoder ,"bitrate"), str(-1))
287                                         elif hasAttr("framerate", encoder):
288                                                 setProcValue(getProcPath(encoder ,"framerate"), str(-1))
289
290                         return 0
291
292                 except:
293                         print "setConfig exception error (%s > %s)" % ( value, procPath )
294                         return -1
295                 return 0
296
297         def setPort(self, configElement):
298                 port = configElement.value
299                 port2 = (port == "8001") and "8002" or "8001"
300
301 #               print "[TranscodingSetup] set port ",port
302                 try:
303                         newConfigData = ""
304                         oldConfigData = file('/etc/inetd.conf').read()
305                         for L in oldConfigData.splitlines():
306                                 try:
307                                         if L[0] == '#':
308                                                 newConfigData += L + '\n'
309                                                 continue
310                                 except: continue
311                                 LL = L.split()
312                                 if LL[5] == '/usr/bin/streamproxy':
313                                         LL[0] = port2
314                                 elif LL[5] == '/usr/bin/transtreamproxy':
315                                         LL[0] = port
316                                 newConfigData += ''.join(str(X) + " " for X in LL) + '\n'
317
318                         if newConfigData.find("transtreamproxy") == -1:
319                                 newConfigData += port + " stream tcp nowait root /usr/bin/transtreamproxy transtreamproxy\n"
320                         file('/etc/inetd.conf', 'w').write(newConfigData)
321                 except:
322                         self.showMessage("Set port failed.", MessageBox.TYPE_ERROR)
323                         return
324
325                 self.inetdRestart()
326                 if port == "8001":
327                         msg = "Set port OK.\nPC Streaming is replaced with mobile streaming."
328                         self.showMessage(msg, MessageBox.TYPE_INFO)
329
330         def setupConfig(self, configElement, procPath):
331 #               print "[TranscodingSetup] set %s to %s" % ( procPath, configElement.value )
332                 configValue = configElement.value
333                 if self.setConfig(procPath, configValue):
334                         # set config failed, reset to current proc value
335                         self.getConfigFromProc(procPath, configElement)
336                         self.showMessage("Set %s failed." % (procPath), MessageBox.TYPE_ERROR)
337
338         def getConfigFromProc(self, procPath, configElement):
339                 curValue = getProcValue(procPath)
340                 if isinstance(configElement.value, int): # is int ?
341                         curValue = int(curValue)
342                 configElement.value = curValue
343                 configElement.save()
344
345         def setAutomode(self, configElement):
346                 configName = "AutoMode"
347 #               print "[TranscodingSetup]  setAutomode, configName %s, value %s" % ( configName, configElement.value )
348                 if configElement.value == "On":
349                         autoValue = str(-1)
350                         if ((hasAttr("bitrate", configElement.encoder) and
351                                         self.setConfig(getProcPath(configElement.encoder ,"bitrate"), autoValue) ) or
352                                         (hasAttr("framerate", configElement.encoder) and
353                                         self.setConfig(getProcPath(configElement.encoder ,"framerate"), autoValue) ) ):
354                                 configElement.value = "Off" # set config failed, reset to previous value
355                                 configElement.save()
356                                 self.showMessage("Set %s failed." % (configName), MessageBox.TYPE_ERROR)
357                 else: # Off
358                         if hasAttr("bitrate", configElement.encoder):
359                                 self.setBitrate(getAttr("bitrate", configElement.encoder))
360                         if hasAttr("framerate", configElement.encoder):
361                                 self.setFramerate(getAttr("framerate", configElement.encoder))
362
363         def setBitrate(self, configElement):
364                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"bitrate"))
365
366         def setFramerate(self, configElement):
367                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"framerate"))
368
369         def setResolution(self, configElement):
370                 resolution = configElement.value
371                 if resolution in [ "320x240", "160x120" ]:
372                         (width, height) = tuple(resolution.split('x'))
373                         self.setConfig(getProcPath(configElement.encoder ,"resolution"), "custom")
374                         self.setConfig(getProcPath(configElement.encoder ,"width"), width)
375                         self.setConfig(getProcPath(configElement.encoder ,"height"), height)
376                 else:
377                         self.setupConfig(configElement, getProcPath(configElement.encoder ,"resolution"))
378
379         def setAspectRatio(self, configElement):
380                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"aspectratio"))
381
382         def setAudioCodec(self, configElement):
383                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"audiocodec"))
384
385         def setVideoCodec(self, configElement):
386                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"videocodec"))
387
388         def setGopFrameB(self, configElement):
389                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"gopframeb"))
390
391         def setGopFrameP(self, configElement):
392                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"gopframep"))
393
394         def setLevel(self, configElement):
395                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"level"))
396
397         def setProfile(self, configElement):
398                 self.setupConfig(configElement, getProcPath(configElement.encoder ,"profile"))
399
400         def inetdRestart(self):
401                 if fileExists("/etc/init.d/inetd"):
402                         os_system("/etc/init.d/inetd restart")
403                 elif fileExists("/etc/init.d/inetd.busybox"):
404                         os_system("/etc/init.d/inetd.busybox restart")
405
406         def showMessage(self, msg, msgType):
407                 if self.pluginsetup:
408                         self.pluginsetup.showMessage(msg, msgType)
409
410 class TranscodingSetup(Screen, ConfigListScreen):
411         size = getDesktop(0).size()
412         if checkSupportAdvanced():
413                 if size.width() > 750:
414                         size_h = 450
415                 else:
416                         size_h = 370
417         else:
418                 size_h = 280
419
420         pos_h = ( size_h , size_h - 150 , (size_h - 150) + 70, (size_h - 150) + 70 + 60 )
421         skin_advanced =  """
422                 <screen position="center,center" size="600,%d">
423                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,0" size="140,40" alphatest="on" />
424                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,0" size="140,40" alphatest="on" />
425                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,0" size="140,40" alphatest="on" />
426                         <ePixmap pixmap="skin_default/buttons/blue.png" position="455,0" size="140,40" alphatest="on" />
427                         <widget source="key_red" render="Label" position="5,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
428                         <widget source="key_green" render="Label" position="155,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
429                         <widget source="key_yellow" render="Label" position="305,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
430                         <widget source="key_blue" render="Label" position="455,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" />
431                         <widget name="config" zPosition="2" position="25,70" size="560,%d" scrollbarMode="showOnDemand" transparent="1" />
432                         <widget source="description" render="Label" position="20,%d" size="540,60" font="Regular;20" halign="center" valign="center" />
433                         <widget source="text" render="Label" position="20,%d" size="540,20" font="Regular;22" halign="center" valign="center" />
434                 </screen>
435                 """ % pos_h
436
437         skin_normal =  """
438                 <screen position="center,center" size="600,%d">
439                         <ePixmap pixmap="skin_default/buttons/red.png" position="40,0" size="140,40" alphatest="on" />
440                         <ePixmap pixmap="skin_default/buttons/green.png" position="230,0" size="140,40" alphatest="on" />
441                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="420,0" size="140,40" alphatest="on" />
442                         <widget source="key_red" render="Label" position="40,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
443                         <widget source="key_green" render="Label" position="230,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
444                         <widget source="key_yellow" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
445                         <widget name="config" zPosition="2" position="25,70" size="560,%d" scrollbarMode="showOnDemand" transparent="1" />
446                         <widget source="description" render="Label" position="20,%d" size="540,60" font="Regular;20" halign="center" valign="center" />
447                         <widget source="text" render="Label" position="20,%d" size="540,20" font="Regular;22" halign="center" valign="center" />
448                 </screen>
449                 """ % pos_h
450
451         def __init__(self,session):
452                 Screen.__init__(self,session)
453                 self.session = session
454                 self.setTitle(_("Transcoding Setup"))
455
456                 if checkSupportAdvanced():
457                         self.skin = TranscodingSetup.skin_advanced
458                 else:
459                         self.skin = TranscodingSetup.skin_normal
460
461                 vumodel = getModel()
462                 if vumodel in ("solo2", "solose", "solo4k"):
463                         TEXT = _("Transcoding and PIP are mutually exclusive.")
464                 elif vumodel == "duo2":
465                         TEXT = _("2nd transcoding and PIP are mutually exclusive.")
466                 else:
467                         TEXT = _(" ")
468
469                 self["text"] = StaticText(_("%s")%TEXT)
470
471                 self["key_red"] = StaticText(_("Cancel"))
472                 self["key_green"] = StaticText(_("Save"))
473                 self["key_yellow"] = StaticText(_("Default"))
474                 self["key_blue"] = StaticText(_("Advanced"))
475                 self["description"] = StaticText(_("Transcoding Setup"))
476
477                 self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ],
478                 {
479                         "cancel"        : self.keyCancel,
480                         "red"           : self.keyCancel,
481                         "green"         : self.keySave,
482                         "yellow"        : self.KeyDefault,
483                         "blue"          : self.keyBlue,
484                 }, -2)
485
486                 self.list = []
487                 ConfigListScreen.__init__(self, self.list,session = self.session)
488                 self.setupMode = "Normal" # Normal / Advanced
489                 self.encoder = None
490                 self.automode = None
491                 self.createSetup()
492                 self.onLayoutFinish.append(self.checkEncoder)
493                 self.invaliedModelTimer = eTimer()
494                 self.invaliedModelTimer.callback.append(self.invalidmodel)
495                 global transcodingsetupinit
496                 transcodingsetupinit.pluginsetup = self
497                 self.onClose.append(self.onClosed)
498
499         def onClosed(self):
500                 transcodingsetupinit.pluginsetup = None
501
502         def checkEncoder(self):
503                 if not fileExists("/proc/stb/encoder/enable"):
504                         self.invaliedModelTimer.start(100,True)
505
506         def invalidmodel(self):
507                 self.session.openWithCallback(self.close, MessageBox, _("This model is not support transcoding."), MessageBox.TYPE_ERROR)
508
509         def createSetup(self):
510                 self.list = []
511                 self.list.append(getConfigListEntry(_("Port"), config.plugins.transcodingsetup.port))
512
513                 encoder = None
514                 if len(encoders) == 1:
515                         encoder = encoders[0]
516                 elif len(encoders) > 1:
517                         self.encoder = getConfigListEntry(_("Encoder"), config.plugins.transcodingsetup.encoder)
518                         self.list.append( self.encoder )
519                         encoder = config.plugins.transcodingsetup.encoder.value                 
520
521                 if encoder is not None:
522                         self.automode = None
523                         if checkSupportAdvanced() and hasAttr('automode', encoder):
524                                 self.automode = getConfigListEntry(_("Auto set Framerate / Bitrate"), getAttr('automode', encoder))
525
526                         if self.automode is not None:
527                                 self.list.append( self.automode )
528
529                         if not ( hasAttr('automode', encoder) and getAttr('automode', encoder).value == "On" ):
530                                 if hasAttr('bitrate', encoder):
531                                         self.list.append(getConfigListEntry(_("Bitrate"), getAttr('bitrate', encoder)))
532                                 if hasAttr('framerate', encoder):
533                                         self.list.append(getConfigListEntry(_("Framerate"), getAttr('framerate', encoder)))
534
535                         if hasAttr('resolution', encoder):
536                                         self.list.append(getConfigListEntry(_("Resolution"), getAttr('resolution', encoder)))
537
538                         if checkSupportAdvanced() and self.setupMode != "Normal":
539                                 if hasAttr('aspectratio', encoder):
540                                         self.list.append(getConfigListEntry(_("Aspect Ratio"), getAttr('aspectratio', encoder)))
541
542                                 if hasAttr('audiocodec', encoder):
543                                         self.list.append(getConfigListEntry(_("Audio codec"), getAttr('audiocodec', encoder)))
544
545                                 if hasAttr('videocodec', encoder):
546                                         self.list.append(getConfigListEntry(_("Video codec"), getAttr('videocodec', encoder)))
547
548                                 if hasAttr('gopframe', encoder):
549                                         self.list.append(getConfigListEntry(_("GOP Frame B"), getAttr('gopframeb', encoder)))
550
551                                 if hasAttr('gopframep', encoder):
552                                         self.list.append(getConfigListEntry(_("GOP Frame P"), getAttr('gopframep', encoder)))
553
554                                 if hasAttr('level', encoder):
555                                         self.list.append(getConfigListEntry(_("Level"), getAttr('level', encoder)))
556
557                                 if hasAttr('profile', encoder):
558                                         self.list.append(getConfigListEntry(_("Profile"), getAttr('profile', encoder)))
559
560                 self["config"].list = self.list
561                 self["config"].l.setList(self.list)
562                 if not self.showDescription in self["config"].onSelectionChanged:
563                         self["config"].onSelectionChanged.append(self.showDescription)
564
565         def showDescription(self):
566                 configName = "<%s>\n"%self["config"].getCurrent()[0]
567                 current = self["config"].getCurrent()[1]
568                 className = self["config"].getCurrent()[1].__class__.__name__
569                 text = ""
570                 if className == "ConfigSelection" or className == "TconfigSelection":
571                         text = configName
572                         for choice in current.choices.choices:
573                                 if text == configName:  
574                                         text += choice[1]
575                                 else:
576                                         text += ', ' + choice[1]
577                 elif className == "ConfigInteger" or className == "TconfigInteger":
578                         limits = current.limits[0]
579                         text = configName
580                         text += "%s : %d, %s : %d" % (_("Min"), limits[0], _("Max"), limits[1])
581                 self["description"].setText(text)
582
583         def showMessage(self, msg, msgType = MessageBox.TYPE_ERROR):
584                 self.session.open(MessageBox, _(msg), msgType)
585
586         def saveAll(self):
587                 configs = config.plugins.transcodingsetup.dict()
588                 for (configName, configElement) in configs.items():
589                         configElement.save()
590
591         def keySave(self):
592                 self.saveAll()
593                 self.close()
594
595         def KeyDefault(self):
596                 configs = config.plugins.transcodingsetup.dict()
597                 for (configName, configElement) in configs.items():
598                         if configName.startswith("automode"):
599                                 continue
600                         configElement.value = configElement.default
601
602                 for (configName, configElement) in configs.items():
603                         if configName.startswith("automode"):
604                                 configElement.value = configElement.default
605
606                 self.createSetup()
607
608         def keyBlue(self):
609                 if not checkSupportAdvanced():
610                         return
611                 if self.setupMode == "Normal":
612                         self.setupMode = "Advanced"
613                         self["key_blue"].setText( _("Normal") )
614                 else:
615                         self.setupMode = "Normal"
616                         self["key_blue"].setText( _("Advanced") )
617                 self.createSetup()
618
619         def resetConfig(self):
620                 for x in self["config"].list:
621                         x[1].cancel()
622
623         def keyLeft(self):
624                 ConfigListScreen.keyLeft(self)
625                 if self.encoder is not None and (self["config"].getCurrent() == self.encoder) or self.automode is not None and (self["config"].getCurrent() == self.automode):
626                         self.createSetup()
627
628         def keyRight(self):
629                 ConfigListScreen.keyRight(self)
630                 if self.encoder is not None and (self["config"].getCurrent() == self.encoder) or self.automode is not None and (self["config"].getCurrent() == self.automode):
631                         self.createSetup()
632
633         def cancelConfirm(self, result):
634                 if not result:
635                         return
636
637                 configs = config.plugins.transcodingsetup.dict()
638
639                 for (configName, configElement) in configs.items():
640                         if configName.startswith("automode"):
641                                 continue
642                         configElement.cancel()
643
644                 for (configName, configElement) in configs.items():
645                         if configName.startswith("automode"):
646                                 configElement.cancel()
647
648                 self.close()
649
650         def keyCancel(self):
651                 transcodingsetupinit.pluginsetup = None
652                 if self["config"].isChanged():
653                         self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"))
654                 else:
655                         self.close()
656
657 def main(session, **kwargs):
658         session.open(TranscodingSetup)
659
660 def Plugins(**kwargs):
661         return [PluginDescriptor(name=_("TranscodingSetup"), description=_("Transcoding Setup"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=main)]
662
663 transcodingsetupinit = TranscodingSetupInit()
664