[transcoding setup] support filestreamproxy(8003).
[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 = "disable", 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                 print "[TranscodingSetup] set port ",port
103                 try:
104                         fp = file('/etc/inetd.conf', 'r')
105                         datas = fp.readlines()
106                         fp.close()
107                 except:
108 #                       print "file open error, inetd.conf!"
109                         self.showMessage("Set port failed.", MessageBox.TYPE_ERROR)
110                         return
111                 try:
112                         newdatas=""
113                         s_port = ""
114                         if port == "8001":
115                                 s_port = "8002"
116                         else:
117                                 s_port = "8001"
118                         for line in datas:
119                                 if line.find("transtreamproxy") != -1:
120                                         p=line.replace('\t',' ').find(' ')
121                                         line = port+line[p:]
122                                 elif line.find("filestreamproxy") != -1:
123                                         p=line.replace('\t',' ').find(' ')
124                                         line = "8003"+line[p:]
125                                 elif line.find("streamproxy") != -1:
126                                         p=line.replace('\t',' ').find(' ')
127                                         line = s_port+line[p:]
128                                 newdatas+=line
129
130                         if newdatas.find("transtreamproxy") == -1:
131                                 newdatas+=port+'\t'+'stream'+'\t'+'tcp'+'\t'+'nowait'+'\t'+'root'+'\t'+'/usr/bin/transtreamproxy'+'\t'+'transtreamproxy\n'
132                         if newdatas.find("filestreamproxy") == -1:
133                                 newdatas+='8003\t'+'stream'+'\t'+'tcp'+'\t'+'nowait'+'\t'+'root'+'\t'+'/usr/bin/filestreamproxy'+'\t'+'filestreamproxy\n'
134                         fd = file("/etc/inetd.conf",'w')
135                         fd.write(newdatas)
136                         fd.close()
137                 except:
138                         self.showMessage("Set port failed.", MessageBox.TYPE_ERROR)
139                         return
140                 self.inetdRestart()
141                 if config.plugins.transcodingsetup.transcoding.value == "enable" and port == "8001":
142                         msg = "Set port OK.\nPC Streaming is replaced with mobile streaming."
143                         self.showMessage(msg, MessageBox.TYPE_INFO)
144
145         def inetdRestart(self):
146                 if fileExists("/etc/init.d/inetd"):
147                         os_system("/etc/init.d/inetd restart")
148                 elif fileExists("/etc/init.d/inetd.busybox"):
149                         os_system("/etc/init.d/inetd.busybox restart")
150
151         def showMessage(self, msg, msgType):
152                 if self.pluginsetup:
153                         self.pluginsetup.showMessage(msg, msgType)
154
155 class TranscodingSetup(Screen,ConfigListScreen):
156         skin =  """
157                 <screen position="center,center" size="540,320">
158                         <ePixmap pixmap="skin_default/buttons/red.png" position="30,10" size="140,40" alphatest="on" />
159                         <ePixmap pixmap="skin_default/buttons/green.png" position="200,10" size="140,40" alphatest="on" />
160                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="370,10" size="140,40" alphatest="on" />
161                         <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" />
162                         <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" />
163                         <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" />
164                         <widget name="config" zPosition="2" position="20,70" size="500,120" scrollbarMode="showOnDemand" transparent="1" />
165                         <widget source="text" render="Label" position="30,190" size="480,130" font="Regular;18" halign="center" valign="center" />
166                 </screen>
167                 """
168
169         def __init__(self,session):
170                 Screen.__init__(self,session)
171                 self.setTitle(_("Transcoding Setup"))
172                 TEXT = _("Transcoding can be started when there is no corresponding channel recordings.")
173                 if getModel() == "solo2":
174                         TEXT += _("\nWhen transcoding, both PIP and analog video outputs are disabled.")
175                 else:
176                         TEXT += _("\nWhen transcoding, PIP is disabled.")
177                 self.session = session
178                 self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ],
179                 {
180                         "ok": self.keySave,
181                         "cancel": self.keyCancel,
182                         "red": self.keyCancel,
183                         "green": self.keySave,
184                         "yellow" : self.KeyDefault,
185                 }, -2)
186                 self.list = []
187                 ConfigListScreen.__init__(self, self.list,session = self.session)
188                 self["key_red"] = StaticText(_("Cancel"))
189                 self["key_green"] = StaticText(_("Save"))
190                 self["key_yellow"] = StaticText(_("Default"))
191                 self["text"] = StaticText(_("%s")%TEXT)
192                 self.createSetup()
193                 self.onLayoutFinish.append(self.checkEncoder)
194                 self.invaliedModelTimer = eTimer()
195                 self.invaliedModelTimer.callback.append(self.invalidmodel)
196                 global transcodingsetupinit
197                 transcodingsetupinit.pluginsetup = self
198                 self.onClose.append(self.onClosed)
199
200         def onClosed(self):
201                 transcodingsetupinit.pluginsetup = None
202
203         def checkEncoder(self):
204                 if not fileExists("/proc/stb/encoder/enable"):
205                         self.invaliedModelTimer.start(100,True)
206
207         def invalidmodel(self):
208                 self.session.openWithCallback(self.close, MessageBox, _("This model is not support transcoding."), MessageBox.TYPE_ERROR)
209
210         def createSetup(self):
211                 self.list = []
212                 self.transcoding = getConfigListEntry(_("Transcoding"), config.plugins.transcodingsetup.transcoding)
213                 self.list.append( self.transcoding )
214                 if config.plugins.transcodingsetup.transcoding.value == "enable":
215                         self.list.append(getConfigListEntry(_("Port"), config.plugins.transcodingsetup.port))
216                         if hasattr(config.plugins.transcodingsetup, "bitrate"):
217                                 self.list.append(getConfigListEntry(_("Bitrate"), config.plugins.transcodingsetup.bitrate))
218                         if hasattr(config.plugins.transcodingsetup, "framerate"):
219                                 self.list.append(getConfigListEntry(_("Framerate"), config.plugins.transcodingsetup.framerate))
220                 self["config"].list = self.list
221                 self["config"].l.setList(self.list)
222
223         def showMessage(self, msg, msgType = MessageBox.TYPE_ERROR):
224                 self.session.open(MessageBox, _(msg), msgType)
225
226         def keySave(self):
227                 self.saveAll()
228                 self.close()
229
230         def KeyDefault(self):
231                 config.plugins.transcodingsetup.port.value = config.plugins.transcodingsetup.port.default
232                 if hasattr(config.plugins.transcodingsetup, "bitrate"):
233                         config.plugins.transcodingsetup.bitrate.value = config.plugins.transcodingsetup.bitrate.default
234                 if hasattr(config.plugins.transcodingsetup, "framerate"):
235                         config.plugins.transcodingsetup.framerate.value = config.plugins.transcodingsetup.framerate.default
236                 self.createSetup()
237
238         def resetConfig(self):
239                 for x in self["config"].list:
240                         x[1].cancel()
241
242         def keyLeft(self):
243                 ConfigListScreen.keyLeft(self)
244                 if self["config"].getCurrent() == self.transcoding:
245                         self.createSetup()
246
247         def keyRight(self):
248                 ConfigListScreen.keyRight(self)
249                 if self["config"].getCurrent() == self.transcoding:
250                         self.createSetup()
251
252         def cancelConfirm(self, result):
253                 if not result:
254                         return
255                 configlist = []
256                 configlist.append(config.plugins.transcodingsetup.transcoding)
257                 configlist.append(config.plugins.transcodingsetup.port)
258                 configlist.append(config.plugins.transcodingsetup.bitrate)
259                 configlist.append(config.plugins.transcodingsetup.framerate)
260                 for x in configlist:
261                         x.cancel()
262                 self.close()
263
264         def keyCancel(self):
265                 transcodingsetupinit.pluginsetup = None
266                 if self["config"].isChanged():
267                         self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"))
268                 else:
269                         self.close()
270
271 def main(session, **kwargs):
272         session.open(TranscodingSetup)
273
274 def Plugins(**kwargs):
275         return [PluginDescriptor(name=_("TranscodingSetup"), description=_("Transcoding Setup"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=main)]
276
277 transcodingsetupinit = TranscodingSetupInit()
278