TranscodingSetup : add default button
[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
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
10 from os import system as os_system
11 from __init__ import _
12
13 error_msg ={
14         -1 : "File not exist - /proc/stb/encoder/enable.",
15         -2 : "File not exist - /etc/inetd.conf.",
16         -3 : "File open error - /proc/stb/encoder/enable.",
17         -4 : "File open error - /etc/inetd.conf.",
18         -5 : "Set encoder error.",
19         -6 : "Set port error.",
20         -7 : "Setting value is incorrect.",
21         -8 : "Set encoder bitrate error.",
22         -9 : "Set encoder framerate error.",
23 }
24 TranscodingConfigList = []
25
26 class TranscodingSetupInit:
27         def __init__(self):
28                 self.createConfigList()
29                 self.createConfig()
30                 self.transcoding_value = config.plugins.transcodingsetup.transcoding.value
31                 if self.transcoding_value == "disable":
32                         self.port_value = "8002"
33                 else:
34                         self.port_value = config.plugins.transcodingsetup.port.value
35                 self.transcoding_old = config.plugins.transcodingsetup.transcoding.value
36                 res = self.setTranscoding(self.transcoding_value, self.port_value)
37                 if res is not None and res < 0:
38                         print "[TranscodingSetup] set failed!(%s, %s, %d)"%(self.transcoding_value, self.port_value, res)
39
40         def createConfigList(self):
41                 global TranscodingConfigList
42                 configList = [
43                         ["Bitrate", "/proc/stb/encoder/0/bitrate", -8],
44                         ["Framerate", "/proc/stb/encoder/0/framerate", -9]
45                 ]
46                 for x in configList:
47                         if fileExists(x[1]):
48                                 TranscodingConfigList.append(x)
49
50         def getModel(self):
51                 if fileExists("/proc/stb/info/vumodel"):
52                         fd = open("/proc/stb/info/vumodel")
53                         vumodel=fd.read().strip()
54                         fd.close()
55                         return vumodel
56                 else:
57                         return False
58
59         def createConfig(self):
60                 config.plugins.transcodingsetup = ConfigSubsection()
61                 config.plugins.transcodingsetup.transcoding = ConfigSelection(default = "disable", choices = [ ("enable", _("enable")), ("disable", _("disable"))] )
62                 config.plugins.transcodingsetup.port = ConfigSelection(default = "8002", choices = [ ("8001", "8001"), ("8002", "8002")] )
63                 global TranscodingConfigList
64                 for x in TranscodingConfigList:
65                         if x[0] == "Bitrate":
66                                 if self.getModel() == "solo2":
67                                         config.plugins.transcodingsetup.bitrate = ConfigInteger(default = 400000, limits = (50000, 1000000))
68                                 else:
69                                         config.plugins.transcodingsetup.bitrate = ConfigInteger(default = 2000000, limits = (100000, 5000000))
70                                 x.append(config.plugins.transcodingsetup.bitrate)
71                         elif x[0] == "Framerate":
72                                 config.plugins.transcodingsetup.framerate = ConfigSelection(default = "30000", choices = [ ("23976", _("23976")), ("24000", _("24000")), ("25000", _("25000")), ("29970", _("29970")), ("30000", _("30000")), ("50000", _("50000")), ("59940", _("59940")), ("60000", _("60000"))])
73                                 x.append(config.plugins.transcodingsetup.framerate)
74
75         def setTranscoding(self, transcoding, port):
76                 if transcoding not in ["enable","disable"] or port not in ["8001","8002"]:
77 #                       print "Input error."
78                         return -7
79                 if not fileExists("/proc/stb/encoder/enable"):
80                         return -1
81                 elif not fileExists("/etc/inetd.conf"):
82                         return -2
83                 res = self.setEncoderExtra()
84                 if res < 0:
85                         return res
86                 if self.setEncoderEnable(transcoding) < 0:
87                         return -5
88                 res = self.setPort(port)
89                 if res < 0:
90                         self.setEncoderEnable(self.transcoding_old)
91                         return res
92                 else:
93                         self.inetdRestart()
94                 return res
95
96         def setEncoderEnable(self,mode = "disable"):
97 #               print "<TranscodingSetup> set encoder %s" % mode
98                 mode = mode.strip(' ').strip('\n')
99                 try:
100                         fd = open("/proc/stb/encoder/enable",'r')
101                         self.transcoding_old = fd.read()
102                         fd.close()
103                         fd = open("/proc/stb/encoder/enable",'w')
104                         fd.write(mode)
105                         fd.close()
106                         fd = open("/proc/stb/encoder/enable",'r')
107                         encoder_enable = fd.read().strip(' ').strip('\n')
108                         fd.close()
109                         if encoder_enable == mode:
110                                 return 0
111                         else:
112 #                               print "<TranscodingSetup> can not setting."
113                                 return -1
114                 except:
115 #                       print "setEncoderEnable exception error"
116                         return -1
117
118         def setPort(self, port = "8001"):
119 #               print "<TranscodingSetup> set port %s" % port
120                 try:
121                         fp = file('/etc/inetd.conf', 'r')
122                         datas = fp.readlines()
123                         fp.close()
124                 except:
125 #                       print "file open error, inetd.conf!"
126                         return -4
127                 try:
128                         newdatas=""
129                         s_port = ""
130                         if port == "8001":
131                                 s_port = "8002"
132                         else:
133                                 s_port = "8001"
134                         for line in datas:
135                                 if line.find("transtreamproxy") != -1:
136                                         p=line.replace('\t',' ').find(' ')
137                                         line = port+line[p:]
138                                 elif line.find("streamproxy") != -1:
139                                         p=line.replace('\t',' ').find(' ')
140                                         line = s_port+line[p:]
141                                 newdatas+=line
142
143                         if newdatas.find("transtreamproxy") == -1:
144                                 newdatas+=port+'\t'+'stream'+'\t'+'tcp'+'\t'+'nowait'+'\t'+'root'+'\t'+'/usr/bin/transtreamproxy'+'\t'+'transtreamproxy\n'
145                         fd = file("/etc/inetd.conf",'w')
146                         fd.write(newdatas)
147                         fd.close()
148                 except:
149                         return -6
150                 return 0
151
152         def inetdRestart(self):
153                 if fileExists("/etc/init.d/inetd"):
154                         os_system("/etc/init.d/inetd restart")
155                 elif fileExists("/etc/init.d/inetd.busybox"):
156                         os_system("/etc/init.d/inetd.busybox restart")
157
158         def setEncoderExtra(self):
159                 global TranscodingConfigList
160                 for x in TranscodingConfigList:
161                         if self.setEncoder(x[1], x[3].value):
162                                 return x[2]
163                 return 0
164
165         def setEncoder(self, procPath, value):
166 #               print "<TranscodingSetup> set %s "%procPath, value
167                 if not fileExists(procPath):
168                         return -1
169                 if isinstance(value, str):
170                         value = value.strip(' ').strip('\n')
171                 else:
172                         value = str(value)
173                 try:
174                         fd = open(procPath,'r')
175                         old_value = fd.read().strip(' ').strip('\n')
176                         fd.close()
177                         if old_value != value:
178                                 print "<TranscodingSetup> set %s "%procPath, value
179                                 fd = open(procPath,'w')
180                                 fd.write(value)
181                                 fd.close()
182                                 fd = open(procPath,'r')
183                                 encoder_value = fd.read().strip(' ').strip('\n')
184                                 fd.close()
185                                 if encoder_value != value:
186                                         return -1
187                         return 0
188                 except:
189                         return -1
190
191 class TranscodingSetup(Screen,ConfigListScreen, TranscodingSetupInit):
192         skin =  """
193                 <screen position="center,center" size="540,320">
194                         <ePixmap pixmap="skin_default/buttons/red.png" position="30,10" size="140,40" alphatest="on" />
195                         <ePixmap pixmap="skin_default/buttons/green.png" position="200,10" size="140,40" alphatest="on" />
196                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="370,10" size="140,40" alphatest="on" />
197                         <widget source="key_red" render="Label" position="30,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
198                         <widget source="key_green" render="Label" position="200,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
199                         <widget source="key_yellow" render="Label" position="370,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
200                         <widget name="config" zPosition="2" position="20,70" size="500,120" scrollbarMode="showOnDemand" transparent="1" />
201                         <widget source="text" render="Label" position="30,190" size="480,130" font="Regular;18" halign="center" valign="center" />
202                 </screen>
203                 """
204
205         def __init__(self,session):
206                 Screen.__init__(self,session)
207                 self.setTitle(_("Transcoding Setup"))
208                 TEXT = _("Transcoding can be started when there is no corresponding channel recordings.")
209                 if self.getModel() == "solo2":
210                         TEXT += _("\nWhen transcoding, both PIP and analog video outputs are disabled.")
211                 else:
212                         TEXT += _("\nWhen transcoding, PIP is disabled.")
213                 self.session = session
214                 self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ],
215                 {
216                         "ok": self.keySave,
217                         "cancel": self.keyCancel,
218                         "red": self.keyCancel,
219                         "green": self.keySave,
220                         "yellow" : self.KeyDefault,
221                 }, -2)
222                 self.list = []
223                 ConfigListScreen.__init__(self, self.list,session = self.session)
224                 self["key_red"] = StaticText(_("Cancel"))
225                 self["key_green"] = StaticText(_("Ok"))
226                 self["key_yellow"] = StaticText(_("Default"))
227                 self["text"] = StaticText(_("%s")%TEXT)
228                 self.createSetup()
229                 self.onLayoutFinish.append(self.checkEncoder)
230                 self.invaliedModelTimer = eTimer()
231                 self.invaliedModelTimer.callback.append(self.invalidmodel)
232
233         def getModel(self):
234                 if fileExists("/proc/stb/info/vumodel"):
235                         fd = open("/proc/stb/info/vumodel")
236                         vumodel=fd.read().strip()
237                         fd.close()
238                         return vumodel
239                 else:
240                         return ""
241
242         def checkEncoder(self):
243                 if not fileExists("/proc/stb/encoder/enable"):
244                         self.invaliedModelTimer.start(100,True)
245
246         def invalidmodel(self):
247                 self.session.openWithCallback(self.close, MessageBox, _("This model is not support transcoding."), MessageBox.TYPE_ERROR)
248
249         def createSetup(self):
250                 global TranscodingConfigList
251                 self.list = []
252                 self.transcoding = getConfigListEntry(_("Transcoding"), config.plugins.transcodingsetup.transcoding)
253                 self.port = getConfigListEntry(_("Port"), config.plugins.transcodingsetup.port)
254                 self.list.append( self.transcoding )
255                 if config.plugins.transcodingsetup.transcoding.value == "enable":
256                         self.list.append( self.port )
257                         for x in TranscodingConfigList:
258                                 self.list.append(getConfigListEntry(_(x[0]), x[3]))
259
260                 self["config"].list = self.list
261                 self["config"].l.setList(self.list)
262
263         def keySave(self):
264                 transcoding = config.plugins.transcodingsetup.transcoding.value
265                 port = config.plugins.transcodingsetup.port.value
266 #               print "<TranscodingSetup> Transcoding %s(port : %s)"%(transcoding, port)
267                 ret = self.setupTranscoding(transcoding, port)
268                 if ret is not None and ret <0 :
269                         self.resetConfig()
270                         global error_msg
271                         self.session.openWithCallback(self.close, MessageBox, _("Failed, Encoder %s\n(%s).")%(transcoding, error_msg[ret]), MessageBox.TYPE_ERROR)
272                 else:
273                         self.saveAll()
274                         if transcoding == "enable" and port == "8001" :
275                                 text = "PC Streaming is replaced with mobile streaming."
276                                 self.session.openWithCallback(self.close, MessageBox, _("OK. Encoder %s.\n%s")%(transcoding,text), MessageBox.TYPE_INFO)
277                         else:
278                                 self.session.openWithCallback(self.close, MessageBox, _("OK. Encoder %s.")%transcoding, MessageBox.TYPE_INFO)
279                         self.close()
280
281         def KeyDefault(self):
282                 config.plugins.transcodingsetup.port.value = config.plugins.transcodingsetup.port.default
283                 global TranscodingConfigList
284                 for x in TranscodingConfigList:
285                          if x[0] == "Bitrate":
286                                 config.plugins.transcodingsetup.bitrate.value = config.plugins.transcodingsetup.bitrate.default
287                          elif x[0] == "Framerate":
288                                 config.plugins.transcodingsetup.framerate.value = config.plugins.transcodingsetup.framerate.default
289                 self.createSetup()
290
291         def resetConfig(self):
292                 for x in self["config"].list:
293                         x[1].cancel()
294
295         def setupTranscoding(self, transcoding = None, port = None):
296                 if transcoding == "disable":
297                         config.plugins.transcodingsetup.port.value = "8002"
298                         port = "8002"
299                 return self.setTranscoding(transcoding, port)
300
301         def keyLeft(self):
302                 ConfigListScreen.keyLeft(self)
303                 if self["config"].getCurrent() == self.transcoding:
304                         self.createSetup()
305
306         def keyRight(self):
307                 ConfigListScreen.keyRight(self)
308                 if self["config"].getCurrent() == self.transcoding:
309                         self.createSetup()
310
311 def main(session, **kwargs):
312         session.open(TranscodingSetup)
313
314 def Plugins(**kwargs):
315         return [PluginDescriptor(name=_("TranscodingSetup"), description=_("Transcoding Setup"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=main)]
316
317 transcodingsetupinit = TranscodingSetupInit()
318