Ejemplo n.º 1
0
	def loadIOPlaylist(self):
		playlistFile = "playlist_%s.e2pls" % (self._playlist_string)
		playlistIOInternal = PlaylistIOInternal()
		items = playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, playlistFile))
		if items:
			for x in items:
				self._playlist.add(x.ref, isBatch=True)
			self._playlist.listChanged()
Ejemplo n.º 2
0
 def loadIOPlaylist(self):
     playlistFile = "playlist_%s.e2pls" % (self._playlist_string)
     playlistIOInternal = PlaylistIOInternal()
     items = playlistIOInternal.open(
         resolveFilename(SCOPE_CONFIG, playlistFile))
     if items:
         for x in items:
             self._playlist.add(x.ref, isBatch=True)
         self._playlist.listChanged()
Ejemplo n.º 3
0
class MediaPlayer(Screen, InfoBarBase, InfoBarScreenSaver, InfoBarSeek, InfoBarAudioSelection, InfoBarCueSheetSupport, InfoBarNotifications, InfoBarSubtitleSupport, HelpableScreen, InfoBarAspectSelection):
	ALLOW_SUSPEND = True
	ENABLE_RESUME_SUPPORT = True
	FLAG_CENTER_DVB_SUBS = 2048

	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarAspectSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarScreenSaver.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.session.nav.stopService()

		self.setTitle(_("Media player"))

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(dts|mp3|wav|wave|wv|oga|ogg|flac|m4a|mp2|m2a|wma|ac3|mka|aac|ape|alac|mpg|vob|m4v|mkv|avi|divx|dat|flv|mp4|mov|wmv|asf|3gp|3g2|mpeg|mpe|rm|rmvb|ogm|ogv|m2ts|mts|ts|m3u|e2pls|pls|amr|au|mid|pva|wtv)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self.playlistname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		try:
			from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
			hotplugNotifier.append(self.hotplugCB)
		except Exception as ex:
			print("[MediaPlayer] No hotplug support", ex)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"ok": (self.ok, _("Add file to playlist")),
				"cancel": (self.exit, _("Exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions",
			{
				"play": (self.xplayEntry, _("Play entry")),
				"pause": (self.pauseEntry, _("Pause")),
				"stop": (self.stopEntry, _("Stop entry")),
				"previous": (self.previousMarkOrEntry, _("Play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("Play from next mark or playlist entry")),
				"menu": (self.showMenu, _("Menu")),
				"skipListbegin": (self.skip_listbegin, _("Jump to beginning of list")),
				"skipListend": (self.skip_listend, _("Jump to end of list")),
				"prevBouquet": (self.prevBouquet, self.prevBouquetHelpText),
				"nextBouquet": (self.nextBouquet, self.nextBouquetHelptext),
				"delete": (self.deletePlaylistEntry, _("Delete playlist entry")),
				"shift_stop": (self.clear_playlist, _("Clear playlist")),
				"shift_record": (self.playlist.PlayListShuffle, _("Shuffle playlist")),
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions",
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"],
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.mediaPlayerInfoBar = self.session.instantiateDialog(MediaPlayerInfoBar)

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)
		self.onShow.append(self.timerHideMediaPlayerInfoBar)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.hideMediaPlayerInfoBar = eTimer()
		self.hideMediaPlayerInfoBar.callback.append(self.timerHideMediaPlayerInfoBar)

		self.currList = "filelist"
		self.isAudioCD = False
		self.ext = None
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})

		self.servicelist = None
		self.pipZapAvailable = False
		if InfoBar.instance is not None:
			self.servicelist = InfoBar.instance.servicelist
			if self.servicelist and hasattr(self.servicelist, 'dopipzap'):
				self.pipZapAvailable = SystemInfo.get("NumVideoDecoders", 1) > 1

	def prevBouquetHelpText(self):
		if not self.shown and self.isPiPzap():
			value = _("when PiPzap enabled zap channel up...")
		else:
			value = _("Switch between filelist/playlist")
		return value

	def nextBouquetHelptext(self):
		if not self.shown and self.isPiPzap():
			value = _("when PiPzap enabled zap channel down...")
		else:
			value = _("Switch between filelist/playlist")
		return value

	def hideAndInfoBar(self):
		self.hide()
		self.mediaPlayerInfoBar.show()
		if config.mediaplayer.alwaysHideInfoBar.value or self.ext not in AUDIO_EXTENSIONS and not self.isAudioCD:
			self.hideMediaPlayerInfoBar.start(5000, True)

	def timerHideMediaPlayerInfoBar(self):
		self.hideMediaPlayerInfoBar.stop()
		self.mediaPlayerInfoBar.hide()

	def doNothing(self):
		pass

	def createSummary(self):
		return MediaPlayerLCDScreen

	def exit(self):
		if self.mediaPlayerInfoBar.shown:
			self.timerHideMediaPlayerInfoBar()
		else:
			self.session.openWithCallback(self.exitCallback, MessageBox, _("Exit media player?"), simple = not self.shown)

	def exitCallback(self, answer):
		if answer:
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			if self.savePlaylistOnExit:
				try:
					self.playlistIOInternal.save(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
				except IOError:
					print("[MediaPlayer] couldn't save playlist.e2pls")
			if config.mediaplayer.saveDirOnExit.getValue():
				config.mediaplayer.defaultDir.setValue(self.filelist.getCurrentDirectory())
				config.mediaplayer.defaultDir.save()
			try:
				from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
				hotplugNotifier.remove(self.hotplugCB)
			except:
				pass
			del self["coverArt"].picload
			self.close()

	def checkSkipShowHideLock(self):
		self.updatedSeekState()

	def doEofInternal(self, playing):
		if playing:
			self.nextEntry()
		else:
			self.show()

	def __onClose(self):
		self.mediaPlayerInfoBar.doClose()
		self.session.nav.playService(self.oldService)

	def __evUpdatedInfo(self):
		currPlay = self.session.nav.getCurrentService()
		sTagTrackNumber = currPlay.info().getInfo(iServiceInformation.sTagTrackNumber)
		sTagTrackCount = currPlay.info().getInfo(iServiceInformation.sTagTrackCount)
		sTagTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
		if sTagTrackNumber or sTagTrackCount or sTagTitle:
			print("[MediaPlayer] __evUpdatedInfo title %d of %d (%s)" % (sTagTrackNumber, sTagTrackCount, sTagTitle))
		self.readTitleInformation()

	def __evAudioDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagAudioCodec = currPlay.info().getInfoString(iServiceInformation.sTagAudioCodec)
		print("[MediaPlayer] __evAudioDecodeError audio-codec %s can't be decoded by hardware" % (sTagAudioCodec))
		self.session.open(MessageBox, _("This receiver cannot decode %s streams!") % sTagAudioCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evVideoDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagVideoCodec = currPlay.info().getInfoString(iServiceInformation.sTagVideoCodec)
		print("[MediaPlayer] __evVideoDecodeError video-codec %s can't be decoded by hardware" % (sTagVideoCodec))
		self.session.open(MessageBox, _("This receiver cannot decode %s streams!") % sTagVideoCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		print("[MediaPlayer] __evPluginError" , message)
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )

	def delMPTimer(self):
		del self.rightKeyTimer
		del self.leftKeyTimer

	def readTitleInformation(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)

			if sTitle == "":
				if not self.isAudioCD:
					sTitle = currPlay.info().getName().split('/')[-1]
				else:
					sTitle = self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()].getName()

			if self.AudioCD_albuminfo:
				if sAlbum == "" and "title" in self.AudioCD_albuminfo:
					sAlbum = self.AudioCD_albuminfo["title"]
				if sGenre == "" and "genre" in self.AudioCD_albuminfo:
					sGenre = self.AudioCD_albuminfo["genre"]
				if sArtist == "" and "artist" in self.AudioCD_albuminfo:
					sArtist = self.AudioCD_albuminfo["artist"]
				if "year" in self.AudioCD_albuminfo:
					sYear = self.AudioCD_albuminfo["year"]

			self.updateMusicInformation( sArtist, sTitle, sAlbum, sYear, sGenre, clear = True )
		else:
			self.updateMusicInformation()

	def updateMusicInformation(self, artist = "", title = "", album = "", year = "", genre = "", clear = False):
		self.updateSingleMusicInformation("artist", artist, clear)
		self.updateSingleMusicInformation("title", title, clear)
		self.updateSingleMusicInformation("album", album, clear)
		self.updateSingleMusicInformation("year", year, clear)
		self.updateSingleMusicInformation("genre", genre, clear)

	def updateSingleMusicInformation(self, name, info, clear):
		if info != "" or clear:
			if self[name].getText() != info:
				self[name].setText(info)

	def leftDown(self):
		self.lefttimer = True
		self.leftKeyTimer.start(1000)

	def rightDown(self):
		self.righttimer = True
		self.rightKeyTimer.start(1000)

	def leftUp(self):
		if self.lefttimer:
			self.leftKeyTimer.stop()
			self.lefttimer = False
			self[self.currList].pageUp()
			self.updateCurrentInfo()

	def rightUp(self):
		if self.righttimer:
			self.rightKeyTimer.stop()
			self.righttimer = False
			self[self.currList].pageDown()
			self.updateCurrentInfo()

	def leftTimerFire(self):
		self.leftKeyTimer.stop()
		self.lefttimer = False
		self.switchToFileList()

	def rightTimerFire(self):
		self.rightKeyTimer.stop()
		self.righttimer = False
		self.switchToPlayList()

	def switchToFileList(self):
		self.currList = "filelist"
		self.filelist.selectionEnabled(1)
		self.playlist.selectionEnabled(0)
		self.updateCurrentInfo()

	def switchToPlayList(self):
		if len(self.playlist) != 0:
			self.currList = "playlist"
			self.filelist.selectionEnabled(0)
			self.playlist.selectionEnabled(1)
			self.updateCurrentInfo()

	def up(self):
		self[self.currList].up()
		self.updateCurrentInfo()

	def down(self):
		self[self.currList].down()
		self.updateCurrentInfo()

	def showAfterSeek(self):
		if not self.shown:
			self.hideAndInfoBar()

	def showAfterCuesheetOperation(self):
		self.show()

	def hideAfterResume(self):
		self.hideAndInfoBar()

	def getIdentifier(self, ref):
		if self.isAudioCD:
			return ref.getName()
		else:
			text = ref.getPath()
			return text.split('/')[-1]

	# FIXME: maybe this code can be optimized
	def updateCurrentInfo(self):
		text = ""
		if self.currList == "filelist":
			idx = self.filelist.getSelectionIndex()
			r = self.filelist.list[idx]
			text = r[1][7]
			if r[0][1] == True:
				if len(text) < 2:
					text += " "
				if text[:2] != "..":
					text = "/" + text
			self.summaries.setText(text,1)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

			text = ""
			if not self.filelist.canDescent():
				r = self.filelist.getServiceRef()
				if r is None:
					return
				text = r.getPath()
				self["currenttext"].setText(os.path.basename(text))

		if self.currList == "playlist":
			t = self.playlist.getSelection()
			if t is None:
				return
			#display current selected entry on LCD
			text = self.getIdentifier(t)
			self.summaries.setText(text,1)
			self["currenttext"].setText(text)
			idx = self.playlist.getSelectionIndex()
			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

	def ok(self):
		if self.currList == "filelist":
			if self.filelist.canDescent():
				self.filelist.descent()
				self.updateCurrentInfo()
			else:
				self.copyFile()

		if self.currList == "playlist":
			if self.playlist.getCurrentIndex() == self.playlist.getSelectionIndex() and not self.playlist.isStopped():
				if self.shown:
					self.hideAndInfoBar()
				elif self.mediaPlayerInfoBar.shown:
					self.mediaPlayerInfoBar.hide()
					self.hideMediaPlayerInfoBar.stop()
					if self.ext in AUDIO_EXTENSIONS or self.isAudioCD:
						self.show()
				else:
					self.mediaPlayerInfoBar.show()
			else:
				self.changeEntry(self.playlist.getSelectionIndex())

	def showMenu(self):
		menu = []
		if len(self.cdAudioTrackFiles):
			menu.insert(0,(_("Play audio-CD..."), "audiocd"))
		if self.currList == "filelist":
			if self.filelist.canDescent():
				menu.append((_("Add directory to playlist"), "copydir"))
			else:
				menu.append((_("Add files to playlist"), "copyfiles"))
			menu.append((_("Switch to playlist"), "playlist"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("Delete file"), "deletefile"))
		else:
			menu.append((_("Switch to filelist"), "filelist"))
			menu.append((_("Clear playlist"), "clear"))
			menu.append((_("Delete entry"), "deleteentry"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("Shuffle playlist"), "shuffle"))
		menu.append((_("Hide player"), "hide"))
		menu.append((_("Load playlist"), "loadplaylist"));
		if config.usage.setup_level.index >= 1: # intermediate+
			menu.append((_("Save playlist"), "saveplaylist"))
			menu.append((_("Delete saved playlist"), "deleteplaylist"))
			menu.append((_("Edit settings"), "settings"))
		if self.pipZapAvailable:
			menu.append((_("Menu") + " PiP", "pip"))
			if self.isPiPzap():
				menu.append((_("Open service list"), "servicelist"))
		self.timerHideMediaPlayerInfoBar()
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)

	def menuCallback(self, choice):
		self.show()
		if choice is None:
			return

		if choice[1] == "copydir":
			self.copyDirectory(self.filelist.getSelection()[0])
		elif choice[1] == "copyfiles":
			self.copyDirectory(os.path.dirname(self.filelist.getSelection()[0].getPath()) + "/", recursive = False)
		elif choice[1] == "playlist":
			self.switchToPlayList()
		elif choice[1] == "filelist":
			self.switchToFileList()
		elif choice[1] == "deleteentry":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()
		elif choice[1] == "clear":
			self.clear_playlist()
		elif choice[1] == "hide":
			self.hideAndInfoBar()
		elif choice[1] == "saveplaylist":
			self.save_playlist()
		elif choice[1] == "loadplaylist":
			self.load_playlist()
		elif choice[1] == "deleteplaylist":
			self.delete_saved_playlist()
		elif choice[1] == "shuffle":
			self.playlist.PlayListShuffle()
		elif choice[1] == "deletefile":
			self.deleteFile()
		elif choice[1] == "settings":
			self.session.openWithCallback(self.applySettings, MediaPlayerSettings, self)
		elif choice[1] == "audiocd":
			self.playAudioCD()
		elif choice[1] == "pip":
			self.activatePiP()
		elif choice[1] == "servicelist":
			self.openServiceList()

	def playAudioCD(self):
		from enigma import eServiceReference
		if len(self.cdAudioTrackFiles):
			self.playlist.clear()
			self.savePlaylistOnExit = False
			self.isAudioCD = True
			for x in self.cdAudioTrackFiles:
				ref = eServiceReference(4097, 0, x)
				self.playlist.addFile(ref)
			try:
				from Plugins.Extensions.CDInfo.plugin import Query
				cdinfo = Query(self)
				cdinfo.scan()
			except ImportError:
				pass # we can live without CDInfo
			self.changeEntry(0)
			self.switchToPlayList()

	def applySettings(self, answer=True):
		if answer is True:
			self.savePlaylistOnExit = config.mediaplayer.savePlaylistOnExit.getValue()
			if config.mediaplayer.repeat.getValue() == True:
				self["repeat"].setPixmapNum(1)
			else:
				self["repeat"].setPixmapNum(0)

	def showEventInformation(self):
		from Screens.EventView import EventViewSimple
		from ServiceReference import ServiceReference
		evt = self[self.currList].getCurrentEvent()
		if evt:
			self.session.open(EventViewSimple, evt, ServiceReference(self.getCurrent()))

	# also works on filelist (?)
	def getCurrent(self):
		return self["playlist"].getCurrent()

	def deletePlaylistEntry(self):
		if self.currList == "playlist":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()

	def skip_listbegin(self):
		if self.currList == "filelist":
			self.filelist.moveToIndex(0)
		else:
			self.playlist.moveToIndex(0)
		self.updateCurrentInfo()

	def skip_listend(self):
		if self.currList == "filelist":
			idx = len(self.filelist.list)
			self.filelist.moveToIndex(idx - 1)
		else:
			self.playlist.moveToIndex(len(self.playlist)-1)
		self.updateCurrentInfo()

	def save_playlist(self):
		self.session.openWithCallback(self.save_playlist2,InputBox, title=_("Please enter filename (empty = use current date)"),windowTitle = _("Save playlist"), text=self.playlistname)

	def save_playlist2(self, name):
		if name is not None:
			name = name.strip()
			if name == "":
				name = time.strftime("%y%m%d_%H%M%S")
			self.playlistname = name
			name += ".e2pls"
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			self.playlistIOInternal.save(resolveFilename(SCOPE_PLAYLIST) + name)

	def get_playlists(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os.listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError as e:
			print("[MediaPlayer] Error while scanning subdirs ",e)
		if config.mediaplayer.sortPlaylists.value:
			listpath.sort()
		return listpath

	def load_playlist(self):
		listpath = self.get_playlists()
		if listpath:
			self.session.openWithCallback(self.PlaylistSelected, ChoiceBox, title=_("Please select a playlist..."), list = listpath)
		else:
			self.session.open(MessageBox, _("There are no saved playlists to load!"), MessageBox.TYPE_ERROR)

	def PlaylistSelected(self,path):
		if path is not None:
			self.playlistname = path[0].rsplit('.',1)[-2]
			self.clear_playlist()
			extension = path[0].rsplit('.',1)[-1]
			if extension in self.playlistparsers:
				playlist = self.playlistparsers[extension]()
				list = playlist.open(path[1])
				for x in list:
					self.playlist.addFile(x.ref)
			self.playlist.updateList()

	def delete_saved_playlist(self):
		listpath = self.get_playlists()
		if listpath:
			self.session.openWithCallback(self.DeletePlaylistSelected, ChoiceBox, title=_("Please select a playlist to delete..."), list = listpath)
		else:
			self.session.open(MessageBox, _("There are no saved playlists to delete!"), MessageBox.TYPE_ERROR)

	def DeletePlaylistSelected(self,path):
		if path is not None:
			self.delname = path[1]
			self.session.openWithCallback(self.deleteConfirmed, MessageBox, _("Do you really want to delete %s?") % (path[1]))

	def deleteConfirmed(self, confirmed):
		if confirmed:
			try:
				os.remove(self.delname)
			except OSError,e:
				print("[MediaPlayer] delete failed:", e)
				self.session.open(MessageBox, _("Delete failed!"), MessageBox.TYPE_ERROR)
Ejemplo n.º 4
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarAspectSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarScreenSaver.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.session.nav.stopService()

		self.setTitle(_("Media player"))

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(dts|mp3|wav|wave|wv|oga|ogg|flac|m4a|mp2|m2a|wma|ac3|mka|aac|ape|alac|mpg|vob|m4v|mkv|avi|divx|dat|flv|mp4|mov|wmv|asf|3gp|3g2|mpeg|mpe|rm|rmvb|ogm|ogv|m2ts|mts|ts|m3u|e2pls|pls|amr|au|mid|pva|wtv)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self.playlistname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		try:
			from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
			hotplugNotifier.append(self.hotplugCB)
		except Exception as ex:
			print("[MediaPlayer] No hotplug support", ex)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"ok": (self.ok, _("Add file to playlist")),
				"cancel": (self.exit, _("Exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions",
			{
				"play": (self.xplayEntry, _("Play entry")),
				"pause": (self.pauseEntry, _("Pause")),
				"stop": (self.stopEntry, _("Stop entry")),
				"previous": (self.previousMarkOrEntry, _("Play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("Play from next mark or playlist entry")),
				"menu": (self.showMenu, _("Menu")),
				"skipListbegin": (self.skip_listbegin, _("Jump to beginning of list")),
				"skipListend": (self.skip_listend, _("Jump to end of list")),
				"prevBouquet": (self.prevBouquet, self.prevBouquetHelpText),
				"nextBouquet": (self.nextBouquet, self.nextBouquetHelptext),
				"delete": (self.deletePlaylistEntry, _("Delete playlist entry")),
				"shift_stop": (self.clear_playlist, _("Clear playlist")),
				"shift_record": (self.playlist.PlayListShuffle, _("Shuffle playlist")),
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions",
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"],
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.mediaPlayerInfoBar = self.session.instantiateDialog(MediaPlayerInfoBar)

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)
		self.onShow.append(self.timerHideMediaPlayerInfoBar)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.hideMediaPlayerInfoBar = eTimer()
		self.hideMediaPlayerInfoBar.callback.append(self.timerHideMediaPlayerInfoBar)

		self.currList = "filelist"
		self.isAudioCD = False
		self.ext = None
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})

		self.servicelist = None
		self.pipZapAvailable = False
		if InfoBar.instance is not None:
			self.servicelist = InfoBar.instance.servicelist
			if self.servicelist and hasattr(self.servicelist, 'dopipzap'):
				self.pipZapAvailable = SystemInfo.get("NumVideoDecoders", 1) > 1
Ejemplo n.º 5
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(mp2|mp3|ogg|ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|mov)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
		hotplugNotifier.append(self.hotplugCB)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", 
			{
				"ok": (self.ok, _("add file to playlist")),
				"cancel": (self.exit, _("exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", 
			{
				"play": (self.xplayEntry, _("play entry")),
				"pause": (self.pauseEntry, _("pause")),
				"stop": (self.stopEntry, _("stop entry")),
				"previous": (self.previousMarkOrEntry, _("play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("play from next mark or playlist entry")),
				"menu": (self.showMenu, _("menu")),
				"skipListbegin": (self.skip_listbegin, _("jump to listbegin")),
				"skipListend": (self.skip_listend, _("jump to listend")),
				"prevBouquet": (self.switchToPlayList, _("switch to playlist")),
				"nextBouquet": (self.switchToFileList, _("switch to filelist")),
				"delete": (self.deletePlaylistEntry, _("delete playlist entry")),
				"shift_stop": (self.clear_playlist, _("clear playlist")),
				"shift_record": (self.playlist.PlayListShuffle, _("shuffle playlist")),
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions", 
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"], 
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.currList = "filelist"
		self.isAudioCD = False
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})
Ejemplo n.º 6
0
class MediaPlayer(Screen, InfoBarBase, InfoBarSeek, InfoBarAudioSelection, InfoBarCueSheetSupport, InfoBarNotifications, InfoBarSubtitleSupport, HelpableScreen):
	ALLOW_SUSPEND = True
	ENABLE_RESUME_SUPPORT = True

	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(mp2|mp3|ogg|ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|mov)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
		hotplugNotifier.append(self.hotplugCB)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", 
			{
				"ok": (self.ok, _("add file to playlist")),
				"cancel": (self.exit, _("exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", 
			{
				"play": (self.xplayEntry, _("play entry")),
				"pause": (self.pauseEntry, _("pause")),
				"stop": (self.stopEntry, _("stop entry")),
				"previous": (self.previousMarkOrEntry, _("play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("play from next mark or playlist entry")),
				"menu": (self.showMenu, _("menu")),
				"skipListbegin": (self.skip_listbegin, _("jump to listbegin")),
				"skipListend": (self.skip_listend, _("jump to listend")),
				"prevBouquet": (self.switchToPlayList, _("switch to playlist")),
				"nextBouquet": (self.switchToFileList, _("switch to filelist")),
				"delete": (self.deletePlaylistEntry, _("delete playlist entry")),
				"shift_stop": (self.clear_playlist, _("clear playlist")),
				"shift_record": (self.playlist.PlayListShuffle, _("shuffle playlist")),
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions", 
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"], 
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.currList = "filelist"
		self.isAudioCD = False
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})

	def doNothing(self):
		pass

	def createSummary(self):
		return MediaPlayerLCDScreen

	def exit(self):
		self.playlistIOInternal.clear()
		for x in self.playlist.list:
			self.playlistIOInternal.addService(ServiceReference(x[0]))
		if self.savePlaylistOnExit:
			try:
				self.playlistIOInternal.save(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
			except IOError:
				print "couldn't save playlist.e2pls"
		if config.mediaplayer.saveDirOnExit.getValue():
			config.mediaplayer.defaultDir.setValue(self.filelist.getCurrentDirectory())
			config.mediaplayer.defaultDir.save()
		from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
		hotplugNotifier.remove(self.hotplugCB)
		del self["coverArt"].picload
		self.close()

	def checkSkipShowHideLock(self):
		self.updatedSeekState()

	def doEofInternal(self, playing):
		if playing:
			self.nextEntry()
		else:
			self.show()

	def __onClose(self):
		self.session.nav.playService(self.oldService)

	def __evUpdatedInfo(self):
		currPlay = self.session.nav.getCurrentService()
		sTagTrackNumber = currPlay.info().getInfo(iServiceInformation.sTagTrackNumber)
		sTagTrackCount = currPlay.info().getInfo(iServiceInformation.sTagTrackCount)
		sTagTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
		print "[__evUpdatedInfo] title %d of %d (%s)" % (sTagTrackNumber, sTagTrackCount, sTagTitle)
		self.readTitleInformation()

	def __evAudioDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagAudioCodec = currPlay.info().getInfoString(iServiceInformation.sTagAudioCodec)
		print "[__evAudioDecodeError] audio-codec %s can't be decoded by hardware" % (sTagAudioCodec)
		self.session.open(MessageBox, _("This Dreambox can't decode %s streams!") % sTagAudioCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evVideoDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagVideoCodec = currPlay.info().getInfoString(iServiceInformation.sTagVideoCodec)
		print "[__evVideoDecodeError] video-codec %s can't be decoded by hardware" % (sTagVideoCodec)
		self.session.open(MessageBox, _("This Dreambox can't decode %s streams!") % sTagVideoCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		print "[__evPluginError]" , message
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )

	def delMPTimer(self):
		del self.rightKeyTimer
		del self.leftKeyTimer

	def readTitleInformation(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)

			if sTitle == "":
				if not self.isAudioCD:
					sTitle = currPlay.info().getName().split('/')[-1]
				else:
					sTitle = self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()].getName()

			if self.AudioCD_albuminfo:
				if sAlbum == "" and "title" in self.AudioCD_albuminfo:
					sAlbum = self.AudioCD_albuminfo["title"]
				if sGenre == "" and "genre" in self.AudioCD_albuminfo:
					sGenre = self.AudioCD_albuminfo["genre"]
				if sArtist == "" and "artist" in self.AudioCD_albuminfo:
					sArtist = self.AudioCD_albuminfo["artist"]
				if "year" in self.AudioCD_albuminfo:
					sYear = self.AudioCD_albuminfo["year"]

			self.updateMusicInformation( sArtist, sTitle, sAlbum, sYear, sGenre, clear = True )
		else:
			self.updateMusicInformation()

	def updateMusicInformation(self, artist = "", title = "", album = "", year = "", genre = "", clear = False):
		self.updateSingleMusicInformation("artist", artist, clear)
		self.updateSingleMusicInformation("title", title, clear)
		self.updateSingleMusicInformation("album", album, clear)
		self.updateSingleMusicInformation("year", year, clear)
		self.updateSingleMusicInformation("genre", genre, clear)

	def updateSingleMusicInformation(self, name, info, clear):
		if info != "" or clear:
			if self[name].getText() != info:
				self[name].setText(info)

	def leftDown(self):
		self.lefttimer = True
		self.leftKeyTimer.start(1000)

	def rightDown(self):
		self.righttimer = True
		self.rightKeyTimer.start(1000)

	def leftUp(self):
		if self.lefttimer:
			self.leftKeyTimer.stop()
			self.lefttimer = False
			self[self.currList].pageUp()
			self.updateCurrentInfo()

	def rightUp(self):
		if self.righttimer:
			self.rightKeyTimer.stop()
			self.righttimer = False
			self[self.currList].pageDown()
			self.updateCurrentInfo()

	def leftTimerFire(self):
		self.leftKeyTimer.stop()
		self.lefttimer = False
		self.switchToFileList()

	def rightTimerFire(self):
		self.rightKeyTimer.stop()
		self.righttimer = False
		self.switchToPlayList()

	def switchToFileList(self):
		self.currList = "filelist"
		self.filelist.selectionEnabled(1)
		self.playlist.selectionEnabled(0)
		self.updateCurrentInfo()

	def switchToPlayList(self):
		if len(self.playlist) != 0:
			self.currList = "playlist"
			self.filelist.selectionEnabled(0)
			self.playlist.selectionEnabled(1)
			self.updateCurrentInfo()

	def up(self):
		self[self.currList].up()
		self.updateCurrentInfo()

	def down(self):
		self[self.currList].down()
		self.updateCurrentInfo()

	def showAfterSeek(self):
		pass

	def showAfterCuesheetOperation(self):
		self.show()

	def hideAfterResume(self):
		self.hide()

	def getIdentifier(self, ref):
		if self.isAudioCD:
			return ref.getName()
		else:
			text = ref.getPath()
			return text.split('/')[-1]

	# FIXME: maybe this code can be optimized 
	def updateCurrentInfo(self):
		text = ""
		if self.currList == "filelist":
			idx = self.filelist.getSelectionIndex()
			r = self.filelist.list[idx]
			text = r[1][7]
			if r[0][1] == True:
				if len(text) < 2:
					text += " "
				if text[:2] != "..":
					text = "/" + text
			self.summaries.setText(text,1)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

			text = ""
			if not self.filelist.canDescent():
				r = self.filelist.getServiceRef()
				if r is None:
					return
				text = r.getPath()
				self["currenttext"].setText(os_path.basename(text))

		if self.currList == "playlist":
			t = self.playlist.getSelection()
			if t is None:
				return
			#display current selected entry on LCD
			text = self.getIdentifier(t)
			self.summaries.setText(text,1)
			self["currenttext"].setText(text)
			idx = self.playlist.getSelectionIndex()
			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

	def ok(self):
		if self.currList == "filelist":
			if self.filelist.canDescent():
				self.filelist.descent()
				self.updateCurrentInfo()
			else:
				self.copyFile()

		if self.currList == "playlist":
			selection = self["playlist"].getSelection()
			self.changeEntry(self.playlist.getSelectionIndex())

	def showMenu(self):
		menu = []
		if len(self.cdAudioTrackFiles):
			menu.insert(0,(_("Play Audio-CD..."), "audiocd"))
		if self.currList == "filelist":
			if self.filelist.canDescent():
				menu.append((_("add directory to playlist"), "copydir"))
			else:
				menu.append((_("add files to playlist"), "copyfiles"))
			menu.append((_("switch to playlist"), "playlist"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("delete file"), "deletefile"))
		else:
			menu.append((_("switch to filelist"), "filelist"))
			menu.append((_("clear playlist"), "clear"))
			menu.append((_("Delete entry"), "deleteentry"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("shuffle playlist"), "shuffle"))
		menu.append((_("hide player"), "hide"));
		menu.append((_("load playlist"), "loadplaylist"));
		if config.usage.setup_level.index >= 1: # intermediate+
			menu.append((_("save playlist"), "saveplaylist"));
			menu.append((_("delete saved playlist"), "deleteplaylist"));
			menu.append((_("Edit settings"), "settings"))
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)

	def menuCallback(self, choice):
		if choice is None:
			return

		if choice[1] == "copydir":
			self.copyDirectory(self.filelist.getSelection()[0])
		elif choice[1] == "copyfiles":
			self.stopEntry()
			self.playlist.clear()
			self.isAudioCD = False
			self.copyDirectory(os_path.dirname(self.filelist.getSelection()[0].getPath()) + "/", recursive = False)
			self.playServiceRefEntry(self.filelist.getServiceRef())
		elif choice[1] == "playlist":
			self.switchToPlayList()
		elif choice[1] == "filelist":
			self.switchToFileList()
		elif choice[1] == "deleteentry":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()
		elif choice[1] == "clear":
			self.clear_playlist()
		elif choice[1] == "hide":
			self.hide()
		elif choice[1] == "saveplaylist":
			self.save_playlist()
		elif choice[1] == "loadplaylist":
			self.load_playlist()
		elif choice[1] == "deleteplaylist":
			self.delete_saved_playlist()
		elif choice[1] == "shuffle":
			self.playlist.PlayListShuffle()
		elif choice[1] == "deletefile":
			self.deleteFile()
		elif choice[1] == "settings":
			self.session.openWithCallback(self.applySettings, MediaPlayerSettings, self)
		elif choice[1] == "audiocd":
			self.playAudioCD()

	def playAudioCD(self):
		from enigma import eServiceReference
		from Plugins.Extensions.CDInfo.plugin import Query

		if len(self.cdAudioTrackFiles):
			self.playlist.clear()
			self.savePlaylistOnExit = False
			self.isAudioCD = True
			for file in self.cdAudioTrackFiles:
				ref = eServiceReference(4097, 0, file)
				self.playlist.addFile(ref)
			cdinfo = Query(self)
			cdinfo.scan()
			self.changeEntry(0)
			self.switchToPlayList()

	def applySettings(self):
		self.savePlaylistOnExit = config.mediaplayer.savePlaylistOnExit.getValue()
		if config.mediaplayer.repeat.getValue() == True:
			self["repeat"].setPixmapNum(1)
		else:
			self["repeat"].setPixmapNum(0)

	def showEventInformation(self):
		from Screens.EventView import EventViewSimple
		from ServiceReference import ServiceReference
		evt = self[self.currList].getCurrentEvent()
		if evt:
			self.session.open(EventViewSimple, evt, ServiceReference(self.getCurrent()))

	# also works on filelist (?)
	def getCurrent(self):
		return self["playlist"].getCurrent()

	def deletePlaylistEntry(self):
		if self.currList == "playlist":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()

	def skip_listbegin(self):
		if self.currList == "filelist":
			self.filelist.moveToIndex(0)
		else:
			self.playlist.moveToIndex(0)
		self.updateCurrentInfo()

	def skip_listend(self):
		if self.currList == "filelist":
			idx = len(self.filelist.list)
			self.filelist.moveToIndex(idx - 1)
		else:
			self.playlist.moveToIndex(len(self.playlist)-1)
		self.updateCurrentInfo()

	def save_playlist(self):
		self.session.openWithCallback(self.save_playlist2,InputBox, title=_("Please enter filename (empty = use current date)"),windowTitle = _("Save Playlist"))

	def save_playlist2(self, name):
		if name is not None:
			name = name.strip()
			if name == "":
				name = strftime("%y%m%d_%H%M%S")
			name += ".e2pls"
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			self.playlistIOInternal.save(resolveFilename(SCOPE_PLAYLIST) + name)

	def load_playlist(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os_listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError,e:
			print "Error while scanning subdirs ",e
		self.session.openWithCallback(self.PlaylistSelected, ChoiceBox, title=_("Please select a playlist..."), list = listpath)
Ejemplo n.º 7
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(mp2|mp3|ogg|ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|mov|m2ts|flv|dts|3gp|3g2|mts|wmv|asf|wma)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

#	ikseong
#		from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
#		hotplugNotifier.append(self.hotplugCB)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", 
			{
				"ok": (self.ok, _("add file to playlist")),
				"cancel": (self.exit, _("exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", 
			{
				"play": (self.xplayEntry, _("play entry")),
				"pause": (self.pauseEntry, _("pause")),
				"stop": (self.stopEntry, _("stop entry")),
				"previous": (self.previousMarkOrEntry, _("play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("play from next mark or playlist entry")),
				"menu": (self.showMenu, _("menu")),
				"skipListbegin": (self.skip_listbegin, _("jump to listbegin")),
				"skipListend": (self.skip_listend, _("jump to listend")),
				"prevBouquet": (self.switchToPlayList, _("switch to playlist")),
				"nextBouquet": (self.switchToFileList, _("switch to filelist")),
				"delete": (self.deletePlaylistEntry, _("delete playlist entry")),
#ikseong				
#				"shift_stop": (self.clear_playlist, _("clear playlist")),
#				"shift_record": (self.playlist.PlayListShuffle, _("shuffle playlist")),
				"shift_stop": self.clear_playlist,
				"shift_record": self.playlist.PlayListShuffle,
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions", 
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"], 
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.currList = "filelist"
		self.isAudioCD = False
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})
Ejemplo n.º 8
0
class MediaPlayer(Screen, InfoBarBase, InfoBarSeek, InfoBarAudioSelection, InfoBarCueSheetSupport, InfoBarNotifications, InfoBarSubtitleSupport, HelpableScreen):
	ALLOW_SUSPEND = True
	ENABLE_RESUME_SUPPORT = True

	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(mp2|mp3|ogg|ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|mov|m2ts|flv|dts|3gp|3g2|mts|wmv|asf|wma)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

#	ikseong
#		from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
#		hotplugNotifier.append(self.hotplugCB)

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts = [ ], actions = { }, prio=0):
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", 
			{
				"ok": (self.ok, _("add file to playlist")),
				"cancel": (self.exit, _("exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", 
			{
				"play": (self.xplayEntry, _("play entry")),
				"pause": (self.pauseEntry, _("pause")),
				"stop": (self.stopEntry, _("stop entry")),
				"previous": (self.previousMarkOrEntry, _("play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("play from next mark or playlist entry")),
				"menu": (self.showMenu, _("menu")),
				"skipListbegin": (self.skip_listbegin, _("jump to listbegin")),
				"skipListend": (self.skip_listend, _("jump to listend")),
				"prevBouquet": (self.switchToPlayList, _("switch to playlist")),
				"nextBouquet": (self.switchToFileList, _("switch to filelist")),
				"delete": (self.deletePlaylistEntry, _("delete playlist entry")),
#ikseong				
#				"shift_stop": (self.clear_playlist, _("clear playlist")),
#				"shift_record": (self.playlist.PlayListShuffle, _("shuffle playlist")),
				"shift_stop": self.clear_playlist,
				"shift_record": self.playlist.PlayListShuffle,
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions", 
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"], 
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.currList = "filelist"
		self.isAudioCD = False
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})

	def doNothing(self):
		pass

	def createSummary(self):
		return MediaPlayerLCDScreen

	def exit(self):
		self.playlistIOInternal.clear()
		for x in self.playlist.list:
			self.playlistIOInternal.addService(ServiceReference(x[0]))
		if self.savePlaylistOnExit:
			try:
				self.playlistIOInternal.save(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
			except IOError:
				print "couldn't save playlist.e2pls"
		if config.mediaplayer.saveDirOnExit.getValue():
			config.mediaplayer.defaultDir.setValue(self.filelist.getCurrentDirectory())
			config.mediaplayer.defaultDir.save()
#	ikseong			
#	from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
#	hotplugNotifier.remove(self.hotplugCB)
		del self["coverArt"].picload
		self.close()

	def checkSkipShowHideLock(self):
		self.updatedSeekState()

	def doEofInternal(self, playing):
		if playing:
			self.nextEntry()
		else:
			self.show()

	def __onClose(self):
		self.session.nav.playService(self.oldService)

	def __evUpdatedInfo(self):
		currPlay = self.session.nav.getCurrentService()
		sTagTrackNumber = currPlay.info().getInfo(iServiceInformation.sTagTrackNumber)
		sTagTrackCount = currPlay.info().getInfo(iServiceInformation.sTagTrackCount)
		sTagTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
		print "[__evUpdatedInfo] title %d of %d (%s)" % (sTagTrackNumber, sTagTrackCount, sTagTitle)
		self.readTitleInformation()

	def __evAudioDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagAudioCodec = currPlay.info().getInfoString(iServiceInformation.sTagAudioCodec)
		print "[__evAudioDecodeError] audio-codec %s can't be decoded by hardware" % (sTagAudioCodec)
		self.session.open(MessageBox, _("This STB can't decode %s streams!") % sTagAudioCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evVideoDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sTagVideoCodec = currPlay.info().getInfoString(iServiceInformation.sTagVideoCodec)
		print "[__evVideoDecodeError] video-codec %s can't be decoded by hardware" % (sTagVideoCodec)
		self.session.open(MessageBox, _("This STB can't decode %s streams!") % sTagVideoCodec, type = MessageBox.TYPE_INFO,timeout = 20 )

	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		print "[__evPluginError]" , message
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )

	def delMPTimer(self):
		del self.rightKeyTimer
		del self.leftKeyTimer

	def readTitleInformation(self):
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)

			if sTitle == "":
				if not self.isAudioCD:
					sTitle = currPlay.info().getName().split('/')[-1]
				else:
					sTitle = self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()].getName()

			if self.AudioCD_albuminfo:
				if sAlbum == "" and "title" in self.AudioCD_albuminfo:
					sAlbum = self.AudioCD_albuminfo["title"]
				if sGenre == "" and "genre" in self.AudioCD_albuminfo:
					sGenre = self.AudioCD_albuminfo["genre"]
				if sArtist == "" and "artist" in self.AudioCD_albuminfo:
					sArtist = self.AudioCD_albuminfo["artist"]
				if "year" in self.AudioCD_albuminfo:
					sYear = self.AudioCD_albuminfo["year"]

			self.updateMusicInformation( sArtist, sTitle, sAlbum, sYear, sGenre, clear = True )
		else:
			self.updateMusicInformation()

	def updateMusicInformation(self, artist = "", title = "", album = "", year = "", genre = "", clear = False):
		self.updateSingleMusicInformation("artist", artist, clear)
		self.updateSingleMusicInformation("title", title, clear)
		self.updateSingleMusicInformation("album", album, clear)
		self.updateSingleMusicInformation("year", year, clear)
		self.updateSingleMusicInformation("genre", genre, clear)

	def updateSingleMusicInformation(self, name, info, clear):
		if info != "" or clear:
			if self[name].getText() != info:
				self[name].setText(info)

	def leftDown(self):
		self.lefttimer = True
		self.leftKeyTimer.start(1000)

	def rightDown(self):
		self.righttimer = True
		self.rightKeyTimer.start(1000)

	def leftUp(self):
		if self.lefttimer:
			self.leftKeyTimer.stop()
			self.lefttimer = False
			self[self.currList].pageUp()
			self.updateCurrentInfo()

	def rightUp(self):
		if self.righttimer:
			self.rightKeyTimer.stop()
			self.righttimer = False
			self[self.currList].pageDown()
			self.updateCurrentInfo()

	def leftTimerFire(self):
		self.leftKeyTimer.stop()
		self.lefttimer = False
		self.switchToFileList()

	def rightTimerFire(self):
		self.rightKeyTimer.stop()
		self.righttimer = False
		self.switchToPlayList()

	def switchToFileList(self):
		self.currList = "filelist"
		self.filelist.selectionEnabled(1)
		self.playlist.selectionEnabled(0)
		self.updateCurrentInfo()

	def switchToPlayList(self):
		if len(self.playlist) != 0:
			self.currList = "playlist"
			self.filelist.selectionEnabled(0)
			self.playlist.selectionEnabled(1)
			self.updateCurrentInfo()

	def up(self):
		self[self.currList].up()
		self.updateCurrentInfo()

	def down(self):
		self[self.currList].down()
		self.updateCurrentInfo()

	def showAfterSeek(self):
		pass

	def showAfterCuesheetOperation(self):
		self.show()

	def hideAfterResume(self):
		self.hide()

	def getIdentifier(self, ref):
		if self.isAudioCD:
			return ref.getName()
		else:
			text = ref.getPath()
			return text.split('/')[-1]

	# FIXME: maybe this code can be optimized 
	def updateCurrentInfo(self):
		text = ""
		if self.currList == "filelist":
			idx = self.filelist.getSelectionIndex()
			r = self.filelist.list[idx]
			text = r[1][7]
			if r[0][1] == True:
				if len(text) < 2:
					text += " "
				if text[:2] != "..":
					text = "/" + text
			self.summaries.setText(text,1)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.filelist.list):
				r = self.filelist.list[idx]
				text = r[1][7]
				if r[0][1] == True:
					text = "/" + text
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

			text = ""
			if not self.filelist.canDescent():
				r = self.filelist.getServiceRef()
				if r is None:
					return
				text = r.getPath()
				self["currenttext"].setText(os_path.basename(text))

		if self.currList == "playlist":
			t = self.playlist.getSelection()
			if t is None:
				return
			#display current selected entry on LCD
			text = self.getIdentifier(t)
			self.summaries.setText(text,1)
			self["currenttext"].setText(text)
			idx = self.playlist.getSelectionIndex()
			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,3)
			else:
				self.summaries.setText(" ",3)

			idx += 1
			if idx < len(self.playlist):
				currref = self.playlist.getServiceRefList()[idx]
				text = self.getIdentifier(currref)
				self.summaries.setText(text,4)
			else:
				self.summaries.setText(" ",4)

	def ok(self):
		if self.currList == "filelist":
			if self.filelist.canDescent():
				self.filelist.descent()
				self.updateCurrentInfo()
			else:
				self.copyFile()

		if self.currList == "playlist":
			selection = self["playlist"].getSelection()
			self.changeEntry(self.playlist.getSelectionIndex())

	def showMenu(self):
		menu = []
		if len(self.cdAudioTrackFiles):
			menu.insert(0,(_("Play Audio-CD..."), "audiocd"))
		if self.currList == "filelist":
			if self.filelist.canDescent():
				menu.append((_("add directory to playlist"), "copydir"))
			else:
				menu.append((_("add files to playlist"), "copyfiles"))
			menu.append((_("switch to playlist"), "playlist"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("delete file"), "deletefile"))
		else:
			menu.append((_("switch to filelist"), "filelist"))
			menu.append((_("clear playlist"), "clear"))
			menu.append((_("Delete entry"), "deleteentry"))
			if config.usage.setup_level.index >= 1: # intermediate+
				menu.append((_("shuffle playlist"), "shuffle"))
		menu.append((_("hide player"), "hide"));
		menu.append((_("load playlist"), "loadplaylist"));
		if config.usage.setup_level.index >= 1: # intermediate+
			menu.append((_("save playlist"), "saveplaylist"));
			menu.append((_("delete saved playlist"), "deleteplaylist"));
			menu.append((_("Edit settings"), "settings"))
		self.session.openWithCallback(self.menuCallback, ChoiceBox, title="", list=menu)

	def menuCallback(self, choice):
		if choice is None:
			return

		if choice[1] == "copydir":
			self.copyDirectory(self.filelist.getSelection()[0])
		elif choice[1] == "copyfiles":
			self.stopEntry()
			self.playlist.clear()
			self.isAudioCD = False
			self.copyDirectory(os_path.dirname(self.filelist.getSelection()[0].getPath()) + "/", recursive = False)
			self.playServiceRefEntry(self.filelist.getServiceRef())
		elif choice[1] == "playlist":
			self.switchToPlayList()
		elif choice[1] == "filelist":
			self.switchToFileList()
		elif choice[1] == "deleteentry":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()
		elif choice[1] == "clear":
			self.clear_playlist()
		elif choice[1] == "hide":
			self.hide()
		elif choice[1] == "saveplaylist":
			self.save_playlist()
		elif choice[1] == "loadplaylist":
			self.load_playlist()
		elif choice[1] == "deleteplaylist":
			self.delete_saved_playlist()
		elif choice[1] == "shuffle":
			self.playlist.PlayListShuffle()
		elif choice[1] == "deletefile":
			self.deleteFile()
		elif choice[1] == "settings":
			self.session.openWithCallback(self.applySettings, MediaPlayerSettings, self)
		elif choice[1] == "audiocd":
			self.playAudioCD()

	def playAudioCD(self):
		from enigma import eServiceReference
		from Plugins.Extensions.CDInfo.plugin import Query

		if len(self.cdAudioTrackFiles):
			self.playlist.clear()
			self.savePlaylistOnExit = False
			self.isAudioCD = True
			for file in self.cdAudioTrackFiles:
				ref = eServiceReference(4097, 0, file)
				self.playlist.addFile(ref)
			cdinfo = Query(self)
			cdinfo.scan()
			self.changeEntry(0)
			self.switchToPlayList()

	def applySettings(self):
		self.savePlaylistOnExit = config.mediaplayer.savePlaylistOnExit.getValue()
		if config.mediaplayer.repeat.getValue() == True:
			self["repeat"].setPixmapNum(1)
		else:
			self["repeat"].setPixmapNum(0)

	def showEventInformation(self):
		from Screens.EventView import EventViewSimple
		from ServiceReference import ServiceReference
		evt = self[self.currList].getCurrentEvent()
		if evt:
			self.session.open(EventViewSimple, evt, ServiceReference(self.getCurrent()))

	# also works on filelist (?)
	def getCurrent(self):
		return self["playlist"].getCurrent()

	def deletePlaylistEntry(self):
		if self.currList == "playlist":
			if self.playlist.getSelectionIndex() == self.playlist.getCurrentIndex():
				self.stopEntry()
			self.deleteEntry()

	def skip_listbegin(self):
		if self.currList == "filelist":
			self.filelist.moveToIndex(0)
		else:
			self.playlist.moveToIndex(0)
		self.updateCurrentInfo()

	def skip_listend(self):
		if self.currList == "filelist":
			idx = len(self.filelist.list)
			self.filelist.moveToIndex(idx - 1)
		else:
			self.playlist.moveToIndex(len(self.playlist)-1)
		self.updateCurrentInfo()

	def save_playlist(self):
		self.session.openWithCallback(self.save_playlist2,InputBox, title=_("Please enter filename (empty = use current date)"),windowTitle = _("Save Playlist"))

	def save_playlist2(self, name):
		if name is not None:
			name = name.strip()
			if name == "":
				name = strftime("%y%m%d_%H%M%S")
			name += ".e2pls"
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			self.playlistIOInternal.save(resolveFilename(SCOPE_PLAYLIST) + name)

	def load_playlist(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os_listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError,e:
			print "Error while scanning subdirs ",e
		self.session.openWithCallback(self.PlaylistSelected, ChoiceBox, title=_("Please select a playlist..."), list = listpath)
Ejemplo n.º 9
0
class MediaPlayer(Screen, InfoBarBase, InfoBarSeek, InfoBarScreenSaver,
                  InfoBarAudioSelection, InfoBarCueSheetSupport,
                  InfoBarNotifications, InfoBarSubtitleSupport,
                  HelpableScreen):
    ALLOW_SUSPEND = True
    ENABLE_RESUME_SUPPORT = True

    def __init__(self, session, args=None):
        Screen.__init__(self, session)
        InfoBarAudioSelection.__init__(self)
        InfoBarCueSheetSupport.__init__(self,
                                        actionmap="MediaPlayerCueSheetActions")
        InfoBarNotifications.__init__(self)
        InfoBarBase.__init__(self)
        InfoBarScreenSaver.__init__(self)
        InfoBarSubtitleSupport.__init__(self)
        HelpableScreen.__init__(self)
        self.summary = None
        self.oldService = self.session.nav.getCurrentlyPlayingServiceReference(
        )
        self.session.nav.stopService()

        self.playlistparsers = {}
        self.addPlaylistParser(PlaylistIOM3U, "m3u")
        self.addPlaylistParser(PlaylistIOPLS, "pls")
        self.addPlaylistParser(PlaylistIOInternal, "e2pls")

        # 'None' is magic to start at the list of mountpoints
        defaultDir = config.mediaplayer.defaultDir.value
        self.filelist = FileList(
            defaultDir,
            matchingPattern=
            "(?i)^.*\.(mp2|mp3|ogg|ts|mts|m2ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|flv|mov|dts|3gp|3g2|asf|wmv|wma|webm)",
            useServiceRef=True,
            additionalExtensions="4098:m3u 4098:e2pls 4098:pls")
        self["filelist"] = self.filelist

        self.playlist = MyPlayList()
        self.is_closing = False
        self.delname = ""
        self.playlistname = ""

        self["playlist"] = self.playlist

        self["PositionGauge"] = ServicePositionGauge(self.session.nav)

        self["currenttext"] = Label("")

        self["artisttext"] = Label(_("Artist") + ':')
        self["artist"] = Label("")
        self["titletext"] = Label(_("Title") + ':')
        self["title"] = Label("")
        self["albumtext"] = Label(_("Album") + ':')
        self["album"] = Label("")
        self["yeartext"] = Label(_("Year") + ':')
        self["year"] = Label("")
        self["genretext"] = Label(_("Genre") + ':')
        self["genre"] = Label("")
        self["coverArt"] = MediaPixmap()
        self["repeat"] = MultiPixmap()

        self.seek_target = None

        try:
            from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
            hotplugNotifier.append(self.hotplugCB)
        except Exception as ex:
            print("[MediaPlayer] No hotplug support", ex)

        class MoviePlayerActionMap(NumberActionMap):
            def __init__(self, player, contexts=None, actions=None, prio=0):
                if not contexts: contexts = []
                if not actions: actions = {}
                NumberActionMap.__init__(self, contexts, actions, prio)
                self.player = player

            def action(self, contexts, action):
                self.player.show()
                return NumberActionMap.action(self, contexts, action)

        self["OkCancelActions"] = HelpableActionMap(
            self, "OkCancelActions", {
                "ok": (self.ok, _("Add file to playlist")),
                "cancel": (self.exit, _("Exit mediaplayer")),
            }, -2)

        self["MediaPlayerActions"] = HelpableActionMap(
            self, "MediaPlayerActions", {
                "play": (self.xplayEntry, _("Play entry")),
                "pause": (self.pauseEntry, _("Pause")),
                "stop": (self.stopEntry, _("Stop entry")),
                "previous": (self.previousMarkOrEntry,
                             _("Play from previous mark or playlist entry")),
                "next": (self.nextMarkOrEntry,
                         _("Play from next mark or playlist entry")),
                "menu": (self.showMenu, _("Menu")),
                "skipListbegin":
                (self.skip_listbegin, _("Jump to beginning of list")),
                "skipListend": (self.skip_listend, _("Jump to end of list")),
                "prevBouquet":
                (self.switchLists, _("Switch between filelist/playlist")),
                "nextBouquet":
                (self.switchLists, _("Switch between filelist/playlist")),
                "delete":
                (self.deletePlaylistEntry, _("Delete playlist entry")),
                "shift_stop": (self.clear_playlist, _("Clear playlist")),
                "shift_record":
                (self.playlist.PlayListShuffle, _("Shuffle playlist")),
                "subtitles": (self.subtitleSelection, _("Subtitle selection")),
            }, -2)

        self["InfobarEPGActions"] = HelpableActionMap(
            self, "InfobarEPGActions", {
                "showEventInfo":
                (self.showEventInformation, _("show event details")),
            })

        self["actions"] = MoviePlayerActionMap(
            self, ["DirectionActions"], {
                "right": self.rightDown,
                "rightRepeated": self.doNothing,
                "rightUp": self.rightUp,
                "left": self.leftDown,
                "leftRepeated": self.doNothing,
                "leftUp": self.leftUp,
                "up": self.up,
                "upRepeated": self.up,
                "upUp": self.doNothing,
                "down": self.down,
                "downRepeated": self.down,
                "downUp": self.doNothing,
            }, -2)

        InfoBarSeek.__init__(self, actionmap="MediaPlayerSeekActions")

        self.onClose.append(self.delMPTimer)
        self.onClose.append(self.__onClose)

        self.righttimer = False
        self.rightKeyTimer = eTimer()
        self.rightKeyTimer.callback.append(self.rightTimerFire)

        self.lefttimer = False
        self.leftKeyTimer = eTimer()
        self.leftKeyTimer.callback.append(self.leftTimerFire)

        self.currList = "filelist"
        self.isAudioCD = False
        self.AudioCD_albuminfo = {}
        self.cdAudioTrackFiles = []
        self.onShown.append(self.applySettings)

        self.playlistIOInternal = PlaylistIOInternal()
        list = self.playlistIOInternal.open(
            resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
        if list:
            for x in list:
                self.playlist.addFile(x.ref)
            self.playlist.updateList()

        self.__event_tracker = ServiceEventTracker(
            screen=self,
            eventmap={
                iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
                iPlayableService.evUser + 10: self.__evAudioDecodeError,
                iPlayableService.evUser + 11: self.__evVideoDecodeError,
                iPlayableService.evUser + 12: self.__evPluginError,
                iPlayableService.evUser + 13: self["coverArt"].embeddedCoverArt
            })

    def hideAndInfoBar(self):
        self.hide()
        self.mediaPlayerInfoBar.show()
        if config.mediaplayer.alwaysHideInfoBar.value or self.ext not in AUDIO_EXTENSIONS and not self.isAudioCD:
            self.hideMediaPlayerInfoBar.start(5000, True)

    def timerHideMediaPlayerInfoBar(self):
        self.hideMediaPlayerInfoBar.stop()
        self.mediaPlayerInfoBar.hide()

    def doNothing(self):
        pass

    def createSummary(self):
        return MediaPlayerLCDScreen

    def exit(self):
        self.playlistIOInternal.clear()
        for x in self.playlist.list:
            self.playlistIOInternal.addService(ServiceReference(x[0]))
        if self.savePlaylistOnExit:
            try:
                self.playlistIOInternal.save(
                    resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
            except IOError:
                print("couldn't save playlist.e2pls")
        if config.mediaplayer.saveDirOnExit.value:
            config.mediaplayer.defaultDir.setValue(
                self.filelist.getCurrentDirectory())
            config.mediaplayer.defaultDir.save()
        try:
            from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
            hotplugNotifier.remove(self.hotplugCB)
        except:
            pass
        del self["coverArt"].picload
        self.close()

    def checkSkipShowHideLock(self):
        self.updatedSeekState()

    def doEofInternal(self, playing):
        if playing:
            self.nextEntry()
        else:
            self.show()

    def __onClose(self):
        self.session.nav.playService(self.oldService)

    def __evUpdatedInfo(self):
        currPlay = self.session.nav.getCurrentService()
        sTagTrackNumber = currPlay.info().getInfo(
            iServiceInformation.sTagTrackNumber)
        sTagTrackCount = currPlay.info().getInfo(
            iServiceInformation.sTagTrackCount)
        sTagTitle = currPlay.info().getInfoString(
            iServiceInformation.sTagTitle)
        print("[__evUpdatedInfo] title %d of %d (%s)" %
              (sTagTrackNumber, sTagTrackCount, sTagTitle))
        self.readTitleInformation()

    def __evAudioDecodeError(self):
        currPlay = self.session.nav.getCurrentService()
        sTagAudioCodec = currPlay.info().getInfoString(
            iServiceInformation.sTagAudioCodec)
        print(
            "[__evAudioDecodeError] audio-codec %s can't be decoded by hardware"
            % sTagAudioCodec)
        self.session.open(
            MessageBox,
            _("This %s %s cannot decode %s streams!") %
            (getMachineBrand(), getMachineName(), sTagAudioCodec),
            type=MessageBox.TYPE_INFO,
            timeout=20)

    def __evVideoDecodeError(self):
        currPlay = self.session.nav.getCurrentService()
        sTagVideoCodec = currPlay.info().getInfoString(
            iServiceInformation.sTagVideoCodec)
        print(
            "[__evVideoDecodeError] video-codec %s can't be decoded by hardware"
            % sTagVideoCodec)
        self.session.open(
            MessageBox,
            _("This %s %s cannot decode %s streams!") %
            (getMachineBrand(), getMachineName(), sTagVideoCodec),
            type=MessageBox.TYPE_INFO,
            timeout=20)

    def __evPluginError(self):
        currPlay = self.session.nav.getCurrentService()
        message = currPlay.info().getInfoString(iServiceInformation.sUser + 12)
        print("[__evPluginError]", message)
        self.session.open(MessageBox,
                          message,
                          type=MessageBox.TYPE_INFO,
                          timeout=20)

    def delMPTimer(self):
        del self.rightKeyTimer
        del self.leftKeyTimer

    def readTitleInformation(self):
        currPlay = self.session.nav.getCurrentService()
        if currPlay is not None:
            sTitle = currPlay.info().getInfoString(
                iServiceInformation.sTagTitle)
            sAlbum = currPlay.info().getInfoString(
                iServiceInformation.sTagAlbum)
            sGenre = currPlay.info().getInfoString(
                iServiceInformation.sTagGenre)
            sArtist = currPlay.info().getInfoString(
                iServiceInformation.sTagArtist)
            sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)

            if sTitle == "":
                if not self.isAudioCD:
                    sTitle = currPlay.info().getName().split('/')[-1]
                else:
                    sTitle = self.playlist.getServiceRefList()[
                        self.playlist.getCurrentIndex()].getName()

            if self.AudioCD_albuminfo:
                if sAlbum == "" and "title" in self.AudioCD_albuminfo:
                    sAlbum = self.AudioCD_albuminfo["title"]
                if sGenre == "" and "genre" in self.AudioCD_albuminfo:
                    sGenre = self.AudioCD_albuminfo["genre"]
                if sArtist == "" and "artist" in self.AudioCD_albuminfo:
                    sArtist = self.AudioCD_albuminfo["artist"]
                if "year" in self.AudioCD_albuminfo:
                    sYear = self.AudioCD_albuminfo["year"]

            self.updateMusicInformation(sArtist,
                                        sTitle,
                                        sAlbum,
                                        sYear,
                                        sGenre,
                                        clear=True)
        else:
            self.updateMusicInformation()

    def updateMusicInformation(self,
                               artist="",
                               title="",
                               album="",
                               year="",
                               genre="",
                               clear=False):
        self.updateSingleMusicInformation("artist", artist, clear)
        self.updateSingleMusicInformation("title", title, clear)
        self.updateSingleMusicInformation("album", album, clear)
        self.updateSingleMusicInformation("year", year, clear)
        self.updateSingleMusicInformation("genre", genre, clear)

    def updateSingleMusicInformation(self, name, info, clear):
        if info != "" or clear:
            if self[name].getText() != info:
                self[name].setText(info)

    def leftDown(self):
        self.lefttimer = True
        self.leftKeyTimer.start(1000)

    def rightDown(self):
        self.righttimer = True
        self.rightKeyTimer.start(1000)

    def leftUp(self):
        if self.lefttimer:
            self.leftKeyTimer.stop()
            self.lefttimer = False
            self[self.currList].pageUp()
            self.updateCurrentInfo()

    def rightUp(self):
        if self.righttimer:
            self.rightKeyTimer.stop()
            self.righttimer = False
            self[self.currList].pageDown()
            self.updateCurrentInfo()

    def leftTimerFire(self):
        self.leftKeyTimer.stop()
        self.lefttimer = False
        self.switchToFileList()

    def rightTimerFire(self):
        self.rightKeyTimer.stop()
        self.righttimer = False
        self.switchToPlayList()

    def switchLists(self):
        if self.currList == "filelist":
            self.switchToPlayList()
            return
        self.switchToFileList()

    def switchToFileList(self):
        self.currList = "filelist"
        self.filelist.selectionEnabled(1)
        self.playlist.selectionEnabled(0)
        self.updateCurrentInfo()

    def switchToPlayList(self):
        if len(self.playlist) != 0:
            self.currList = "playlist"
            self.filelist.selectionEnabled(0)
            self.playlist.selectionEnabled(1)
            self.updateCurrentInfo()

    def up(self):
        self[self.currList].up()
        self.updateCurrentInfo()

    def down(self):
        self[self.currList].down()
        self.updateCurrentInfo()

    def showAfterSeek(self):
        pass

    def showAfterCuesheetOperation(self):
        self.show()

    def hideAfterResume(self):
        self.hide()

    def getIdentifier(self, ref):
        if self.isAudioCD:
            return ref.getName()
        else:
            text = ref.getPath()
            return text.split('/')[-1]

    # FIXME: maybe this code can be optimized
    def updateCurrentInfo(self):
        text = ""
        if self.currList == "filelist":
            idx = self.filelist.getSelectionIndex()
            r = self.filelist.list[idx]
            text = r[1][7]
            if r[0][1]:
                if len(text) < 2:
                    text += " "
                if text[:2] != "..":
                    text = "/" + text
            self.summaries.setText(text, 1)

            idx += 1
            if idx < len(self.filelist.list):
                r = self.filelist.list[idx]
                text = r[1][7]
                if r[0][1]:
                    text = "/" + text
                self.summaries.setText(text, 3)
            else:
                self.summaries.setText(" ", 3)

            idx += 1
            if idx < len(self.filelist.list):
                r = self.filelist.list[idx]
                text = r[1][7]
                if r[0][1]:
                    text = "/" + text
                self.summaries.setText(text, 4)
            else:
                self.summaries.setText(" ", 4)

            text = ""
            if not self.filelist.canDescent():
                r = self.filelist.getServiceRef()
                if r is None:
                    return
                text = r.getPath()
                self["currenttext"].setText(os.path.basename(text))

        if self.currList == "playlist":
            t = self.playlist.getSelection()
            if t is None:
                return
            #display current selected entry on LCD
            text = self.getIdentifier(t)
            self.summaries.setText(text, 1)
            self["currenttext"].setText(text)
            idx = self.playlist.getSelectionIndex()
            idx += 1
            if idx < len(self.playlist):
                currref = self.playlist.getServiceRefList()[idx]
                text = self.getIdentifier(currref)
                self.summaries.setText(text, 3)
            else:
                self.summaries.setText(" ", 3)

            idx += 1
            if idx < len(self.playlist):
                currref = self.playlist.getServiceRefList()[idx]
                text = self.getIdentifier(currref)
                self.summaries.setText(text, 4)
            else:
                self.summaries.setText(" ", 4)

    def ok(self):
        if self.currList == "filelist":
            if self.filelist.canDescent():
                self.filelist.descent()
                self.updateCurrentInfo()
            else:
                self.copyFile()

        if self.currList == "playlist":
            if self.playlist.getCurrentIndex(
            ) == self.playlist.getSelectionIndex():
                self.hide()
            else:
                self.changeEntry(self.playlist.getSelectionIndex())

    def showMenu(self):
        menulist = []
        if len(self.cdAudioTrackFiles):
            menulist.insert(0, (_("Play audio-CD..."), "audiocd"))
        if self.currList == "filelist":
            if self.filelist.canDescent():
                menulist.append((_("Add directory to playlist"), "copydir"))
            else:
                menulist.append((_("Add files to playlist"), "copyfiles"))
            menulist.append((_("Switch to playlist"), "playlist"))
            if config.usage.setup_level.index >= 1:  # intermediate+
                menulist.append((_("Delete file"), "deletefile"))
        else:
            menulist.append((_("Switch to filelist"), "filelist"))
            menulist.append((_("Clear playlist"), "clear"))
            menulist.append((_("Delete entry"), "deleteentry"))
            if config.usage.setup_level.index >= 1:  # intermediate+
                menulist.append((_("Shuffle playlist"), "shuffle"))
        menulist.append((_("Hide player"), "hide"))
        menulist.append((_("Load playlist"), "loadplaylist"))
        if config.usage.setup_level.index >= 1:  # intermediate+
            menulist.append((_("Save playlist"), "saveplaylist"))
            menulist.append((_("Delete saved playlist"), "deleteplaylist"))
            menulist.append((_("Edit settings"), "settings"))
        #self.timerHideMediaPlayerInfoBar()
        self.session.openWithCallback(self.menuCallback,
                                      ChoiceBox,
                                      title="",
                                      list=menulist)

    def menuCallback(self, choice):
        self.show()
        if choice is None:
            return

        if choice[1] == "copydir":
            self.copyDirectory(self.filelist.getSelection()[0])
        elif choice[1] == "copyfiles":
            self.copyDirectory(
                os.path.dirname(self.filelist.getSelection()[0].getPath()) +
                "/",
                recursive=False)
        elif choice[1] == "playlist":
            self.switchToPlayList()
        elif choice[1] == "filelist":
            self.switchToFileList()
        elif choice[1] == "deleteentry":
            if self.playlist.getSelectionIndex(
            ) == self.playlist.getCurrentIndex():
                self.stopEntry()
            self.deleteEntry()
        elif choice[1] == "clear":
            self.clear_playlist()
        elif choice[1] == "hide":
            self.hide()
        elif choice[1] == "saveplaylist":
            self.save_playlist()
        elif choice[1] == "loadplaylist":
            self.load_playlist()
        elif choice[1] == "deleteplaylist":
            self.delete_saved_playlist()
        elif choice[1] == "shuffle":
            self.playlist.PlayListShuffle()
        elif choice[1] == "deletefile":
            self.deleteFile()
        elif choice[1] == "settings":
            self.session.openWithCallback(self.applySettings,
                                          MediaPlayerSettings, self)
        elif choice[1] == "audiocd":
            self.playAudioCD()

    def playAudioCD(self):
        from enigma import eServiceReference
        if len(self.cdAudioTrackFiles):
            self.playlist.clear()
            self.savePlaylistOnExit = False
            self.isAudioCD = True
            for file in self.cdAudioTrackFiles:
                ref = eServiceReference(4097, 0, file)
                self.playlist.addFile(ref)
            try:
                from Plugins.Extensions.CDInfo.plugin import Query
                cdinfo = Query(self)
                cdinfo.scan()
            except ImportError:
                pass  # we can live without CDInfo
            self.changeEntry(0)
            self.switchToPlayList()

    def applySettings(self):
        self.savePlaylistOnExit = config.mediaplayer.savePlaylistOnExit.value
        if config.mediaplayer.repeat.value:
            self["repeat"].setPixmapNum(1)
        else:
            self["repeat"].setPixmapNum(0)

    def showEventInformation(self):
        from Screens.EventView import EventViewSimple
        from ServiceReference import ServiceReference
        evt = self[self.currList].getCurrentEvent()
        if evt:
            self.session.open(EventViewSimple, evt,
                              ServiceReference(self.getCurrent()))

    # also works on filelist (?)
    def getCurrent(self):
        return self["playlist"].getCurrent()

    def deletePlaylistEntry(self):
        if self.currList == "playlist":
            if self.playlist.getSelectionIndex(
            ) == self.playlist.getCurrentIndex():
                self.stopEntry()
            self.deleteEntry()

    def skip_listbegin(self):
        if self.currList == "filelist":
            self.filelist.moveToIndex(0)
        else:
            self.playlist.moveToIndex(0)
        self.updateCurrentInfo()

    def skip_listend(self):
        if self.currList == "filelist":
            idx = len(self.filelist.list)
            self.filelist.moveToIndex(idx - 1)
        else:
            self.playlist.moveToIndex(len(self.playlist) - 1)
        self.updateCurrentInfo()

    def save_playlist(self):
        self.session.openWithCallback(
            self.save_playlist2,
            InputBox,
            title=_("Please enter filename (empty = use current date)"),
            windowTitle=_("Save playlist"),
            text=self.playlistname)

    def save_playlist2(self, name):
        if name is not None:
            name = name.strip()
            if name == "":
                name = strftime("%y%m%d_%H%M%S")
            self.playlistname = name
            name += ".e2pls"
            self.playlistIOInternal.clear()
            for x in self.playlist.list:
                self.playlistIOInternal.addService(ServiceReference(x[0]))
            self.playlistIOInternal.save(
                resolveFilename(SCOPE_PLAYLIST) + name)

    def load_playlist(self):
        listpath = []
        playlistdir = resolveFilename(SCOPE_PLAYLIST)
        try:
            for i in os.listdir(playlistdir):
                listpath.append((i, playlistdir + i))
        except IOError as e:
            print("Error while scanning subdirs ", e)
        if config.mediaplayer.sortPlaylists.value:
            listpath.sort()
        self.session.openWithCallback(self.PlaylistSelected,
                                      ChoiceBox,
                                      title=_("Please select a playlist..."),
                                      list=listpath)

    def PlaylistSelected(self, path):
        if path is not None:
            self.playlistname = path[0].rsplit('.', 1)[-2]
            self.clear_playlist()
            extension = path[0].rsplit('.', 1)[-1]
            if extension in self.playlistparsers:
                playlist = self.playlistparsers[extension]()
                list = playlist.open(path[1])
                for x in list:
                    self.playlist.addFile(x.ref)
            self.playlist.updateList()

    def delete_saved_playlist(self):
        listpath = []
        playlistdir = resolveFilename(SCOPE_PLAYLIST)
        try:
            for i in os.listdir(playlistdir):
                listpath.append((i, playlistdir + i))
        except IOError as e:
            print("Error while scanning subdirs ", e)
        if config.mediaplayer.sortPlaylists.value:
            listpath.sort()
        self.session.openWithCallback(
            self.DeletePlaylistSelected,
            ChoiceBox,
            title=_("Please select a playlist to delete..."),
            list=listpath)

    def DeletePlaylistSelected(self, path):
        if path is not None:
            self.delname = path[1]
            self.session.openWithCallback(
                self.deleteConfirmed, MessageBox,
                _("Do you really want to delete %s?") % (path[1]))

    def deleteConfirmed(self, confirmed):
        if confirmed:
            try:
                os.remove(self.delname)
            except OSError as e:
                print("delete failed:", e)
                self.session.open(MessageBox, _("Delete failed!"),
                                  MessageBox.TYPE_ERROR)

    def clear_playlist(self):
        self.isAudioCD = False
        self.stopEntry()
        self.playlist.clear()
        self.switchToFileList()

    def copyDirectory(self, directory, recursive=True):
        print("copyDirectory", directory)
        if directory == '/':
            print("refusing to operate on /")
            return
        filelist = FileList(directory,
                            useServiceRef=True,
                            showMountpoints=False,
                            isTop=True)

        for x in filelist.getFileList():
            if x[0][1]:  #isDir
                if recursive:
                    if x[0][0] != directory:
                        self.copyDirectory(x[0][0])
            elif filelist.getServiceRef() and filelist.getServiceRef(
            ).type == 4097:
                self.playlist.addFile(x[0][0])
        self.playlist.updateList()

    def deleteFile(self):
        if self.currList == "filelist":
            self.service = self.filelist.getServiceRef()
        else:
            self.service = self.playlist.getSelection()
        if self.service is None:
            return
        if self.service.type != 4098 and self.session.nav.getCurrentlyPlayingServiceReference(
        ) is not None:
            if self.service == self.session.nav.getCurrentlyPlayingServiceReference(
            ):
                self.stopEntry()

        serviceHandler = eServiceCenter.getInstance()
        offline = serviceHandler.offlineOperations(self.service)
        info = serviceHandler.info(self.service)
        name = info and info.getName(self.service)
        result = False
        if offline is not None:
            # simulate first
            if not offline.deleteFromDisk(1):
                result = True
        if result:
            self.session.openWithCallback(
                self.deleteConfirmed_offline, MessageBox,
                _("Do you really want to delete %s?") % name)
        else:
            self.session.openWithCallback(self.close, MessageBox,
                                          _("You cannot delete this!"),
                                          MessageBox.TYPE_ERROR)

    def deleteConfirmed_offline(self, confirmed):
        if confirmed:
            serviceHandler = eServiceCenter.getInstance()
            offline = serviceHandler.offlineOperations(self.service)
            result = False
            if offline is not None:
                # really delete!
                if not offline.deleteFromDisk(0):
                    result = True
            if not result:
                self.session.open(MessageBox, _("Delete failed!"),
                                  MessageBox.TYPE_ERROR)
            else:
                self.removeListEntry()

    def removeListEntry(self):
        currdir = self.filelist.getCurrentDirectory()
        self.filelist.changeDir(currdir)
        deleteend = False
        while not deleteend:
            index = 0
            deleteend = True
            if len(self.playlist) > 0:
                for x in self.playlist.list:
                    if self.service == x[0]:
                        self.playlist.deleteFile(index)
                        deleteend = False
                        break
                    index += 1
        self.playlist.updateList()
        if self.currList == "playlist":
            if len(self.playlist) == 0:
                self.switchToFileList()

    def copyFile(self):
        if self.filelist.getServiceRef().type == 4098:  # playlist
            ServiceRef = self.filelist.getServiceRef()
            extension = ServiceRef.getPath()[ServiceRef.getPath().rfind('.') +
                                             1:]
            if extension in self.playlistparsers:
                playlist = self.playlistparsers[extension]()
                list = playlist.open(ServiceRef.getPath())
                for x in list:
                    self.playlist.addFile(x.ref)
            self.playlist.updateList()
        else:
            self.playlist.addFile(self.filelist.getServiceRef())
            self.playlist.updateList()
            if len(self.playlist) == 1:
                self.changeEntry(0)

    def addPlaylistParser(self, parser, extension):
        self.playlistparsers[extension] = parser

    def nextEntry(self):
        next = self.playlist.getCurrentIndex() + 1
        if next < len(self.playlist):
            self.changeEntry(next)
        elif (len(self.playlist) > 0) and (config.mediaplayer.repeat.value
                                           == True):
            self.stopEntry()
            self.changeEntry(0)
        elif len(self.playlist) > 0:
            self.stopEntry()

    def nextMarkOrEntry(self):
        if not self.jumpPreviousNextMark(lambda x: x):
            next = self.playlist.getCurrentIndex() + 1
            if next < len(self.playlist):
                self.changeEntry(next)
            else:
                self.doSeek(-1)

    def previousMarkOrEntry(self):
        if not self.jumpPreviousNextMark(lambda x: -x - 5 * 90000, start=True):
            next = self.playlist.getCurrentIndex() - 1
            if next >= 0:
                self.changeEntry(next)

    def deleteEntry(self):
        self.playlist.deleteFile(self.playlist.getSelectionIndex())
        self.playlist.updateList()
        if len(self.playlist) == 0:
            self.switchToFileList()

    def changeEntry(self, index):
        self.playlist.setCurrentPlaying(index)
        self.playEntry()

    def playServiceRefEntry(self, serviceref):
        serviceRefList = self.playlist.getServiceRefList()
        for count in list(range(len(serviceRefList))):
            if serviceRefList[count] == serviceref:
                self.changeEntry(count)
                break

    def xplayEntry(self):
        if self.currList == "playlist":
            self.playEntry()
        else:
            self.stopEntry()
            self.playlist.clear()
            self.isAudioCD = False
            sel = self.filelist.getSelection()
            if sel:
                if sel[1]:  # can descent
                    # add directory to playlist
                    self.copyDirectory(sel[0])
                else:
                    # add files to playlist
                    self.copyDirectory(os.path.dirname(sel[0].getPath()) + "/",
                                       recursive=False)
            if len(self.playlist) > 0:
                self.changeEntry(0)

    def playEntry(self):
        if len(self.playlist.getServiceRefList()):
            needsInfoUpdate = False
            currref = self.playlist.getServiceRefList()[
                self.playlist.getCurrentIndex()]
            if self.session.nav.getCurrentlyPlayingServiceReference(
            ) is None or currref != self.session.nav.getCurrentlyPlayingServiceReference(
            ):
                idx = self.playlist.getCurrentIndex()
                currref = self.playlist.getServiceRefList()[idx]
                text = self.getIdentifier(currref)
                ext = os.path.splitext(text)[1].lower()
                if ext not in AUDIO_EXTENSIONS and not self.isAudioCD:
                    movie = self.playlist.getServiceRefList()[
                        self.playlist.getCurrentIndex()]
                    self.session.openWithCallback(self.stopEntry,
                                                  ExMoviePlayer, movie)
                else:
                    self.session.nav.playService(
                        self.playlist.getServiceRefList()[
                            self.playlist.getCurrentIndex()])
                    info = eServiceCenter.getInstance().info(currref)
                    description = info and info.getInfoString(
                        currref, iServiceInformation.sDescription) or ""
                    self["title"].setText(description)
                    # display just playing musik on LCD
                    idx = self.playlist.getCurrentIndex()
                    currref = self.playlist.getServiceRefList()[idx]
                    text = self.getIdentifier(currref)
                    ext = os.path.splitext(text)[1].lower()
                    text = ">" + text
                    # FIXME: the information if the service contains video (and we should hide our window) should com from the service instead
                    if ext not in AUDIO_EXTENSIONS and not self.isAudioCD:
                        self.hide()
                    else:
                        needsInfoUpdate = True
                    self.summaries.setText(text, 1)

                    # get the next two entries
                    idx += 1
                    if idx < len(self.playlist):
                        currref = self.playlist.getServiceRefList()[idx]
                        text = self.getIdentifier(currref)
                        self.summaries.setText(text, 3)
                    else:
                        self.summaries.setText(" ", 3)

                    idx += 1
                    if idx < len(self.playlist):
                        currref = self.playlist.getServiceRefList()[idx]
                        text = self.getIdentifier(currref)
                        self.summaries.setText(text, 4)
                    else:
                        self.summaries.setText(" ", 4)
            else:
                idx = self.playlist.getCurrentIndex()
                currref = self.playlist.getServiceRefList()[idx]
                text = currref.getPath()
                ext = os.path.splitext(text)[1].lower()
                if ext not in AUDIO_EXTENSIONS and not self.isAudioCD:
                    self.hide()
                else:
                    needsInfoUpdate = True

            self.unPauseService()
            if needsInfoUpdate:
                path = self.playlist.getServiceRefList()[
                    self.playlist.getCurrentIndex()].getPath()
                self["coverArt"].updateCoverArt(path)
            else:
                self["coverArt"].showDefaultCover()
            self.readTitleInformation()

    def updatedSeekState(self):
        if self.seekstate == self.SEEK_STATE_PAUSE:
            self.playlist.pauseFile()
        elif self.seekstate == self.SEEK_STATE_PLAY:
            self.playlist.playFile()
        elif self.isStateForward(self.seekstate):
            self.playlist.forwardFile()
        elif self.isStateBackward(self.seekstate):
            self.playlist.rewindFile()

    def pauseEntry(self):
        self.pauseService()
        if self.seekstate == self.SEEK_STATE_PAUSE:
            self.show()
        else:
            self.hide()

    def stopEntry(self):
        self.playlist.stopFile()
        self.session.nav.playService(None)
        self.updateMusicInformation(clear=True)
        self.show()

    def unPauseService(self):
        self.setSeekState(self.SEEK_STATE_PLAY)

    def subtitleSelection(self):
        from Screens.AudioSelection import SubtitleSelection
        self.session.open(SubtitleSelection, self)

    def hotplugCB(self, dev, media_state):
        if dev == harddiskmanager.getCD():
            if media_state == "1":
                from Components.Scanner import scanDevice
                devpath = harddiskmanager.getAutofsMountpoint(
                    harddiskmanager.getCD())
                self.cdAudioTrackFiles = []
                res = scanDevice(devpath)
                list = [(r.description, r, res[r], self.session) for r in res]
                if list:
                    (desc, scanner, files, session) = list[0]
                    for file in files:
                        if file.mimetype == "audio/x-cda":
                            self.cdAudioTrackFiles.append(file.path)
            else:
                self.cdAudioTrackFiles = []
                if self.isAudioCD:
                    self.clear_playlist()
Ejemplo n.º 10
0
class MediaPlayer(Screen, InfoBarBase, InfoBarScreenSaver, InfoBarSeek, InfoBarAudioSelection, InfoBarAspectSelection, InfoBarCueSheetSupport, InfoBarNotifications, InfoBarSubtitleSupport, HelpableScreen):
	ALLOW_SUSPEND = True
	ENABLE_RESUME_SUPPORT = True

	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarAspectSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarScreenSaver.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.value
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(mp2|mp3|ogg|ts|trp|mts|m2ts|wav|wave|m3u|pls|e2pls|mpg|vob|avi|divx|m4v|mkv|mp4|m4a|dat|flac|flv|mov|dts|3gp|3g2|asf|wmv|wma)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.hiding = False
		self.delname = ""
		self.playlistname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

		self["currenttext"] = Label("")

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		try:
			from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
			hotplugNotifier.append(self.hotplugCB)
		except Exception, ex:
			print "[MediaPlayer] No hotplug support", ex

		class MoviePlayerActionMap(NumberActionMap):
			def __init__(self, player, contexts=None, actions=None, prio=0):
				if not contexts: contexts = []
				if not actions: actions = {}
				NumberActionMap.__init__(self, contexts, actions, prio)
				self.player = player

			def action(self, contexts, action):
				self.player.show()
				return NumberActionMap.action(self, contexts, action)

		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"ok": (self.ok, _("Add file to playlist")),
				"cancel": (self.exit, _("Exit mediaplayer")),
			}, -2)

		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions",
			{
				"play": (self.xplayEntry, _("Play entry")),
				"pause": (self.pauseEntry, _("Pause")),
				"stop": (self.stopEntry, _("Stop entry")),
				"previous": (self.previousMarkOrEntry, _("Play from previous mark or playlist entry")),
				"next": (self.nextMarkOrEntry, _("Play from next mark or playlist entry")),
				"menu": (self.showMenu, _("Menu")),
				"skipListbegin": (self.skip_listbegin, _("Jump to beginning of list")),
				"skipListend": (self.skip_listend, _("Jump to end of list")),
				"prevBouquet": (self.switchLists, _("Switch between filelist/playlist")),
				"nextBouquet": (self.switchLists, _("Switch between filelist/playlist")),
				"delete": (self.deletePlaylistEntry, _("Delete playlist entry")),
				"shift_stop": (self.clear_playlist, _("Clear playlist")),
				"shift_record": (self.playlist.PlayListShuffle, _("Shuffle playlist")),
				"subtitles": (self.subtitleSelection, _("Subtitle selection")),
			}, -2)

		self["InfobarEPGActions"] = HelpableActionMap(self, "InfobarEPGActions",
			{
				"showEventInfo": (self.showEventInformation, _("show event details")),
			})

		self["actions"] = MoviePlayerActionMap(self, ["DirectionActions"],
		{
			"right": self.rightDown,
			"rightRepeated": self.doNothing,
			"rightUp": self.rightUp,
			"left": self.leftDown,
			"leftRepeated": self.doNothing,
			"leftUp": self.leftUp,

			"up": self.up,
			"upRepeated": self.up,
			"upUp": self.doNothing,
			"down": self.down,
			"downRepeated": self.down,
			"downUp": self.doNothing,
		}, -2)

		InfoBarSeek.__init__(self, actionmap = "MediaPlayerSeekActions")

		self.mediaPlayerInfoBar = self.session.instantiateDialog(MediaPlayerInfoBar)

		self.onClose.append(self.delMPTimer)
		self.onClose.append(self.__onClose)
		self.onShow.append(self.timerHideMediaPlayerInfoBar)

		self.righttimer = False
		self.rightKeyTimer = eTimer()
		self.rightKeyTimer.callback.append(self.rightTimerFire)

		self.lefttimer = False
		self.leftKeyTimer = eTimer()
		self.leftKeyTimer.callback.append(self.leftTimerFire)

		self.hideMediaPlayerInfoBar = eTimer()
		self.hideMediaPlayerInfoBar.callback.append(self.timerHideMediaPlayerInfoBar)

		self.currList = "filelist"
		self.isAudioCD = False
		self.ext = None
		self.AudioCD_albuminfo = {}
		self.cdAudioTrackFiles = []
		self.onShown.append(self.applySettings)

		self.playlistIOInternal = PlaylistIOInternal()
		list = self.playlistIOInternal.open(resolveFilename(SCOPE_CONFIG, "playlist.e2pls"))
		if list:
			for x in list:
				self.playlist.addFile(x.ref)
			self.playlist.updateList()

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evStart: self.__evStart,
				iPlayableService.evUpdatedInfo: self.__evUpdatedInfo,
				iPlayableService.evUser+10: self.__evAudioDecodeError,
				iPlayableService.evUser+11: self.__evVideoDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				# we dont need that anymore, but keep it for the next two weeks
				# let us see, if user reports any problems
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt,
				iPlayableService.evUser+13: self.__embeddedCoverArt
			})
	def __init__(self, session):
		Screen.__init__(self, session)

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)
		
		self["key_red"] = Button(_(" "))
		self["key_green"] = Button(" ")
		self["key_yellow"] = Button(" ")
		self["key_blue"] = Button(_("File Browser"))
		
		self["fileinfo"] = Label()
		self["coverArt"] = MediaPixmap()
		
		self["currentfolder"] = Label()
		self["currentfavname"] = Label()
		self.curfavfolder = -1

		self["play"] = Pixmap()
		self["stop"] = Pixmap()

		self["curplayingtitle"] = Label()
		self.updateFileInfo()
		self.PlaySingle = 0
		
		self.isVisible = True
		
		self.playlist = PlayList()
		self["playlist"] = self.playlist
		
		self.playlistIOInternal = PlaylistIOInternal()
		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")
		
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.updateFileInfo,
				#iPlayableService.evStopped: self.StopPlayback,
				#iPlayableService.evUser+11: self.__evDecodeError,
				#iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})
		
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions", 
			{
				"ok": (self.KeyOK, _("Play from selected file")),
				"cancel": (self.Exit, _("Exit Audio Player")),
				"left": (self.leftUp, _("List Top")),
				"right": (self.rightDown, _("List Bottom")),
				"up": (self.up, _("List up")),
				"down": (self.down, _("List down")),
				"menu": (self.showMenu, _("File / Folder Options")),
				"video": (self.visibility, _("Show / Hide Player")),
				"info": (self.showFileInfo, _("Show File Info")),
				"stop": (self.StopPlayback, _("Stop Playback")),
				#"red": (self.Exit, _("Close Playlist")),
				#"green": (self.close, _("Play All")),
				#"yellow": (self.Exit, _("Playlists")),
				"blue": (self.Exit, _("Close Playlist")),
				"next": (self.KeyNext, _("Next song")),
				"previous": (self.KeyPrevious, _("Previous song")),
				"playpause": (self.PlayPause, _("Play / Pause")),
				"stop": (self.StopPlayback, _("Stop")),
			}, -2)
class MC_AudioPlaylist(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)
		
		self["key_red"] = Button(_(" "))
		self["key_green"] = Button(" ")
		self["key_yellow"] = Button(" ")
		self["key_blue"] = Button(_("File Browser"))
		
		self["fileinfo"] = Label()
		self["coverArt"] = MediaPixmap()
		
		self["currentfolder"] = Label()
		self["currentfavname"] = Label()
		self.curfavfolder = -1

		self["play"] = Pixmap()
		self["stop"] = Pixmap()

		self["curplayingtitle"] = Label()
		self.updateFileInfo()
		self.PlaySingle = 0
		
		self.isVisible = True
		
		self.playlist = PlayList()
		self["playlist"] = self.playlist
		
		self.playlistIOInternal = PlaylistIOInternal()
		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")
		
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.updateFileInfo,
				#iPlayableService.evStopped: self.StopPlayback,
				#iPlayableService.evUser+11: self.__evDecodeError,
				#iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})
		
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions", 
			{
				"ok": (self.KeyOK, _("Play from selected file")),
				"cancel": (self.Exit, _("Exit Audio Player")),
				"left": (self.leftUp, _("List Top")),
				"right": (self.rightDown, _("List Bottom")),
				"up": (self.up, _("List up")),
				"down": (self.down, _("List down")),
				"menu": (self.showMenu, _("File / Folder Options")),
				"video": (self.visibility, _("Show / Hide Player")),
				"info": (self.showFileInfo, _("Show File Info")),
				"stop": (self.StopPlayback, _("Stop Playback")),
				#"red": (self.Exit, _("Close Playlist")),
				#"green": (self.close, _("Play All")),
				#"yellow": (self.Exit, _("Playlists")),
				"blue": (self.Exit, _("Close Playlist")),
				"next": (self.KeyNext, _("Next song")),
				"previous": (self.KeyPrevious, _("Previous song")),
				"playpause": (self.PlayPause, _("Play / Pause")),
				"stop": (self.StopPlayback, _("Stop")),
			}, -2)
		
	def up(self):
		self["playlist"].up()

	def down(self):
		self["playlist"].down()
		
	def leftUp(self):
		self["playlist"].pageUp()
		
	def rightDown(self):
		self["playlist"].pageDown()

	def KeyOK(self):
		if len(self.playlist.getServiceRefList()):
			x = self.playlist.getSelectionIndex()
			print "x is %s" % (x)
			self.playlist.setCurrentPlaying(self.playlist.getSelectionIndex())
			x = self.playlist.getCurrentIndex()
			print "x is %s" % (x)
			x = len(self.playlist)
			print "x is %s" % (x)
			self.PlayService()

	def PlayPause(self):
		if MC_AudioPlayer.STATE != "NONE":
			if MC_AudioPlayer.STATE == "PLAY":
				service = self.session.nav.getCurrentService()
				pausable = service.pause()
				pausable.pause()
				MC_AudioPlayer.STATE = "PAUSED"
			elif MC_AudioPlayer.STATE == "PAUSED":
				service = self.session.nav.getCurrentService()
				pausable = service.pause()
				pausable.unpause()
				MC_AudioPlayer.STATE = "PLAY"
			else:
				self.KeyOK()

	def KeyNext(self):
		if MC_AudioPlayer.STATE != "NONE":
			if MC_AudioPlayer.playlistplay == 1:
				next = self.playlist.getCurrentIndex() + 1
				if next < len(self.playlist):
					MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying + 1
				else:
					MC_AudioPlayer.currPlaying = 0
				self.PlayService()
			
			else:
				self.session.open(MessageBox, _("You have to close playlist before you can go to the next song while playing from file browser."), MessageBox.TYPE_ERROR)
		
	def KeyPrevious(self):
		if MC_AudioPlayer.playlistplay == 1:
			next = self.playlist.getCurrentIndex() - 1
			if next != -1:
				MC_AudioPlayer.currPlaying = MC_AudioPlayer.currPlaying - 1
			else:
				MC_AudioPlayer.currPlaying = 0
			self.PlayService()
		
		else:
			self.session.open(MessageBox, _("You have to close playlist before you can go to the previous song while playing from file browser."), MessageBox.TYPE_ERROR)
			
	def PlayService(self):
		MC_AudioPlayer.playlistplay = 1
		
		ref = self.playlist.getServiceRefList()[self.playlist.getCurrentIndex()]
		#newref = eServiceReference(4370, 0, ref.getPath())
		self.session.nav.playService(ref)
		MC_AudioPlayer.STATE = "PLAY"
		self.updateFileInfo()
			
		#self["play"].instance.setPixmapFromFile("/usr/lib/enigma2/python/Plugins/Extensions/MediaCenter/icons/play_enabled.png")
		#self["stop"].instance.setPixmapFromFile("/usr/lib/enigma2/python/Plugins/Extensions/MediaCenter/icons/stop_disabled.png")

		#path = self["filelist"].getCurrentDirectory() + self["filelist"].getFilename()
		#self["coverArt"].updateCoverArt(path)
				
	def StopPlayback(self):

		if self.isVisible == False:
			self.show()
			self.isVisible = True
		
		if self.session.nav.getCurrentService() is None:
			return
		
		else:
			self.session.nav.stopService()
			MC_AudioPlayer.STATE = "NONE"
			
			#self["play"].instance.setPixmapFromFile("/usr/lib/enigma2/python/Plugins/Extensions/MediaCenter/icons/play_disabled.png")
			#self["stop"].instance.setPixmapFromFile("/usr/lib/enigma2/python/Plugins/Extensions/MediaCenter/icons/stop_enabled.png")

	def visibility(self, force=1):
		if self.isVisible == True:
			self.isVisible = False
			self.hide()
		else:
			self.isVisible = True
			self.show()
			#self["list"].refresh()

	def showFileInfo(self):
		if self["filelist"].canDescent():
			return
		else:
			self.session.open(MC_AudioInfoView, self["filelist"].getCurrentDirectory() + self["filelist"].getFilename() , self["filelist"].getFilename(), self["filelist"].getServiceRef())
	
	def Settings(self):
		self.session.open(AudioPlayerSettings)

	def Exit(self):
		self.close()

	def updateFileInfo(self):
		print "DOING EOF FOR 2"
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			sTitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sComment = currPlay.info().getInfoString(iServiceInformation.sTagComment)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTagDate)
			
			if sTitle == "":
				sTitle = currPlay.info().getName().split('/')[-1]
					
			self["fileinfo"].setText(_("Title:") + " " + sTitle + "\n" + _("Artist:") + " " +  sArtist + "\n" + _("Album:") + " " + sAlbum + "\n" + _("Genre:") + " " + sGenre + "\n" + _("Comment:") + " " + sComment)
			self["curplayingtitle"].setText(_("Now Playing:") + " " + sArtist + " - " + sTitle)

	def save_playlist(self):
		self.session.openWithCallback(self.save_pls,InputBox, title=_("Please enter filename (empty = use current date)"),windowTitle = _("Save Playlist"))

	def save_pls(self, name):
		if name is not None:
			name = name.strip()
			if name == "":
				name = strftime("%y%m%d_%H%M%S")
			name += ".e2pls"
			self.playlistIOInternal.clear()
			for x in self.playlist.list:
				self.playlistIOInternal.addService(ServiceReference(x[0]))
			self.playlistIOInternal.save(resolveFilename(SCOPE_PLAYLIST) + name)

	def load_playlist(self):
		listpath = []
		playlistdir = resolveFilename(SCOPE_PLAYLIST)
		try:
			for i in os_listdir(playlistdir):
				listpath.append((i,playlistdir + i))
		except IOError,e:
			print "Error while scanning subdirs ",e
		self.session.openWithCallback(self.load_pls, ChoiceBox, title=_("Please select a playlist..."), list = listpath)