hide activation item on UI and modify inetd.conf parser.
[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 transcodingsetupinit = None
14
15 def getModel():
16         filename = "/proc/stb/info/vumodel"
17         if fileExists(filename):
18                 return file(filename).read().strip()
19         return ""
20
21 config.plugins.transcodingsetup = ConfigSubsection()
22 config.plugins.transcodingsetup.transcoding = ConfigSelection(default = "enable", choices = [ ("enable", _("enable")), ("disable", _("disable"))] )
23 config.plugins.transcodingsetup.port = ConfigSelection(default = "8002", choices = [ ("8001", "8001"), ("8002", "8002")] )
24 if fileExists("/proc/stb/encoder/0/bitrate"):
25         if getModel() == "solo2":
26                 config.plugins.transcodingsetup.bitrate = ConfigInteger(default = 400000, limits = (50000, 1000000))
27         else:
28                 config.plugins.transcodingsetup.bitrate = ConfigInteger(default = 2000000, limits = (100000, 5000000))
29 if fileExists("/proc/stb/encoder/0/framerate"):
30         config.plugins.transcodingsetup.framerate = ConfigSelection(default = "30000", choices = [ ("23976", _("23976")), ("24000", _("24000")), ("25000", _("25000")), ("29970", _("29970")), ("30000", _("30000")), ("50000", _("50000")), ("59940", _("59940")), ("60000", _("60000"))])
31
32 class TranscodingSetupInit:
33         def __init__(self):
34                 self.pluginsetup = None
35                 #config.plugins.transcodingsetup.transcoding.addNotifier(self.setTranscoding)
36                 config.plugins.transcodingsetup.port.addNotifier(self.setPort)
37                 if hasattr(config.plugins.transcodingsetup, "bitrate"):
38                         config.plugins.transcodingsetup.bitrate.addNotifier(self.setBitrate)
39                 if hasattr(config.plugins.transcodingsetup, "framerate"):
40                         config.plugins.transcodingsetup.framerate.addNotifier(self.serFramerate)
41
42         def setConfig(self, procPath, value):
43                 if not fileExists(procPath):
44                         return -1
45                 if isinstance(value, str):
46                         value = value.strip(' ').strip('\n')
47                 else:
48                         value = str(value)
49                 try:
50                         fd = open(procPath,'r')
51                         oldValue = fd.read().strip(' ').strip('\n')
52                         fd.close()
53                         if oldValue != value:
54                                 print "[TranscodingSetup] set %s "%procPath, value
55                                 fd = open(procPath,'w')
56                                 fd.write(value)
57                                 fd.close()
58                                 fd = open(procPath,'r')
59                                 setvalue = fd.read().strip(' ').strip('\n')
60                                 fd.close()
61                                 if value != setvalue:
62                                         print "[TranscodingSetup] set failed. (%s > %s)" % ( value, procPath )
63                                         return -1
64                                 return 0
65                 except:
66                         print "setConfig exception error (%s > %s)" % ( value, procPath )
67                         return -1
68
69         def setTranscoding(self, configElement):
70                 encoder = configElement.value
71                 procPath = "/proc/stb/encoder/enable"
72                 if self.setConfig(procPath, encoder):
73                         self.showMessage("Set encoder %s failed."%encoder, MessageBox.TYPE_ERROR)
74                 elif encoder == "enable" and config.plugins.transcodingsetup.port.value == "8001":
75                         msg = "OK. Encoder enable.\nPC Streaming is replaced with mobile streaming."
76                         self.showMessage(msg, MessageBox.TYPE_INFO)
77                 else:
78                         self.showMessage("OK. Encoder %s."%encoder, MessageBox.TYPE_INFO)
79                         if encoder == "disable":
80                                 config.plugins.transcodingsetup.port.value = "8002"
81
82         def setBitrate(self, configElement):
83                 bitrate = configElement.value
84                 procPath = "/proc/stb/encoder/0/bitrate"
85                 if self.setConfig(procPath, bitrate):
86                         fd = open(procPath,'r')
87                         curValue = fd.read().strip(' ').strip('\n')
88                         fd.close()
89                         if curValue.isdigit():
90                                 config.plugins.transcodingsetup.bitrate.value = int(curValue)
91                                 config.plugins.transcodingsetup.bitrate.save()
92                         self.showMessage("Set bitrate failed.", MessageBox.TYPE_ERROR)
93
94         def serFramerate(self, configElement):
95                 framerate = configElement.value
96                 procPath = "/proc/stb/encoder/0/framerate"
97                 if self.setConfig(procPath, framerate):
98                         self.showMessage("Set framerate failed.", MessageBox.TYPE_ERROR)
99
100         def setPort(self, configElement):
101                 port = configElement.value
102                 port2 = (port == "8001") and "8002" or "8001"
103
104                 print "[TranscodingSetup] set port ",port
105                 try:
106                         newConfigData = ""
107                         oldConfigData = file('/etc/inetd.conf').read()
108                         for L in oldConfigData.splitlines():
109                                 try:
110                                         if L[0] == '#':
111                                                 newConfigData += L + '\n'
112                                                 continue
113                                 except: continue
114                                 LL = L.split()
115                                 if LL[5] == '/usr/bin/streamproxy':
116                                         LL[0] = port2
117                                 elif LL[5] == '/usr/bin/transtreamproxy':
118                                         LL[0] = port
119                                 newConfigData += ''.join(str(X) + " " for X in LL) + '\n'
120
121                         if newConfigData.find("transtreamproxy") == -1:
122                                 newConfigData += port + " stream tcp nowait root /usr/bin/transtreamproxy transtreamproxy\n"
123                         file('/etc/inetd.conf', 'w').write(newConfigData)
124                 except:
125                         self.showMessage("Set port failed.", MessageBox.TYPE_ERROR)
126                         return
127
128                 self.inetdRestart()
129                 if config.plugins.transcodingsetup.transcoding.value == "enable" and port == "8001":
130                         msg = "Set port OK.\nPC Streaming is replaced with mobile streaming."
131                         self.showMessage(msg, MessageBox.TYPE_INFO)
132
133         def inetdRestart(self):
134                 if fileExists("/etc/init.d/inetd"):
135                         os_system("/etc/init.d/inetd restart")
136                 elif fileExists("/etc/init.d/inetd.busybox"):
137                         os_system("/etc/init.d/inetd.busybox restart")
138
139         def showMessage(self, msg, msgType):
140                 if self.pluginsetup:
141                         self.pluginsetup.showMessage(msg, msgType)
142
143 class TranscodingSetup(Screen,ConfigListScreen):
144         skin =  """
145                 <screen position="center,center" size="540,320">
146                         <ePixmap pixmap="skin_default/buttons/red.png" position="30,10" size="140,40" alphatest="on" />
147                         <ePixmap pixmap="skin_default/buttons/green.png" position="200,10" size="140,40" alphatest="on" />
148                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="370,10" size="140,40" alphatest="on" />
149                         <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" />
150                         <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" />
151                         <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" />
152                         <widget name="config" zPosition="2" position="20,70" size="500,120" scrollbarMode="showOnDemand" transparent="1" />
153                         <widget source="text" render="Label" position="30,190" size="480,130" font="Regular;18" halign="center" valign="center" />
154                 </screen>
155                 """
156
157         def __init__(self,session):
158                 Screen.__init__(self,session)
159                 self.setTitle(_("Transcoding Setup"))
160                 TEXT = _("Transcoding can be started when there is no corresponding channel recordings.")
161                 if getModel() == "solo2":
162                         TEXT += _("\nWhen transcoding, both PIP and analog video outputs are disabled.")
163                 else:
164                         TEXT += _("\nWhen transcoding, PIP is disabled.")
165                 self.session = session
166                 self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ],
167                 {
168                         "ok": self.keySave,
169                         "cancel": self.keyCancel,
170                         "red": self.keyCancel,
171                         "green": self.keySave,
172                         "yellow" : self.KeyDefault,
173                 }, -2)
174                 self.list = []
175                 ConfigListScreen.__init__(self, self.list,session = self.session)
176                 self["key_red"] = StaticText(_("Cancel"))
177                 self["key_green"] = StaticText(_("Save"))
178                 self["key_yellow"] = StaticText(_("Default"))
179                 self["text"] = StaticText(_("%s")%TEXT)
180                 self.createSetup()
181                 self.onLayoutFinish.append(self.checkEncoder)
182                 self.invaliedModelTimer = eTimer()
183                 self.invaliedModelTimer.callback.append(self.invalidmodel)
184                 global transcodingsetupinit
185                 transcodingsetupinit.pluginsetup = self
186                 self.onClose.append(self.onClosed)
187
188         def onClosed(self):
189                 transcodingsetupinit.pluginsetup = None
190
191         def checkEncoder(self):
192                 if not fileExists("/proc/stb/encoder/enable"):
193                         self.invaliedModelTimer.start(100,True)
194
195         def invalidmodel(self):
196                 self.session.openWithCallback(self.close, MessageBox, _("This model is not support transcoding."), MessageBox.TYPE_ERROR)
197
198         def createSetup(self):
199                 self.list = []
200                 #self.transcoding = getConfigListEntry(_("Transcoding"), config.plugins.transcodingsetup.transcoding)
201                 #self.list.append( self.transcoding )
202                 if config.plugins.transcodingsetup.transcoding.value == "enable":
203                         self.list.append(getConfigListEntry(_("Port"), config.plugins.transcodingsetup.port))
204                         if hasattr(config.plugins.transcodingsetup, "bitrate"):
205                                 self.list.append(getConfigListEntry(_("Bitrate"), config.plugins.transcodingsetup.bitrate))
206                         if hasattr(config.plugins.transcodingsetup, "framerate"):
207                                 self.list.append(getConfigListEntry(_("Framerate"), config.plugins.transcodingsetup.framerate))
208                 self["config"].list = self.list
209                 self["config"].l.setList(self.list)
210
211         def showMessage(self, msg, msgType = MessageBox.TYPE_ERROR):
212                 self.session.open(MessageBox, _(msg), msgType)
213
214         def keySave(self):
215                 self.saveAll()
216                 self.close()
217
218         def KeyDefault(self):
219                 config.plugins.transcodingsetup.port.value = config.plugins.transcodingsetup.port.default
220                 if hasattr(config.plugins.transcodingsetup, "bitrate"):
221                         config.plugins.transcodingsetup.bitrate.value = config.plugins.transcodingsetup.bitrate.default
222                 if hasattr(config.plugins.transcodingsetup, "framerate"):
223                         config.plugins.transcodingsetup.framerate.value = config.plugins.transcodingsetup.framerate.default
224                 self.createSetup()
225
226         def resetConfig(self):
227                 for x in self["config"].list:
228                         x[1].cancel()
229
230         def keyLeft(self):
231                 ConfigListScreen.keyLeft(self)
232                 #if self["config"].getCurrent() == self.transcoding:
233                 #       self.createSetup()
234
235         def keyRight(self):
236                 ConfigListScreen.keyRight(self)
237                 #if self["config"].getCurrent() == self.transcoding:
238                 #       self.createSetup()
239
240         def cancelConfirm(self, result):
241                 if not result:
242                         return
243                 configlist = []
244                 configlist.append(config.plugins.transcodingsetup.transcoding)
245                 configlist.append(config.plugins.transcodingsetup.port)
246                 configlist.append(config.plugins.transcodingsetup.bitrate)
247                 configlist.append(config.plugins.transcodingsetup.framerate)
248                 for x in configlist:
249                         x.cancel()
250                 self.close()
251
252         def keyCancel(self):
253                 transcodingsetupinit.pluginsetup = None
254                 if self["config"].isChanged():
255                         self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"))
256                 else:
257                         self.close()
258
259 def main(session, **kwargs):
260         session.open(TranscodingSetup)
261
262 def Plugins(**kwargs):
263         return [PluginDescriptor(name=_("TranscodingSetup"), description=_("Transcoding Setup"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=main)]
264
265 transcodingsetupinit = TranscodingSetupInit()
266