openlp-core team mailing list archive
-
openlp-core team
-
Mailing list archive
-
Message #10169
[Merge] lp:~crichter/openlp/media_rewrite into lp:openlp
rimach has proposed merging lp:~crichter/openlp/media_rewrite into lp:openlp.
Requested reviews:
Tim Bentley (trb143)
Raoul Snyman (raoul-snyman)
Jonathan Corwin (j-corwin)
For more details, see:
https://code.launchpad.net/~crichter/openlp/media_rewrite/+merge/64630
Rewrite of the multimedia stuff.
- move all related functionality to the media plugin
--
https://code.launchpad.net/~crichter/openlp/media_rewrite/+merge/64630
Your team OpenLP Core is subscribed to branch lp:openlp.
=== modified file 'openlp/core/lib/htmlbuilder.py'
--- openlp/core/lib/htmlbuilder.py 2011-06-12 16:02:52 +0000
+++ openlp/core/lib/htmlbuilder.py 2011-06-15 04:36:33 +0000
@@ -66,12 +66,7 @@
#image {
z-index:2;
}
-#video1 {
- z-index:3;
-}
-#video2 {
- z-index:3;
-}
+%s
#alert {
position: absolute;
left: 0px;
@@ -95,89 +90,8 @@
</style>
<script language="javascript">
var timer = null;
- var video_timer = null;
- var current_video = '1';
var transition = %s;
-
- function show_video(state, path, volume, loop){
- // Note, the preferred method for looping would be to use the
- // video tag loop attribute.
- // But QtWebKit doesn't support this. Neither does it support the
- // onended event, hence the setInterval()
- // In addition, setting the currentTime attribute to zero to restart
- // the video raises an INDEX_SIZE_ERROR: DOM Exception 1
- // To complicate it further, sometimes vid.currentTime stops
- // slightly short of vid.duration and vid.ended is intermittent!
- //
- // Note, currently the background may go black between loops. Not
- // desirable. Need to investigate using two <video>'s, and hiding/
- // preloading one, and toggle between the two when looping.
-
- if(current_video=='1'){
- var vid = document.getElementById('video1');
- var vid2 = document.getElementById('video2');
- } else {
- var vid = document.getElementById('video2');
- var vid2 = document.getElementById('video1');
- }
- if(volume != null){
- vid.volume = volume;
- vid2.volume = volume;
- }
- switch(state){
- case 'init':
- vid.src = path;
- vid2.src = path;
- if(loop == null) loop = false;
- vid.looping = loop;
- vid2.looping = loop;
- vid.load();
- break;
- case 'load':
- vid2.style.visibility = 'hidden';
- vid2.load();
- break;
- case 'play':
- vid.play();
- vid.style.visibility = 'visible';
- if(vid.looping){
- video_timer = setInterval(
- function() {
- show_video('poll');
- }, 200);
- }
- break;
- case 'pause':
- if(video_timer!=null){
- clearInterval(video_timer);
- video_timer = null;
- }
- vid.pause();
- break;
- case 'stop':
- show_video('pause');
- vid.style.visibility = 'hidden';
- break;
- case 'poll':
- if(vid.ended||vid.currentTime+0.2>vid.duration)
- show_video('swap');
- break;
- case 'swap':
- show_video('pause');
- if(current_video=='1')
- current_video = '2';
- else
- current_video = '1';
- show_video('play');
- show_video('load');
- break;
- case 'close':
- show_video('stop');
- vid.src = '';
- vid2.src = '';
- break;
- }
- }
+ %s
function show_image(src){
var img = document.getElementById('image');
@@ -305,15 +219,13 @@
function show_text_complete(){
return (text_opacity()==1);
}
+
</script>
</head>
<body>
<img id="bgimage" class="size" %s />
<img id="image" class="size" %s />
-<video id="video1" class="size" style="visibility:hidden" autobuffer preload>
-</video>
-<video id="video2" class="size" style="visibility:hidden" autobuffer preload>
-</video>
+%s
%s
<div id="footer" class="footer"></div>
<div id="black" class="size"></div>
@@ -322,7 +234,7 @@
</html>
"""
-def build_html(item, screen, alert, islive, background, image=None):
+def build_html(item, screen, alert, islive, background, plugins=None, image=None):
"""
Build the full web paged structure for display
@@ -341,6 +253,9 @@
``background``
Theme background image - bytes
+ ``plugins``
+ access to the plugins
+
``image``
Image media item - bytes
"""
@@ -359,14 +274,25 @@
image_src = u'src="data:image/png;base64,%s"' % image
else:
image_src = u'style="display:none;"'
+ plugin_css = u''
+ plugin_js = u''
+ plugin_html = u''
+ if plugins:
+ for plugin in plugins:
+ plugin_css += plugin.getDisplayCss()
+ plugin_js += plugin.getDisplayJavascript()
+ plugin_html += plugin.getDisplayHtml()
html = HTMLSRC % (build_background_css(item, width, height),
width, height,
+ plugin_css,
build_alert_css(alert, width),
build_footer_css(item, height),
build_lyrics_css(item, webkitvers),
u'true' if theme and theme.display_slide_transition and islive \
else u'false',
+ plugin_js,
bgimage_src, image_src,
+ plugin_html,
build_lyrics_html(item, webkitvers))
return html
=== modified file 'openlp/core/lib/plugin.py'
--- openlp/core/lib/plugin.py 2011-06-12 16:02:52 +0000
+++ openlp/core/lib/plugin.py 2011-06-15 04:36:33 +0000
@@ -246,6 +246,12 @@
"""
pass
+ def addControllerItems(self, controller, control_panel):
+ """
+ Create items for all controller Panes
+ """
+ pass
+
def getSettingsTab(self, parent):
"""
Create a tab for the settings window to display the configurable
@@ -368,3 +374,21 @@
after this has been set.
"""
self.textStrings[name] = {u'title': title, u'tooltip': tooltip}
+
+ def getDisplayCss(self):
+ """
+ Add css style sheets to htmlbuilder
+ """
+ return u''
+
+ def getDisplayJavascript(self):
+ """
+ Add javascript functions to htmlbuilder
+ """
+ return u''
+
+ def getDisplayHtml(self):
+ """
+ Add html code to htmlbuilder
+ """
+ return u''
\ No newline at end of file
=== modified file 'openlp/core/lib/pluginmanager.py'
--- openlp/core/lib/pluginmanager.py 2011-06-12 16:02:52 +0000
+++ openlp/core/lib/pluginmanager.py 2011-06-15 04:36:33 +0000
@@ -188,6 +188,11 @@
if plugin.status is not PluginStatus.Disabled:
plugin.addToolsMenuItem(tools_menu)
+ def hook_controller_items(self, controller, control_panel):
+ for plugin in self.plugins:
+ if plugin.status is not PluginStatus.Disabled:
+ plugin.addControllerItems(controller, control_panel)
+
def initialise_plugins(self):
"""
Loop through all the plugins and give them an opportunity to
=== modified file 'openlp/core/lib/renderer.py'
--- openlp/core/lib/renderer.py 2011-06-12 16:02:52 +0000
+++ openlp/core/lib/renderer.py 2011-06-15 04:36:33 +0000
@@ -77,7 +77,7 @@
self.theme_data = None
self.bg_frame = None
self.force_page = False
- self.display = MainDisplay(None, self.image_manager, False)
+ self.display = MainDisplay(None, None, self.image_manager, False)
self.display.setup()
def update_display(self):
@@ -88,7 +88,7 @@
self._calculate_default(self.screens.current[u'size'])
if self.display:
self.display.close()
- self.display = MainDisplay(None, self.image_manager, False)
+ self.display = MainDisplay(None, None, self.image_manager, False)
self.display.setup()
self.bg_frame = None
self.theme_data = None
=== modified file 'openlp/core/ui/__init__.py'
--- openlp/core/ui/__init__.py 2011-06-12 16:02:52 +0000
+++ openlp/core/ui/__init__.py 2011-06-15 04:36:33 +0000
@@ -58,7 +58,7 @@
from filerenameform import FileRenameForm
from starttimeform import StartTimeForm
from screen import ScreenList
-from maindisplay import MainDisplay
+from maindisplay import MainDisplay, Display
from servicenoteform import ServiceNoteForm
from serviceitemeditform import ServiceItemEditForm
from slidecontroller import SlideController
=== modified file 'openlp/core/ui/maindisplay.py'
--- openlp/core/ui/maindisplay.py 2011-06-12 16:02:52 +0000
+++ openlp/core/ui/maindisplay.py 2011-06-15 04:36:33 +0000
@@ -44,12 +44,39 @@
#http://www.steveheffernan.com/html5-video-player/demo-video-player.html
#http://html5demos.com/two-videos
+class Display(QtGui.QGraphicsView):
+ """
+ This is the display screen for preview Widgets.
+ """
+ def __init__(self, parent, controller):
+ QtGui.QGraphicsView.__init__(self, parent)
+ self.controller = controller
+
+ def setup(self):
+ """
+ Set up and build the preview screen
+ """
+ self.webView = QtWebKit.QWebView(self)
+ self.webView.setGeometry(0, 0,
+ self.parent().width(), self.parent().height())
+ self.webView.settings().setAttribute(
+ QtWebKit.QWebSettings.PluginsEnabled, True)
+ self.page = self.webView.page()
+ self.frame = self.page.mainFrame()
+ screen = {}
+ screen[u'size'] = self.size()
+ serviceItem = ServiceItem()
+ self.webView.setHtml(build_html(serviceItem, screen,
+ None, None, None, self.controller.parent().pluginManager.plugins))
+ self.webView.hide()
+
class MainDisplay(QtGui.QGraphicsView):
"""
This is the display screen.
"""
- def __init__(self, parent, image_manager, live):
+ def __init__(self, parent, controller, image_manager, live):
QtGui.QGraphicsView.__init__(self, parent)
+ self.controller = controller
self.isLive = live
self.image_manager = image_manager
self.screens = ScreenList.get_instance()
@@ -69,9 +96,6 @@
QtCore.SIGNAL(u'maindisplay_hide'), self.hideDisplay)
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'maindisplay_show'), self.showDisplay)
- QtCore.QObject.connect(Receiver.get_receiver(),
- QtCore.SIGNAL(u'openlp_phonon_creation'),
- self.createMediaObject)
def retranslateUi(self):
"""
@@ -84,23 +108,15 @@
Set up and build the output screen
"""
log.debug(u'Start MainDisplay setup (live = %s)' % self.isLive)
- self.usePhonon = QtCore.QSettings().value(
- u'media/use phonon', QtCore.QVariant(True)).toBool()
- self.phononActive = False
self.screen = self.screens.current
self.setVisible(False)
self.setGeometry(self.screen[u'size'])
- self.videoWidget = Phonon.VideoWidget(self)
- self.videoWidget.setVisible(False)
- self.videoWidget.setGeometry(QtCore.QRect(0, 0,
- self.screen[u'size'].width(), self.screen[u'size'].height()))
- if self.isLive:
- if not self.firstTime:
- self.createMediaObject()
log.debug(u'Setup webView')
self.webView = QtWebKit.QWebView(self)
self.webView.setGeometry(0, 0,
self.screen[u'size'].width(), self.screen[u'size'].height())
+ self.webView.settings().setAttribute( \
+ QtWebKit.QWebSettings.PluginsEnabled, True)
self.page = self.webView.page()
self.frame = self.page.mainFrame()
QtCore.QObject.connect(self.webView,
@@ -145,7 +161,8 @@
serviceItem = ServiceItem()
serviceItem.bg_image_bytes = image_to_byte(self.initialFrame)
self.webView.setHtml(build_html(serviceItem, self.screen,
- self.alertTab, self.isLive, None))
+ self.alertTab, self.isLive, None,
+ self.controller.parent().pluginManager.plugins))
self.__hideMouse()
# To display or not to display?
if not self.screen[u'primary']:
@@ -154,24 +171,6 @@
self.primary = True
log.debug(u'Finished MainDisplay setup')
- def createMediaObject(self):
- self.firstTime = False
- log.debug(u'Creating Phonon objects - Start for %s', self.isLive)
- self.mediaObject = Phonon.MediaObject(self)
- self.audio = Phonon.AudioOutput(Phonon.VideoCategory, self.mediaObject)
- Phonon.createPath(self.mediaObject, self.videoWidget)
- Phonon.createPath(self.mediaObject, self.audio)
- QtCore.QObject.connect(self.mediaObject,
- QtCore.SIGNAL(u'stateChanged(Phonon::State, Phonon::State)'),
- self.videoState)
- QtCore.QObject.connect(self.mediaObject,
- QtCore.SIGNAL(u'finished()'),
- self.videoFinished)
- QtCore.QObject.connect(self.mediaObject,
- QtCore.SIGNAL(u'tick(qint64)'),
- self.videoTick)
- log.debug(u'Creating Phonon objects - Finished for %s', self.isLive)
-
def text(self, slide):
"""
Add the slide text from slideController
@@ -196,8 +195,8 @@
The slide text to be displayed
"""
log.debug(u'alert to display')
- if self.height() != self.screen[u'size'].height() or not \
- self.isVisible() or self.videoWidget.isVisible():
+ if self.height() != self.screen[u'size'].height() \
+ or not self.isVisible():# or self.videoWidget.isVisible():
shrink = True
else:
shrink = False
@@ -206,10 +205,7 @@
u'top' if shrink else u'')
height = self.frame.evaluateJavaScript(js)
if shrink:
- if self.phononActive:
- shrinkItem = self.webView
- else:
- shrinkItem = self
+ shrinkItem = self
if text:
alert_height = int(height.toString())
shrinkItem.resize(self.width(), alert_height)
@@ -278,131 +274,6 @@
if self.isLive:
Receiver.send_message(u'maindisplay_active')
- def resetVideo(self):
- """
- Used after Video plugin has changed the background
- """
- log.debug(u'resetVideo')
- if self.phononActive:
- self.mediaObject.stop()
- self.mediaObject.clearQueue()
- self.webView.setVisible(True)
- self.videoWidget.setVisible(False)
- self.phononActive = False
- else:
- self.frame.evaluateJavaScript(u'show_video("close");')
- self.override = {}
- # Update the preview frame.
- if self.isLive:
- Receiver.send_message(u'maindisplay_active')
-
- def videoPlay(self):
- """
- Responds to the request to play a loaded video
- """
- log.debug(u'videoPlay')
- if self.phononActive:
- self.mediaObject.play()
- else:
- self.frame.evaluateJavaScript(u'show_video("play");')
- # show screen
- if self.isLive:
- self.setVisible(True)
-
- def videoPause(self):
- """
- Responds to the request to pause a loaded video
- """
- log.debug(u'videoPause')
- if self.phononActive:
- self.mediaObject.pause()
- else:
- self.frame.evaluateJavaScript(u'show_video("pause");')
-
- def videoStop(self):
- """
- Responds to the request to stop a loaded video
- """
- log.debug(u'videoStop')
- if self.phononActive:
- self.mediaObject.stop()
- else:
- self.frame.evaluateJavaScript(u'show_video("stop");')
-
- def videoVolume(self, volume):
- """
- Changes the volume of a running video
- """
- log.debug(u'videoVolume %d' % volume)
- vol = float(volume) / float(10)
- if self.phononActive:
- self.audio.setVolume(vol)
- else:
- self.frame.evaluateJavaScript(u'show_video(null, null, %s);' %
- str(vol))
-
- def video(self, videoPath, volume, isBackground=False):
- """
- Loads and starts a video to run with the option of sound
- """
- if not self.mediaObject:
- self.createMediaObject()
- log.debug(u'video')
- self.webLoaded = True
- self.setGeometry(self.screen[u'size'])
- # We are running a background theme
- self.override[u'theme'] = u''
- self.override[u'video'] = True
- vol = float(volume) / float(10)
- if isBackground or not self.usePhonon:
- js = u'show_video("init", "%s", %s, true); show_video("play");' % \
- (videoPath.replace(u'\\', u'\\\\'), str(vol))
- self.frame.evaluateJavaScript(js)
- else:
- self.phononActive = True
- self.mediaObject.stop()
- self.mediaObject.clearQueue()
- self.mediaObject.setCurrentSource(Phonon.MediaSource(videoPath))
- # Need the timer to trigger set the trigger to 200ms
- # Value taken from web documentation.
- if self.serviceItem.end_time != 0:
- self.mediaObject.setTickInterval(200)
- self.mediaObject.play()
- self.webView.setVisible(False)
- self.videoWidget.setVisible(True)
- self.audio.setVolume(vol)
- # Update the preview frame.
- if self.isLive:
- Receiver.send_message(u'maindisplay_active')
- return self.preview()
-
- def videoState(self, newState, oldState):
- """
- Start the video at a predetermined point.
- """
- if newState == Phonon.PlayingState \
- and oldState != Phonon.PausedState \
- and self.serviceItem.start_time > 0:
- # set start time in milliseconds
- self.mediaObject.seek(self.serviceItem.start_time * 1000)
-
- def videoFinished(self):
- """
- Blank the Video when it has finished so the final frame is not left
- hanging
- """
- self.videoStop()
- self.hideDisplay(HideMode.Blank)
- self.phononActive = False
- self.videoHide = True
-
- def videoTick(self, tick):
- """
- Triggered on video tick every 200 milli seconds
- """
- if tick > self.serviceItem.end_time * 1000:
- self.videoFinished()
-
def isWebLoaded(self):
"""
Called by webView event to show display is fully loaded
@@ -483,7 +354,8 @@
else:
image_bytes = None
html = build_html(self.serviceItem, self.screen, self.alertTab,
- self.isLive, background, image_bytes)
+ self.isLive, background,
+ self.controller.parent().pluginManager.plugins, image_bytes)
log.debug(u'buildHtml - pre setHtml')
self.webView.setHtml(html)
log.debug(u'buildHtml - post setHtml')
@@ -517,8 +389,6 @@
Store the images so they can be replaced when required
"""
log.debug(u'hideDisplay mode = %d', mode)
- if self.phononActive:
- self.videoPause()
if mode == HideMode.Screen:
self.frame.evaluateJavaScript(u'show_blank("desktop");')
self.setVisible(False)
@@ -529,7 +399,6 @@
if mode != HideMode.Screen:
if self.isHidden():
self.setVisible(True)
- if self.phononActive:
self.webView.setVisible(True)
self.hideMode = mode
@@ -543,9 +412,6 @@
self.frame.evaluateJavaScript('show_blank("show");')
if self.isHidden():
self.setVisible(True)
- if self.phononActive:
- self.webView.setVisible(False)
- self.videoPlay()
self.hideMode = None
# Trigger actions when display is active again
if self.isLive:
=== modified file 'openlp/core/ui/mainwindow.py'
--- openlp/core/ui/mainwindow.py 2011-06-13 07:29:58 +0000
+++ openlp/core/ui/mainwindow.py 2011-06-15 04:36:33 +0000
@@ -581,6 +581,11 @@
self.pluginManager.hook_export_menu(self.fileExportMenu)
# Call the hook method to pull in tools menus.
self.pluginManager.hook_tools_menu(self.toolsMenu)
+ # Call the hook method to pull in plugin Controller items
+ self.pluginManager.hook_controller_items(
+ self.previewController, self.previewController.getControlPanel())
+ self.pluginManager.hook_controller_items(
+ self.liveController, self.liveController.getControlPanel())
# Call the initialise method to setup plugins.
log.info(u'initialise plugins')
self.pluginManager.initialise_plugins()
=== modified file 'openlp/core/ui/slidecontroller.py'
--- openlp/core/ui/slidecontroller.py 2011-06-12 16:02:52 +0000
+++ openlp/core/ui/slidecontroller.py 2011-06-15 04:36:33 +0000
@@ -34,7 +34,7 @@
from openlp.core.lib import OpenLPToolbar, Receiver, resize_image, \
ItemCapabilities, translate
from openlp.core.lib.ui import UiStrings, shortcut_action
-from openlp.core.ui import HideMode, MainDisplay, ScreenList
+from openlp.core.ui import HideMode, MainDisplay, Display, ScreenList
from openlp.core.utils.actions import ActionList, CategoryOrder
log = logging.getLogger(__name__)
@@ -72,7 +72,6 @@
self.songEditList = [
u'Edit Song',
]
- self.volume = 10
self.timer_id = 0
self.songEdit = False
self.selectedRow = 0
@@ -233,20 +232,6 @@
'Edit and reload song preview.'),
self.onEditSong)
self.controllerLayout.addWidget(self.toolbar)
- # Build a Media ToolBar
- self.mediabar = OpenLPToolbar(self)
- self.mediabar.addToolbarButton(
- u'Media Start', u':/slides/media_playback_start.png',
- translate('OpenLP.SlideController', 'Start playing media.'),
- self.onMediaPlay)
- self.mediabar.addToolbarButton(
- u'Media Pause', u':/slides/media_playback_pause.png',
- translate('OpenLP.SlideController', 'Start playing media.'),
- self.onMediaPause)
- self.mediabar.addToolbarButton(
- u'Media Stop', u':/slides/media_playback_stop.png',
- translate('OpenLP.SlideController', 'Start playing media.'),
- self.onMediaStop)
if self.isLive:
# Build the Song Toolbar
self.songMenu = QtGui.QToolButton(self.toolbar)
@@ -256,23 +241,6 @@
self.songMenu.setMenu(QtGui.QMenu(
translate('OpenLP.SlideController', 'Go To'), self.toolbar))
self.toolbar.makeWidgetsInvisible([u'Song Menu'])
- # Build the volumeSlider.
- self.volumeSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
- self.volumeSlider.setTickInterval(1)
- self.volumeSlider.setTickPosition(QtGui.QSlider.TicksAbove)
- self.volumeSlider.setMinimum(0)
- self.volumeSlider.setMaximum(10)
- else:
- # Build the seekSlider.
- self.seekSlider = Phonon.SeekSlider()
- self.seekSlider.setGeometry(QtCore.QRect(90, 260, 221, 24))
- self.seekSlider.setObjectName(u'seekSlider')
- self.mediabar.addToolbarWidget(u'Seek Slider', self.seekSlider)
- self.volumeSlider = Phonon.VolumeSlider()
- self.volumeSlider.setGeometry(QtCore.QRect(90, 260, 221, 24))
- self.volumeSlider.setObjectName(u'volumeSlider')
- self.mediabar.addToolbarWidget(u'Audio Volume', self.volumeSlider)
- self.controllerLayout.addWidget(self.mediabar)
# Screen preview area
self.previewFrame = QtGui.QFrame(self.splitter)
self.previewFrame.setGeometry(QtCore.QRect(0, 0, 300, 300 * self.ratio))
@@ -290,16 +258,9 @@
self.slideLayout.setSpacing(0)
self.slideLayout.setMargin(0)
self.slideLayout.setObjectName(u'SlideLayout')
- if not self.isLive:
- self.mediaObject = Phonon.MediaObject(self)
- self.video = Phonon.VideoWidget()
- self.video.setVisible(False)
- self.audio = Phonon.AudioOutput(Phonon.VideoCategory,
- self.mediaObject)
- Phonon.createPath(self.mediaObject, self.video)
- Phonon.createPath(self.mediaObject, self.audio)
- self.video.setGeometry(QtCore.QRect(0, 0, 300, 225))
- self.slideLayout.insertWidget(0, self.video)
+ self.previewDisplay = Display(self, self)
+ self.previewDisplay.setGeometry(QtCore.QRect(0, 0, 300, 300))
+ self.slideLayout.insertWidget(0, self.previewDisplay)
# Actual preview screen
self.slidePreview = QtGui.QLabel(self)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
@@ -320,8 +281,6 @@
QtCore.QObject.connect(self.previewListWidget,
QtCore.SIGNAL(u'clicked(QModelIndex)'), self.onSlideSelected)
if self.isLive:
- QtCore.QObject.connect(self.volumeSlider,
- QtCore.SIGNAL(u'sliderReleased()'), self.mediaVolume)
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'maindisplay_active'), self.updatePreview)
QtCore.QObject.connect(Receiver.get_receiver(),
@@ -333,7 +292,6 @@
QtCore.SIGNAL(u'doubleClicked(QModelIndex)'),
self.onGoLiveClick)
self.toolbar.makeWidgetsInvisible(self.songEditList)
- self.mediabar.setVisible(False)
if self.isLive:
self.setLiveHotkeys(self)
self.__addActionsToWidget(self.previewListWidget)
@@ -373,6 +331,19 @@
QtCore.SIGNAL(u'slidecontroller_%s_text_request' % self.typePrefix),
self.onTextRequest)
+ def getControlPanel(self):
+ return self.controllerLayout
+
+ def sendToPlugins(self, *args):
+ """
+ This is the generic function to send signal for control widgets,
+ created from within other plugins
+ This function is needed to catch the current controller
+ """
+ sender = self.sender().objectName() or self.sender().text()
+ controller = self
+ Receiver.send_message('%s' % sender, [controller, args])
+
def setPreviewHotkeys(self, parent=None):
self.previousItem.setObjectName(u'previousItemPreview')
self.nextItem.setObjectName(u'nextItemPreview')
@@ -409,7 +380,7 @@
def liveEscape(self):
self.display.setVisible(False)
- self.display.videoStop()
+ Receiver.send_message('media_stop', self)
def servicePrevious(self):
Receiver.send_message('servicemanager_previous_item')
@@ -425,7 +396,7 @@
# rebuild display as screen size changed
if self.display:
self.display.close()
- self.display = MainDisplay(self, self.imageManager, self.isLive)
+ self.display = MainDisplay(self, self, self.imageManager, self.isLive)
self.display.alertTab = self.alertTab
self.display.setup()
if self.isLive:
@@ -434,6 +405,10 @@
self.ratio = float(self.screens.current[u'size'].width()) / \
float(self.screens.current[u'size'].height())
self.previewSizeChanged()
+ Receiver.send_message(u'setup_display', self.display)
+ self.previewDisplay.resize(self.slidePreview.size())
+ self.previewDisplay.setup()
+ Receiver.send_message(u'setup_display', self.previewDisplay)
if self.serviceItem:
self.refreshServiceItem()
@@ -513,7 +488,6 @@
len(item.get_frames()) > 1:
self.toolbar.makeWidgetsVisible(self.loopList)
if item.is_media():
- self.toolbar.setVisible(False)
self.mediabar.setVisible(True)
def enablePreviewToolBar(self, item):
@@ -521,14 +495,9 @@
Allows the Preview toolbar to be customised
"""
self.toolbar.setVisible(True)
- self.mediabar.setVisible(False)
self.toolbar.makeWidgetsInvisible(self.songEditList)
if item.is_capable(ItemCapabilities.AllowsEdit) and item.from_plugin:
self.toolbar.makeWidgetsVisible(self.songEditList)
- elif item.is_media():
- self.toolbar.setVisible(False)
- self.mediabar.setVisible(True)
- self.volumeSlider.setAudioOutput(self.audio)
def refreshServiceItem(self):
"""
@@ -1121,72 +1090,15 @@
"""
log.debug(u'SlideController onMediaStart')
file = os.path.join(item.get_frame_path(), item.get_frame_title())
- if self.isLive:
- self.display.video(file, self.volume)
- self.volumeSlider.setValue(self.volume)
- else:
- self.mediaObject.stop()
- self.mediaObject.clearQueue()
- self.mediaObject.setCurrentSource(Phonon.MediaSource(file))
- self.seekSlider.setMediaObject(self.mediaObject)
- self.seekSlider.show()
- self.onMediaPlay()
-
- def mediaVolume(self):
- """
- Respond to the release of Volume Slider
- """
- log.debug(u'SlideController mediaVolume')
- self.volume = self.volumeSlider.value()
- self.display.videoVolume(self.volume)
-
- def onMediaPause(self):
- """
- Respond to the Pause from the media Toolbar
- """
- log.debug(u'SlideController onMediaPause')
- if self.isLive:
- self.display.videoPause()
- else:
- self.mediaObject.pause()
-
- def onMediaPlay(self):
- """
- Respond to the Play from the media Toolbar
- """
- log.debug(u'SlideController onMediaPlay')
- if self.isLive:
- self.display.videoPlay()
- else:
- self.slidePreview.hide()
- self.video.show()
- self.mediaObject.play()
-
- def onMediaStop(self):
- """
- Respond to the Stop from the media Toolbar
- """
- log.debug(u'SlideController onMediaStop')
- if self.isLive:
- self.display.videoStop()
- else:
- self.mediaObject.stop()
- self.video.hide()
- self.slidePreview.clear()
- self.slidePreview.show()
+ Receiver.send_message(u'media_video', [self, file, False])
+ self.slidePreview.hide()
def onMediaClose(self):
"""
Respond to a request to close the Video
"""
- log.debug(u'SlideController onMediaStop')
- if self.isLive:
- self.display.resetVideo()
- else:
- self.mediaObject.stop()
- self.mediaObject.clearQueue()
- self.video.hide()
- self.slidePreview.clear()
+ log.debug(u'SlideController onMediaClose')
+ Receiver.send_message(u'media_reset', self)
self.slidePreview.show()
def _resetBlank(self):
=== modified file 'openlp/plugins/media/lib/__init__.py'
--- openlp/plugins/media/lib/__init__.py 2011-06-12 16:02:52 +0000
+++ openlp/plugins/media/lib/__init__.py 2011-06-15 04:36:33 +0000
@@ -25,7 +25,41 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
+class MediaState(object):
+ """
+ An enumeration for possible States of the Media Player
+ (copied partially from Phonon::State)
+ """
+ Loading = 0
+ Stopped = 1
+ Playing = 2
+ Paused = 4
+ Off = 6
+
+class MediaType(object):
+ """
+ """
+ Audio = 0
+ Video = 1
+ Cd = 3
+ Dvd = 4
+
+class MediaInfo(object):
+ """
+ This class hold the media related infos
+ """
+ file_info = None
+ volume = 100
+ isFlash = False
+ is_background = False
+ length = 0
+ start_time = 0
+ end_time = 0
+ media_type = MediaType()
+
from mediaitem import MediaMediaItem
from mediatab import MediaTab
+from mediaapi import MediaAPI
+from mediamanager import MediaManager
__all__ = ['MediaMediaItem']
=== added file 'openlp/plugins/media/lib/mediaapi.py'
--- openlp/plugins/media/lib/mediaapi.py 1970-01-01 00:00:00 +0000
+++ openlp/plugins/media/lib/mediaapi.py 2011-06-15 04:36:33 +0000
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2011 Raoul Snyman #
+# Portions copyright (c) 2008-2011 Tim Bentley, Gerald Britton, Jonathan #
+# Corwin, Michael Gorven, Scott Guerrieri, Matthias Hub, Meinert Jordan, #
+# Armin Köhler, Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias #
+# Põldaru, Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Frode Woldsund #
+# --------------------------------------------------------------------------- #
+# This program is free software; you can redistribute it and/or modify it #
+# under the terms of the GNU General Public License as published by the Free #
+# Software Foundation; version 2 of the License. #
+# #
+# This program is distributed in the hope that it will be useful, but WITHOUT #
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
+# more details. #
+# #
+# You should have received a copy of the GNU General Public License along #
+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
+###############################################################################
+
+from openlp.plugins.media.lib import MediaState
+
+class MediaAPI(object):
+ """
+ Specialiced Media API class
+ to reflect Features of the related API
+ """
+ def __init__(self, parent, name=u'MediaApi'):
+ self.parent = parent
+ self.name = name
+ self.available = self.check_available()
+ self.isActive = False
+ self.canBackground = False
+ self.state = MediaState.Off
+ self.hasOwnWidget = False
+ self.audio_extensions_list = []
+ self.video_extensions_list = []
+
+ def check_available(self):
+ """
+ API is available on this machine
+ """
+ return False
+
+
+ def setup(self, display):
+ """
+ Create the related widgets for the current display
+ """
+ pass
+
+ def load(self, display):
+ """
+ Load a new media file and check if it is valid
+ """
+ return True
+
+ def resize(self, display):
+ """
+ If the main display size or position is changed,
+ the media widgets should also resized
+ """
+ pass
+
+ def play(self, display):
+ """
+ Starts playing of current Media File
+ """
+ pass
+
+ def pause(self, display):
+ """
+ Pause of current Media File
+ """
+ pass
+
+ def stop(self, display):
+ """
+ Stop playing of current Media File
+ """
+ pass
+
+ def volume(self, display, vol):
+ """
+ Change volume of current Media File
+ """
+ pass
+
+ def seek(self, display, seekVal):
+ """
+ Change playing position of current Media File
+ """
+ pass
+
+ def reset(self, display):
+ """
+ Remove the current loaded video
+ """
+ pass
+
+ def set_visible(self, display, status):
+ """
+ Show/Hide the media widgets
+ """
+ pass
+
+ def update_ui(self, display):
+ """
+ Do some ui related stuff
+ (e.g. update the seek slider)
+ """
+ pass
+
+ def getDisplayCss(self):
+ """
+ Add css style sheets to htmlbuilder
+ """
+ return u''
+
+
+ def getDisplayJavascript(self):
+ """
+ Add javascript functions to htmlbuilder
+ """
+ return u''
+
+
+ def getDisplayHtml(self):
+ """
+ Add html code to htmlbuilder
+ """
+ return u''
=== modified file 'openlp/plugins/media/lib/mediaitem.py'
--- openlp/plugins/media/lib/mediaitem.py 2011-06-12 17:56:11 +0000
+++ openlp/plugins/media/lib/mediaitem.py 2011-06-15 04:36:33 +0000
@@ -25,7 +25,6 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
###############################################################################
-from datetime import datetime
import logging
import os
import locale
@@ -57,9 +56,6 @@
QtCore.QObject.connect(Receiver.get_receiver(),
QtCore.SIGNAL(u'video_background_replaced'),
self.videobackgroundReplaced)
- QtCore.QObject.connect(Receiver.get_receiver(),
- QtCore.SIGNAL(u'openlp_phonon_creation'),
- self.createPhonon)
def retranslateUi(self):
self.onNewPrompt = translate('MediaPlugin.MediaItem', 'Select Media')
@@ -95,7 +91,8 @@
Called to reset the Live backgound with the media selected,
"""
self.resetAction.setVisible(False)
- self.plugin.liveController.display.resetVideo()
+ Receiver.send_message(u'media_reset',
+ self.plugin.liveController)
def videobackgroundReplaced(self):
"""
@@ -114,7 +111,8 @@
filename = unicode(item.data(QtCore.Qt.UserRole).toString())
if os.path.exists(filename):
(path, name) = os.path.split(filename)
- self.plugin.liveController.display.video(filename, 0, True)
+ Receiver.send_message(u'media_video',
+ [self.plugin.liveController, filename, 0, True])
self.resetAction.setVisible(True)
else:
critical_error_message_box(UiStrings().LiveBGError,
@@ -135,29 +133,14 @@
unicode(translate('MediaPlugin.MediaItem',
'The file %s no longer exists.')) % filename)
return False
- self.mediaObject.stop()
- self.mediaObject.clearQueue()
- self.mediaObject.setCurrentSource(Phonon.MediaSource(filename))
- if not self.mediaStateWait(Phonon.StoppedState):
- critical_error_message_box(UiStrings().UnsupportedFile,
- UiStrings().UnsupportedFile)
- return False
- # File too big for processing
- if os.path.getsize(filename) <= 52428800: # 50MiB
- self.mediaObject.play()
- if not self.mediaStateWait(Phonon.PlayingState) \
- or self.mediaObject.currentSource().type() \
- == Phonon.MediaSource.Invalid:
- self.mediaObject.stop()
- critical_error_message_box(UiStrings().UnsupportedFile,
- UiStrings().UnsupportedFile)
- return False
- self.mediaObject.stop()
- service_item.media_length = self.mediaObject.totalTime() / 1000
- service_item.add_capability(
+ self.mediaLength = 0
+ service_item.media_length = self.mediaLength
+ service_item.add_capability(
ItemCapabilities.AllowsVariableStartTime)
service_item.title = unicode(self.plugin.nameStrings[u'singular'])
service_item.add_capability(ItemCapabilities.RequiresMedia)
+ # TODO
+ #Receiver.send_message(u'media_video', [self.plugin.liveController, filename, False])
# force a non-existent theme
service_item.theme = -1
frame = u':/media/image_clapperboard.png'
@@ -165,20 +148,6 @@
service_item.add_from_command(path, name, frame)
return True
- def mediaStateWait(self, mediaState):
- """
- Wait for the video to change its state
- Wait no longer than 5 seconds.
- """
- start = datetime.now()
- while self.mediaObject.state() != mediaState:
- if self.mediaObject.state() == Phonon.ErrorState:
- return False
- Receiver.send_message(u'openlp_process_events')
- if (datetime.now() - start).seconds > 5:
- return False
- return True
-
def initialise(self):
self.listView.clear()
self.listView.setIconSize(QtCore.QSize(88, 50))
@@ -210,11 +179,6 @@
item_name.setData(QtCore.Qt.UserRole, QtCore.QVariant(file))
self.listView.addItem(item_name)
- def createPhonon(self):
- log.debug(u'CreatePhonon')
- if not self.mediaObject:
- self.mediaObject = Phonon.MediaObject(self)
-
def search(self, string):
files = SettingsManager.load_list(self.settingsSection, u'media')
results = []
=== added file 'openlp/plugins/media/lib/mediamanager.py'
--- openlp/plugins/media/lib/mediamanager.py 1970-01-01 00:00:00 +0000
+++ openlp/plugins/media/lib/mediamanager.py 2011-06-15 04:36:33 +0000
@@ -0,0 +1,404 @@
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2011 Raoul Snyman #
+# Portions copyright (c) 2008-2011 Tim Bentley, Gerald Britton, Jonathan #
+# Corwin, Michael Gorven, Scott Guerrieri, Matthias Hub, Meinert Jordan, #
+# Armin Köhler, Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias #
+# Põldaru, Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Frode Woldsund #
+# --------------------------------------------------------------------------- #
+# This program is free software; you can redistribute it and/or modify it #
+# under the terms of the GNU General Public License as published by the Free #
+# Software Foundation; version 2 of the License. #
+# #
+# This program is distributed in the hope that it will be useful, but WITHOUT #
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
+# more details. #
+# #
+# You should have received a copy of the GNU General Public License along #
+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
+###############################################################################
+
+import logging
+
+import sys, os,time
+from PyQt4 import QtCore, QtGui, QtWebKit
+
+from openlp.core.lib import OpenLPToolbar, Receiver, translate
+from openlp.core.lib.ui import UiStrings, critical_error_message_box
+from openlp.plugins.media.lib import MediaAPI, MediaState, MediaInfo
+
+log = logging.getLogger(__name__)
+
+class MediaManager(object):
+ """
+ The implementation of a Media Manager
+ The idea is to separate the media related implementation
+ into the plugin files and unify the access from other parts of code
+ The media manager adds an own class for every API
+ Currently these are QtWebkit, Phonon and planed Vlc.
+ Manager
+ - different API classes with specialised Access functions
+
+ Controller
+ - have general and API specific control Elements
+ - have one or more displays (Preview, Live, ...) with different settings
+
+ Display
+ - have API-Specific Display Elements
+ - have media info for current media
+ """
+
+ def __init__(self, parent):
+ self.parent = parent
+ self.APIs = {}
+ self.controller = []
+ self.curDisplayMediaAPI = {}
+ #Timer for video state
+ self.Timer = QtCore.QTimer()
+ self.Timer.setInterval(200)
+ self.withLivePreview = False
+ #Signals
+ QtCore.QObject.connect(self.Timer,
+ QtCore.SIGNAL("timeout()"), self.video_state)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'setup_display'), self.setup_display)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'media_video'), self.video)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'Media Start'), self.video_play)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'Media Pause'), self.video_pause)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'Media Stop'), self.video_stop)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'seekSlider'), self.video_seek)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'volumeSlider'), self.video_volume)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'media_reset'), self.video_reset)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'media_hide'), self.video_hide)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'media_blank'), self.video_blank)
+ QtCore.QObject.connect(Receiver.get_receiver(),
+ QtCore.SIGNAL(u'media_unblank'), self.video_unblank)
+
+ def video_state(self):
+ """
+ Check if there is an assigned media API and do some
+ updating stuff (e.g. update the UI)
+ """
+ isAnyonePlaying = False
+ if len(self.curDisplayMediaAPI.keys()) == 0:
+ self.Timer.stop()
+ else:
+ for display in self.curDisplayMediaAPI.keys():
+ self.curDisplayMediaAPI[display].update_ui(display)
+ if self.curDisplayMediaAPI[display] \
+ .state == MediaState.Playing:
+ isAnyonePlaying = True
+ if not isAnyonePlaying:
+ self.Timer.stop()
+
+ def getDisplayCss(self):
+ """
+ Add css style sheets to htmlbuilder
+ """
+ css = u'';
+ for api in self.APIs.values():
+ css += api.getDisplayCss()
+ return css
+
+ def getDisplayJavascript(self):
+ """
+ Add javascript functions to htmlbuilder
+ """
+ js = u''
+ for api in self.APIs.values():
+ js += api.getDisplayJavascript()
+ return js
+
+ def getDisplayHtml(self):
+ """
+ Add html code to htmlbuilder
+ """
+ html = u''
+ for api in self.APIs.values():
+ html += api.getDisplayHtml()
+ return html
+
+ def addControllerItems(self, controller, control_panel):
+ self.controller.append(controller)
+ self.setup_generic_controls(controller, control_panel)
+ for api in self.APIs.values():
+ api.setup_controls(controller, control_panel)
+
+ def setup_generic_controls(self, controller, control_panel):
+ controller.media_info = MediaInfo()
+ # Build a Media ToolBar
+ controller.mediabar = OpenLPToolbar(controller)
+ controller.mediabar.addToolbarButton(
+ u'Media Start', u':/slides/media_playback_start.png',
+ translate('OpenLP.SlideController', 'Start playing media'),
+ controller.sendToPlugins)
+ controller.mediabar.addToolbarButton(
+ u'Media Pause', u':/slides/media_playback_pause.png',
+ translate('OpenLP.SlideController', 'Pause playing media'),
+ controller.sendToPlugins)
+ controller.mediabar.addToolbarButton(
+ u'Media Stop', u':/slides/media_playback_stop.png',
+ translate('OpenLP.SlideController', 'Stop playing media'),
+ controller.sendToPlugins)
+ # Build the seekSlider.
+ controller.seekSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
+ controller.seekSlider.setMaximum(1000)
+ # Build the volumeSlider.
+ controller.volumeSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
+ controller.volumeSlider.setTickInterval(10)
+ controller.volumeSlider.setTickPosition(QtGui.QSlider.TicksAbove)
+ controller.volumeSlider.setMinimum(0)
+ controller.volumeSlider.setMaximum(100)
+ controller.volumeSlider.setValue(controller.media_info.volume)
+ controller.seekSlider.setGeometry(QtCore.QRect(90, 260, 221, 24))
+ controller.seekSlider.setObjectName(u'seekSlider')
+ controller.mediabar.addToolbarWidget(u'Seek Slider', controller.seekSlider)
+ controller.volumeSlider.setGeometry(QtCore.QRect(90, 160, 221, 24))
+ controller.volumeSlider.setObjectName(u'volumeSlider')
+ controller.mediabar.addToolbarWidget(u'Audio Volume', controller.volumeSlider)
+ control_panel.addWidget(controller.mediabar)
+ controller.mediabar.setVisible(False)
+ #Signals
+ QtCore.QObject.connect(controller.seekSlider,
+ QtCore.SIGNAL(u'sliderMoved(int)'), controller.sendToPlugins)
+ QtCore.QObject.connect(controller.volumeSlider,
+ QtCore.SIGNAL(u'sliderMoved(int)'), controller.sendToPlugins)
+
+ def setup_display(self, display):
+ """
+ After a new display is configured, all media related widget
+ will be created too
+ """
+ display.hasAudio = True
+ if not self.withLivePreview and \
+ display == self.parent.liveController.previewDisplay:
+ return
+ if display == self.parent.previewController.previewDisplay or \
+ display == self.parent.liveController.previewDisplay:
+ display.resize(display.controller.slidePreview.size())
+ display.hasAudio = False
+ for api in self.APIs.values():
+ api.setup(display)
+
+ def set_controls_visible(self, controller, value):
+ # Generic controls
+ controller.mediabar.setVisible(value)
+ # Special controls
+ # TODO
+# for api in self.APIs.values():
+# api.setup_controls(controller, control_panel)
+
+ def resize(self, controller, display, api):
+ """
+ After Mainwindow changes or Splitter moved all related media
+ widgets have to be resized
+ """
+ if display == self.parent.previewController.previewDisplay or \
+ display == self.parent.liveController.previewDisplay:
+ display.resize(controller.slidePreview.size())
+ api.resize(display)
+
+ def video(self, msg):
+ """
+ Loads and starts a video to run with the option of sound
+ """
+ log.debug(u'video')
+ controller = msg[0]
+ isValid = False
+ # stop running videos
+ self.video_reset(controller)
+ controller.media_info = MediaInfo()
+ controller.media_info.volume = controller.volumeSlider.value()
+ controller.media_info.file_info = QtCore.QFileInfo(msg[1])
+ controller.media_info.is_background = msg[2]
+ if controller.isLive:
+ if self.withLivePreview:
+ display = controller.previewDisplay
+ isValid = self.check_file_type(controller, display)
+ display = controller.display
+ isValid = self.check_file_type(controller, display)
+ else:
+ display = controller.previewDisplay
+ isValid = self.check_file_type(controller, display)
+ if not isValid:
+ #Media could not be loaded correctly
+ critical_error_message_box(
+ translate('MediaPlugin.MediaItem', 'Unsupported File'),
+ unicode(translate('MediaPlugin.MediaItem',
+ 'Unsupported File')))
+ return
+ #now start playing
+ self.video_play([controller])
+ self.video_pause([controller])
+ self.video_seek([controller, [0]])
+ self.video_play([controller])
+ self.set_controls_visible(controller, True)
+ log.debug(u'use %s controller' % self.curDisplayMediaAPI[display])
+ print u'use %s controller' % self.curDisplayMediaAPI[display].name
+
+ def check_file_type(self, controller, display):
+ """
+ Used to choose the right media API type
+ from the prioritized API list
+ """
+ apiSettings = str(QtCore.QSettings().value(u'media/apis',
+ QtCore.QVariant(u'Webkit')).toString())
+ usedAPIs = apiSettings.split(u',')
+ if controller.media_info.file_info.isFile():
+ suffix = u'*.%s' % controller.media_info.file_info.suffix()
+ for title in usedAPIs:
+ api = self.APIs[title]
+ if suffix in api.video_extensions_list:
+ if not controller.media_info.is_background or \
+ controller.media_info.is_background and api.canBackground:
+ self.resize(controller, display, api)
+ if api.load(display):
+ self.curDisplayMediaAPI[display] = api
+ return True
+ # no valid api found
+ return False
+
+ def video_play(self, msg):
+ """
+ Responds to the request to play a loaded video
+ """
+ log.debug(u'video_play')
+ controller = msg[0]
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].play(display)
+ # Start Timer for ui updates
+ if not self.Timer.isActive():
+ self.Timer.start()
+
+ def video_pause(self, msg):
+ """
+ Responds to the request to pause a loaded video
+ """
+ log.debug(u'videoPause')
+ controller = msg[0]
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].pause(display)
+
+ def video_stop(self, msg):
+ """
+ Responds to the request to stop a loaded video
+ """
+ log.debug(u'video_stop')
+ controller = msg[0]
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].stop(display)
+ self.curDisplayMediaAPI[display].set_visible(display, False)
+
+ def video_volume(self, msg):
+ """
+ Changes the volume of a running video
+ """
+ controller = msg[0]
+ vol = msg[1][0]
+ log.debug(u'video_volume %d' % vol)
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].volume(display, vol)
+
+ def video_seek(self, msg):
+ """
+ Responds to the request to change the seek Slider of a loaded video
+ """
+ log.debug(u'video_seek')
+ controller = msg[0]
+ seekVal = msg[1][0]
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].seek(display, seekVal)
+
+ def video_reset(self, controller):
+ """
+ Responds to the request to reset a loaded video
+ """
+ log.debug(u'video_reset')
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ self.curDisplayMediaAPI[display].reset(display)
+ del self.curDisplayMediaAPI[display]
+ self.set_controls_visible(controller, False)
+
+ def video_hide(self, msg):
+ """
+ Hide the related video Widget
+ """
+ isLive = msg[1]
+ if isLive:
+ controller = self.parent.liveController
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ if self.curDisplayMediaAPI[display] \
+ .state == MediaState.Playing:
+ self.curDisplayMediaAPI[display].pause(display)
+ self.curDisplayMediaAPI[display] \
+ .set_visible(display, False)
+
+ def video_blank(self, msg):
+ """
+ Blank the related video Widget
+ """
+ isLive = msg[1]
+ if isLive:
+ controller = self.parent.liveController
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ if self.curDisplayMediaAPI[display] \
+ .state == MediaState.Playing:
+ self.curDisplayMediaAPI[display].pause(display)
+ self.curDisplayMediaAPI[display] \
+ .set_visible(display, False)
+
+ def video_unblank(self, msg):
+ """
+ Unblank the related video Widget
+ """
+ Receiver.send_message(u'maindisplay_show')
+ isLive = msg[1]
+ if isLive:
+ controller = self.parent.liveController
+ for display in self.curDisplayMediaAPI.keys():
+ if display.controller == controller:
+ if self.curDisplayMediaAPI[display] \
+ .state == MediaState.Paused:
+ self.curDisplayMediaAPI[display].play(display)
+ self.curDisplayMediaAPI[display] \
+ .set_visible(display, True)
+
+ def get_audio_extensions_list(self):
+ audio_list = []
+ for api in self.APIs.values():
+ for item in api.audio_extensions_list:
+ if not item in audio_list:
+ audio_list.append(item)
+ return audio_list
+
+ def get_video_extensions_list(self):
+ video_list = []
+ for api in self.APIs.values():
+ for item in api.video_extensions_list:
+ if not item in video_list:
+ video_list.append(item)
+ return video_list
=== modified file 'openlp/plugins/media/lib/mediatab.py'
--- openlp/plugins/media/lib/mediatab.py 2011-06-12 16:02:52 +0000
+++ openlp/plugins/media/lib/mediatab.py 2011-06-15 04:36:33 +0000
@@ -33,46 +33,142 @@
"""
MediaTab is the Media settings tab in the settings dialog.
"""
- def __init__(self, parent, title, visible_title, icon_path):
+ def __init__(self, parent, title, visible_title, apis, icon_path):
+ self.apis = apis
SettingsTab.__init__(self, parent, title, visible_title, icon_path)
def setupUi(self):
self.setObjectName(u'MediaTab')
SettingsTab.setupUi(self)
- self.mediaModeGroupBox = QtGui.QGroupBox(self.leftColumn)
- self.mediaModeGroupBox.setObjectName(u'mediaModeGroupBox')
- self.mediaModeLayout = QtGui.QFormLayout(self.mediaModeGroupBox)
- self.mediaModeLayout.setObjectName(u'mediaModeLayout')
- self.usePhononCheckBox = QtGui.QCheckBox(self.mediaModeGroupBox)
- self.usePhononCheckBox.setObjectName(u'usePhononCheckBox')
- self.mediaModeLayout.addRow(self.usePhononCheckBox)
- self.leftLayout.addWidget(self.mediaModeGroupBox)
+ self.mediaAPIGroupBox = QtGui.QGroupBox(self.leftColumn)
+ self.mediaAPIGroupBox.setObjectName(u'mediaAPIGroupBox')
+ self.mediaApiLayout = QtGui.QVBoxLayout(self.mediaAPIGroupBox)
+ self.mediaApiLayout.setObjectName(u'mediaApiLayout')
+ self.ApiCheckBoxes = {}
+ for key in self.apis:
+ api = self.apis[key]
+ checkbox = QtGui.QCheckBox(self.mediaAPIGroupBox)
+ checkbox.setEnabled(api.available)
+ checkbox.setObjectName(api.name + u'CheckBox')
+ self.ApiCheckBoxes[api.name] = checkbox
+ self.mediaApiLayout.addWidget(checkbox)
+ self.leftLayout.addWidget(self.mediaAPIGroupBox)
+
+ self.apiOrderGroupBox = QtGui.QGroupBox(self.leftColumn)
+ self.apiOrderGroupBox.setObjectName(u'apiOrderGroupBox')
+ self.apiOrderLayout = QtGui.QVBoxLayout(self.apiOrderGroupBox)
+ self.apiOrderLayout.setObjectName(u'apiOrderLayout')
+ self.apiOrderlistWidget = QtGui.QListWidget( \
+ self.apiOrderGroupBox)
+ sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum,
+ QtGui.QSizePolicy.Expanding)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ sizePolicy.setHeightForWidth(self.apiOrderlistWidget. \
+ sizePolicy().hasHeightForWidth())
+ self.apiOrderlistWidget.setSizePolicy(sizePolicy)
+
+ self.apiOrderlistWidget.setVerticalScrollBarPolicy( \
+ QtCore.Qt.ScrollBarAsNeeded)
+ self.apiOrderlistWidget.setHorizontalScrollBarPolicy( \
+ QtCore.Qt.ScrollBarAlwaysOff)
+ self.apiOrderlistWidget.setEditTriggers( \
+ QtGui.QAbstractItemView.NoEditTriggers)
+ self.apiOrderlistWidget.setObjectName(u'apiOrderlistWidget')
+ self.apiOrderLayout.addWidget(self.apiOrderlistWidget)
+ self.orderingButtonsWidget = QtGui.QWidget(self.apiOrderGroupBox)
+ self.orderingButtonsWidget.setObjectName(u'orderingButtonsWidget')
+ self.orderingButtonLayout = QtGui.QHBoxLayout( \
+ self.orderingButtonsWidget)
+ self.orderingButtonLayout.setObjectName(u'orderingButtonLayout')
+ self.orderingDownButton = QtGui.QPushButton(self.orderingButtonsWidget)
+ self.orderingDownButton.setObjectName(u'orderingDownButton')
+ self.orderingButtonLayout.addWidget(self.orderingDownButton)
+ self.orderingUpButton = QtGui.QPushButton(self.apiOrderGroupBox)
+ self.orderingUpButton.setObjectName(u'orderingUpButton')
+ self.orderingButtonLayout.addWidget(self.orderingUpButton)
+ self.apiOrderLayout.addWidget(self.orderingButtonsWidget)
+ self.leftLayout.addWidget(self.apiOrderGroupBox)
self.leftLayout.addStretch()
self.rightLayout.addStretch()
- QtCore.QObject.connect(self.usePhononCheckBox,
- QtCore.SIGNAL(u'stateChanged(int)'),
- self.onUsePhononCheckBoxChanged)
+ for key in self.apis:
+ api = self.apis[key]
+ checkbox = self.ApiCheckBoxes[api.name]
+ QtCore.QObject.connect(checkbox,
+ QtCore.SIGNAL(u'stateChanged(int)'),
+ self.onApiCheckBoxChanged)
+ QtCore.QObject.connect(self.orderingUpButton,
+ QtCore.SIGNAL(u'pressed()'), self.onOrderingUpButtonPressed)
+ QtCore.QObject.connect(self.orderingDownButton,
+ QtCore.SIGNAL(u'pressed()'), self.onOrderingDownButtonPressed)
def retranslateUi(self):
- self.mediaModeGroupBox.setTitle(
- translate('MediaPlugin.MediaTab', 'Media Display'))
- self.usePhononCheckBox.setText(
- translate('MediaPlugin.MediaTab', 'Use Phonon for video playback'))
-
- def onUsePhononCheckBoxChanged(self, check_state):
- self.usePhonon = (check_state == QtCore.Qt.Checked)
- self.usePhononChanged = True
+ self.mediaAPIGroupBox.setTitle(
+ translate('MediaPlugin.MediaTab', 'Media APIs'))
+ for key in self.apis:
+ api = self.apis[key]
+ checkbox = self.ApiCheckBoxes[api.name]
+ if api.available:
+ checkbox.setText(api.name)
+ else:
+ checkbox.setText(
+ unicode(translate('MediaPlugin.MediaTab',
+ '%s (unavailable)')) % api.name)
+ self.apiOrderGroupBox.setTitle(
+ translate('MediaPlugin.MediaTab', 'API Order'))
+ self.orderingDownButton.setText(
+ translate('MediaPlugin.MediaTab', 'Down'))
+ self.orderingUpButton.setText(
+ translate('MediaPlugin.MediaTab', 'Up'))
+
+ def onApiCheckBoxChanged(self, check_state):
+ api = self.sender().text()
+ if check_state == QtCore.Qt.Checked:
+ if api not in self.usedAPIs:
+ self.usedAPIs.append(api)
+ else:
+ self.usedAPIs.takeAt(self.usedAPIs.indexOf(api))
+ self.updateApiList()
+
+ def updateApiList(self):
+ self.apiOrderlistWidget.clear()
+ for api in self.usedAPIs:
+ if api in self.ApiCheckBoxes.keys():
+ self.apiOrderlistWidget.addItem(api)
+
+ def onOrderingUpButtonPressed(self):
+ currentRow = self.apiOrderlistWidget.currentRow()
+ if currentRow > 0:
+ item = self.apiOrderlistWidget.takeItem(currentRow)
+ self.apiOrderlistWidget.insertItem(currentRow - 1, item)
+ self.apiOrderlistWidget.setCurrentRow(currentRow - 1)
+ self.usedAPIs.move(currentRow, currentRow - 1)
+
+ def onOrderingDownButtonPressed(self):
+ currentRow = self.apiOrderlistWidget.currentRow()
+ if currentRow < self.apiOrderlistWidget.count() - 1:
+ item = self.apiOrderlistWidget.takeItem(currentRow)
+ self.apiOrderlistWidget.insertItem(currentRow + 1, item)
+ self.apiOrderlistWidget.setCurrentRow(currentRow + 1)
+ self.usedAPIs.move(currentRow, currentRow + 1)
def load(self):
- self.usePhonon = QtCore.QSettings().value(
- self.settingsSection + u'/use phonon',
- QtCore.QVariant(True)).toBool()
- self.usePhononCheckBox.setChecked(self.usePhonon)
+ self.usedAPIs = QtCore.QSettings().value(
+ self.settingsSection + u'/apis',
+ QtCore.QVariant(u'Webkit')).toString().split(u',')
+ for key in self.apis:
+ api = self.apis[key]
+ checkbox = self.ApiCheckBoxes[api.name]
+ if api.available and api.name in self.usedAPIs:
+ checkbox.setChecked(True)
+ self.updateApiList()
def save(self):
- oldUsePhonon = QtCore.QSettings().value(
- u'media/use phonon', QtCore.QVariant(True)).toBool()
- if oldUsePhonon != self.usePhonon:
- QtCore.QSettings().setValue(self.settingsSection + u'/use phonon',
- QtCore.QVariant(self.usePhonon))
+ oldApiString = QtCore.QSettings().value(
+ self.settingsSection + u'/apis',
+ QtCore.QVariant(u'Webkit')).toString()
+ newApiString = self.usedAPIs.join(u',')
+ if oldApiString != newApiString:
+ QtCore.QSettings().setValue(self.settingsSection + u'/apis',
+ QtCore.QVariant(newApiString))
Receiver.send_message(u'config_screen_changed')
=== added file 'openlp/plugins/media/lib/phononapi.py'
--- openlp/plugins/media/lib/phononapi.py 1970-01-01 00:00:00 +0000
+++ openlp/plugins/media/lib/phononapi.py 2011-06-15 04:36:33 +0000
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2011 Raoul Snyman #
+# Portions copyright (c) 2008-2011 Tim Bentley, Gerald Britton, Jonathan #
+# Corwin, Michael Gorven, Scott Guerrieri, Matthias Hub, Meinert Jordan, #
+# Armin Köhler, Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias #
+# Põldaru, Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Frode Woldsund #
+# --------------------------------------------------------------------------- #
+# This program is free software; you can redistribute it and/or modify it #
+# under the terms of the GNU General Public License as published by the Free #
+# Software Foundation; version 2 of the License. #
+# #
+# This program is distributed in the hope that it will be useful, but WITHOUT #
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
+# more details. #
+# #
+# You should have received a copy of the GNU General Public License along #
+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
+###############################################################################
+
+import logging
+import mimetypes
+from datetime import datetime
+
+from PyQt4 import QtCore, QtGui
+from PyQt4.phonon import Phonon
+
+from openlp.core.lib import Receiver
+from openlp.plugins.media.lib import MediaAPI, MediaState
+
+log = logging.getLogger(__name__)
+
+class PhononAPI(MediaAPI):
+ """
+ Specialiced MediaAPI class
+ to reflect Features of the Phonon API
+ """
+
+ def __init__(self, parent):
+ MediaAPI.__init__(self, parent, u'Phonon')
+ self.parent = parent
+ self.additional_extensions = {
+ u'audio/ac3': [u'.ac3'],
+ u'audio/flac': [u'.flac'],
+ u'audio/x-m4a': [u'.m4a'],
+ u'audio/midi': [u'.mid', u'.midi'],
+ u'audio/x-mp3': [u'.mp3'],
+ u'audio/mpeg': [u'.mp3', u'.mp2', u'.mpga', u'.mpega', u'.m4a'],
+ u'audio/qcelp': [u'.qcp'],
+ u'audio/x-wma': [u'.wma'],
+ u'audio/x-ms-wma': [u'.wma'],
+ u'video/x-flv': [u'.flv'],
+ u'video/x-matroska': [u'.mpv', u'.mkv'],
+ u'video/x-wmv': [u'.wmv'],
+ u'video/x-mpg': [u'.mpg'],
+ u'video/x-ms-wmv': [u'.wmv']}
+ mimetypes.init()
+ for mimetype in Phonon.BackendCapabilities.availableMimeTypes():
+ mimetype = unicode(mimetype)
+ if mimetype.startswith(u'audio/'):
+ self._addToList(self.audio_extensions_list, mimetype)
+ elif mimetype.startswith(u'video/'):
+ self._addToList(self.video_extensions_list, mimetype)
+
+ def _addToList(self, list, mimetype):
+ # Add all extensions which mimetypes provides us for supported types.
+ extensions = mimetypes.guess_all_extensions(unicode(mimetype))
+ for extension in extensions:
+ ext = u'*%s' % extension
+ if ext not in list:
+ list.append(ext)
+ self.parent.serviceManager.supportedSuffixes(extension[1:])
+ log.info(u'MediaPlugin: %s extensions: %s' % (mimetype,
+ u' '.join(extensions)))
+ # Add extensions for this mimetype from self.additional_extensions.
+ # This hack clears mimetypes' and operating system's shortcomings
+ # by providing possibly missing extensions.
+ if mimetype in self.additional_extensions.keys():
+ for extension in self.additional_extensions[mimetype]:
+ ext = u'*%s' % extension
+ if ext not in list:
+ list.append(ext)
+ self.parent.serviceManager.supportedSuffixes(extension[1:])
+ log.info(u'MediaPlugin: %s additional extensions: %s' % (mimetype,
+ u' '.join(self.additional_extensions[mimetype])))
+
+ def setup_controls(self, controller, control_panel):
+ pass
+
+ def setup(self, display):
+ display.phononWidget = Phonon.VideoWidget(display)
+ display.phononWidget.setVisible(False)
+ display.phononWidget.resize(display.size())
+ display.mediaObject = Phonon.MediaObject(display)
+ display.audio = Phonon.AudioOutput( \
+ Phonon.VideoCategory, display.mediaObject)
+ Phonon.createPath(display.mediaObject, display.phononWidget)
+ Phonon.createPath(display.mediaObject, display.audio)
+ display.phononWidget.raise_()
+ display.phononWidget.hide()
+ self.hasOwnWidget = True
+
+ def check_available(self):
+ return True
+
+ def get_supported_file_types(self):
+ self.supported_file_types = ['avi']
+ self.additional_extensions = {
+ u'audio/ac3': [u'.ac3'],
+ u'audio/flac': [u'.flac'],
+ u'audio/x-m4a': [u'.m4a'],
+ u'audio/midi': [u'.mid', u'.midi'],
+ u'audio/x-mp3': [u'.mp3'],
+ u'audio/mpeg': [u'.mp3', u'.mp2', u'.mpga', u'.mpega', u'.m4a'],
+ u'audio/qcelp': [u'.qcp'],
+ u'audio/x-wma': [u'.wma'],
+ u'audio/x-ms-wma': [u'.wma'],
+ u'video/x-flv': [u'.flv'],
+ u'video/x-matroska': [u'.mpv', u'.mkv'],
+ u'video/x-wmv': [u'.wmv'],
+ u'video/x-ms-wmv': [u'.wmv']}
+
+ def load(self, display):
+ log.debug(u'load vid in Phonon Controller')
+ controller = display.controller
+ volume = controller.media_info.volume
+ path = controller.media_info.file_info.absoluteFilePath()
+ display.mediaObject.setCurrentSource(Phonon.MediaSource(path))
+ if not self.mediaStateWait(display, Phonon.StoppedState):
+ return False
+ self.volume(display, volume)
+ return True
+
+ def mediaStateWait(self, display, mediaState):
+ """
+ Wait for the video to change its state
+ Wait no longer than 5 seconds.
+ """
+ start = datetime.now()
+ while display.mediaObject.state() != mediaState:
+ if display.mediaObject.state() == Phonon.ErrorState:
+ return False
+ Receiver.send_message(u'openlp_process_events')
+ if (datetime.now() - start).seconds > 5:
+ return False
+ return True
+
+ def resize(self, display):
+ display.phononWidget.resize(display.size())
+
+ def play(self, display):
+ self.set_visible(display, True)
+ controller = display.controller
+ vol = float(controller.media_info.volume) / float(10)
+ display.audio.setVolume(vol)
+ display.mediaObject.play()
+ self.state = MediaState.Playing
+
+ def pause(self, display):
+ display.mediaObject.pause()
+ self.state = MediaState.Paused
+
+ def stop(self, display):
+ display.mediaObject.stop()
+ self.set_visible(display, False)
+ self.state = MediaState.Stopped
+
+ def volume(self, display, vol):
+ # 1.0 is the highest value
+ if display.hasAudio:
+ vol = float(vol) / float(100)
+ display.audio.setVolume(vol)
+
+ def seek(self, display, seekVal):
+ display.mediaObject.seek(seekVal)
+
+ def reset(self, display):
+ display.mediaObject.stop()
+ display.mediaObject.clearQueue()
+ display.phononWidget.setVisible(False)
+ self.state = MediaState.Off
+
+ def set_visible(self, display, status):
+ if self.hasOwnWidget:
+ display.phononWidget.setVisible(status)
+
+ def update_ui(self, display):
+ controller = display.controller
+ controller.media_info.length = display.mediaObject.totalTime()
+ controller.seekSlider.setMaximum(controller.media_info.length)
+ if controller.media_info.start_time > 0:
+ if display.mediaObject.currentTime() < \
+ controller.media_info.start_time:
+ self.seek(display, controller.media_info.start_time)
+ if controller.media_info.end_time > 0:
+ if display.mediaObject.currentTime() > \
+ controller.media_info.end_time:
+ self.stop(display)
+ self.set_visible(display, False)
+ if not controller.seekSlider.isSliderDown():
+ controller.seekSlider.setSliderPosition( \
+ display.mediaObject.currentTime())
=== added file 'openlp/plugins/media/lib/webkitapi.py'
--- openlp/plugins/media/lib/webkitapi.py 1970-01-01 00:00:00 +0000
+++ openlp/plugins/media/lib/webkitapi.py 2011-06-15 04:36:33 +0000
@@ -0,0 +1,379 @@
+# -*- coding: utf-8 -*-
+# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4
+
+###############################################################################
+# OpenLP - Open Source Lyrics Projection #
+# --------------------------------------------------------------------------- #
+# Copyright (c) 2008-2011 Raoul Snyman #
+# Portions copyright (c) 2008-2011 Tim Bentley, Gerald Britton, Jonathan #
+# Corwin, Michael Gorven, Scott Guerrieri, Matthias Hub, Meinert Jordan, #
+# Armin Köhler, Joshua Miller, Stevan Pettit, Andreas Preikschat, Mattias #
+# Põldaru, Christian Richter, Philip Ridout, Simon Scudder, Jeffrey Smith, #
+# Maikel Stuivenberg, Martin Thompson, Jon Tibble, Frode Woldsund #
+# --------------------------------------------------------------------------- #
+# This program is free software; you can redistribute it and/or modify it #
+# under the terms of the GNU General Public License as published by the Free #
+# Software Foundation; version 2 of the License. #
+# #
+# This program is distributed in the hope that it will be useful, but WITHOUT #
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
+# more details. #
+# #
+# You should have received a copy of the GNU General Public License along #
+# with this program; if not, write to the Free Software Foundation, Inc., 59 #
+# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
+###############################################################################
+
+import logging
+
+from PyQt4 import QtCore, QtGui, QtWebKit
+
+from openlp.core.lib import OpenLPToolbar, translate
+from openlp.plugins.media.lib import MediaAPI, MediaState
+
+log = logging.getLogger(__name__)
+
+class WebkitAPI(MediaAPI):
+ """
+ Specialiced MediaAPI class
+ to reflect Features of the QtWebkit API
+ """
+
+ def __init__(self, parent):
+ MediaAPI.__init__(self, parent, u'Webkit')
+ self.parent = parent
+ self.canBackground = True
+ self.video_extensions_list = [
+ u'*.3gp'
+ , u'*.3gpp'
+ , u'*.3g2'
+ , u'*.3gpp2'
+ , u'*.aac'
+ , u'*.flv'
+ , u'*.f4a'
+ , u'*.f4b'
+ , u'*.f4p'
+ , u'*.f4v'
+ , u'*.mov'
+ , u'*.m4a'
+ , u'*.m4b'
+ , u'*.m4p'
+ , u'*.m4v'
+ , u'*.mkv'
+ , u'*.mp4'
+ , u'*.mp3'
+ , u'*.ogg'
+ , u'*.ogv'
+ , u'*.webm'
+ , u'*.swf', u'*.mpg', u'*.wmv', u'*.mpeg', u'*.avi'
+ ]
+
+ def setup_controls(self, controller, control_panel):
+ # no special controls
+ pass
+
+ def getDisplayCss(self):
+ """
+ Add css style sheets to htmlbuilder
+ """
+ css = u'''
+ #video1 {
+ z-index:3;
+ }
+ #video2 {
+ z-index:3;
+ }
+ #flash {
+ z-index:4;
+ }
+ '''
+ return css
+
+
+ def getDisplayJavascript(self):
+ """
+ Add javascript functions to htmlbuilder
+ """
+ js = u'''
+ var video_timer = null;
+ var current_video = '1';
+
+ function show_video(state, path, volume, loop, seekVal){
+ // Note, the preferred method for looping would be to use the
+ // video tag loop attribute.
+ // But QtWebKit doesn't support this. Neither does it support the
+ // onended event, hence the setInterval()
+ // In addition, setting the currentTime attribute to zero to restart
+ // the video raises an INDEX_SIZE_ERROR: DOM Exception 1
+ // To complicate it further, sometimes vid.currentTime stops
+ // slightly short of vid.duration and vid.ended is intermittent!
+ //
+ // Note, currently the background may go black between loops. Not
+ // desirable. Need to investigate using two <video>'s, and hiding/
+ // preloading one, and toggle between the two when looping.
+
+ if(current_video=='1'){
+ var vid = document.getElementById('video1');
+ var vid2 = document.getElementById('video2');
+ } else {
+ var vid = document.getElementById('video2');
+ var vid2 = document.getElementById('video1');
+ }
+ if(volume != null){
+ vid.volume = volume;
+ vid2.volume = volume;
+ }
+ switch(state){
+ case 'init':
+ vid.src = path;
+ vid2.src = path;
+ if(loop == null) loop = false;
+ vid.looping = loop;
+ vid2.looping = loop;
+ vid.load();
+ break;
+ case 'load':
+ vid2.style.visibility = 'hidden';
+ vid2.load();
+ break;
+ case 'play':
+ vid.play();
+ vid.style.visibility = 'visible';
+ if(vid.looping){
+ video_timer = setInterval(
+ function() {
+ show_video('poll');
+ }, 200);
+ }
+ break;
+ case 'pause':
+ if(video_timer!=null){
+ clearInterval(video_timer);
+ video_timer = null;
+ }
+ vid.pause();
+ break;
+ case 'stop':
+ show_video('pause');
+ vid.style.visibility = 'hidden';
+ break;
+ case 'poll':
+ if(vid.ended||vid.currentTime+0.2>vid.duration)
+ show_video('swap');
+ break;
+ case 'swap':
+ show_video('pause');
+ if(current_video=='1')
+ current_video = '2';
+ else
+ current_video = '1';
+ show_video('play');
+ show_video('load');
+ break;
+ case 'close':
+ show_video('stop');
+ vid.src = '';
+ vid2.src = '';
+ break;
+ case 'length':
+ return vid.duration;
+ case 'currentTime':
+ return vid.currentTime;
+ case 'seek':
+ // doesnt work curently
+ //vid.currentTime = seekVal;
+ break;
+ }
+ }
+
+ function getFlashMovieObject(movieName)
+ {
+ if (window.document[movieName])
+ {
+ return window.document[movieName];
+ }
+ if (document.embeds && document.embeds[movieName])
+ return document.embeds[movieName];
+ }
+
+ // http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html
+ function show_flash(state, path, volume, seekVal){
+ var text = document.getElementById('flash');
+ var flashMovie = getFlashMovieObject("OpenLPFlashMovie");
+ var src = "src = 'file:///" + path + "'";
+ var view_parm = " wmode='opaque'" +
+ " width='" + window.innerWidth + "'" +
+ " height='" + window.innerHeight + "'";
+ var swf_parm = " name='OpenLPFlashMovie'" +
+ " autostart='true' loop='false' play='true'" +
+ " hidden='false' swliveconnect='true' allowscriptaccess='always'" +
+ " volume='" + volume + "'";
+
+ switch(state){
+ case 'load':
+ text.innerHTML = "<embed " + src + view_parm + swf_parm + "/>";
+ flashMovie = getFlashMovieObject("OpenLPFlashMovie");
+ text.style.visibility = 'visible';
+ flashMovie.Play();
+ break;
+ case 'play':
+ text.style.visibility = 'visible';
+ flashMovie.Play();
+ break;
+ case 'pause':
+ flashMovie.StopPlay();
+ text.style.visibility = 'hidden';
+ break;
+ case 'stop':
+ flashMovie.StopPlay();
+ text.style.visibility = 'hidden';
+ tempHtml = text.innerHTML;
+ text.innerHTML = '';
+ text.innerHTML = tempHtml;
+ break;
+ case 'close':
+ flashMovie.StopPlay();
+ text.style.visibility = 'hidden';
+ text.innerHTML = '';
+ break;
+ case 'length':
+ return flashMovie.TotalFrames();
+ case 'currentTime':
+ return flashMovie.CurrentFrame();
+ case 'seek':
+ // flashMovie.GotoFrame(seekVal);
+ break;
+ }
+ }
+ '''
+ return js
+
+
+ def getDisplayHtml(self):
+ """
+ Add html code to htmlbuilder
+ """
+ html = u'''
+ <video id="video1" class="size" style="visibility:hidden" autobuffer preload>
+ </video>
+ <video id="video2" class="size" style="visibility:hidden" autobuffer preload>
+ </video>
+ <div id="flash" class="size" style="visibility:hidden"></div>
+ '''
+ return html
+
+ def setup(self, display):
+ display.webView.resize(display.size())
+ display.webView.raise_()
+ self.hasOwnWidget = False
+ display.webView.hide()
+
+ def check_available(self):
+ return True
+
+ def load(self, display):
+ log.debug(u'load vid in Webkit Controller')
+ controller = display.controller
+ volume = controller.media_info.volume
+ vol = float(volume) / float(100)
+ path = controller.media_info.file_info.absoluteFilePath()
+ if controller.media_info.is_background:
+ loop = u'true'
+ else:
+ loop = u'false'
+ display.webView.setVisible(True)
+ if controller.media_info.file_info.suffix() == u'swf':
+ controller.media_info.isFlash = True
+ js = u'show_flash("load","%s");' % \
+ (path.replace(u'\\', u'\\\\'))
+ else:
+ js = u'show_video("init", "%s", %s, %s);' % \
+ (path.replace(u'\\', u'\\\\'), str(vol), loop)
+ display.frame.evaluateJavaScript(js)
+ return True
+
+ def resize(self, display):
+ controller = display.controller
+ display.webView.resize(display.size())
+
+ def play(self, display):
+ controller = display.controller
+ display.webLoaded = True
+ self.set_visible(display, True)
+ if controller.media_info.isFlash:
+ display.frame.evaluateJavaScript(u'show_flash("play");')
+ else:
+ display.frame.evaluateJavaScript(u'show_video("play");')
+ self.state = MediaState.Playing
+
+ def pause(self, display):
+ controller = display.controller
+ if controller.media_info.isFlash:
+ display.frame.evaluateJavaScript(u'show_flash("pause");')
+ else:
+ display.frame.evaluateJavaScript(u'show_video("pause");')
+ self.state = MediaState.Paused
+
+ def stop(self, display):
+ controller = display.controller
+ if controller.media_info.isFlash:
+ display.frame.evaluateJavaScript(u'show_flash("stop");')
+ else:
+ display.frame.evaluateJavaScript(u'show_video("stop");')
+ self.state = MediaState.Stopped
+
+ def volume(self, display, vol):
+ controller = display.controller
+ # 1.0 is the highest value
+ if display.hasVolume:
+ vol = float(vol) / float(100)
+ if not controller.media_info.isFlash:
+ display.frame.evaluateJavaScript(
+ u'show_video(null, null, %s);' % str(vol))
+
+ def seek(self, display, seekVal):
+ controller = display.controller
+ if controller.media_info.isFlash:
+ seek = seekVal
+ display.frame.evaluateJavaScript( \
+ u'show_flash("seek", null, null, "%s");' % (seek))
+ else:
+ seek = float(seekVal)/1000
+ display.frame.evaluateJavaScript( \
+ u'show_video("seek", null, null, null, "%f");' % (seek))
+
+ def reset(self, display):
+ controller = display.controller
+ if controller.media_info.isFlash:
+ display.frame.evaluateJavaScript(u'show_flash("close");')
+ else:
+ display.frame.evaluateJavaScript(u'show_video("close");')
+ self.state = MediaState.Off
+
+ def set_visible(self, display, status):
+ if self.hasOwnWidget:
+ display.webView.setVisible(status)
+
+ def update_ui(self, display):
+ controller = display.controller
+ if controller.media_info.isFlash:
+ currentTime = display.frame.evaluateJavaScript( \
+ u'show_flash("currentTime");').toInt()[0]
+ length = display.frame.evaluateJavaScript( \
+ u'show_flash("length");').toInt()[0]
+ else:
+ (currentTime, ok) = display.frame.evaluateJavaScript( \
+ u'show_video("currentTime");').toFloat()
+ # check if conversion was ok and value is not 'NaN'
+ if ok and currentTime == currentTime:
+ currentTime = int(currentTime*1000)
+ (length, ok) = display.frame.evaluateJavaScript( \
+ u'show_video("length");').toFloat()
+ # check if conversion was ok and value is not 'NaN'
+ if ok and length == length:
+ length = int(length*1000)
+ if currentTime > 0:
+ controller.seekSlider.setMaximum(length)
+ if not controller.seekSlider.isSliderDown():
+ controller.seekSlider.setSliderPosition(currentTime)
=== modified file 'openlp/plugins/media/mediaplugin.py'
--- openlp/plugins/media/mediaplugin.py 2011-06-12 16:02:52 +0000
+++ openlp/plugins/media/mediaplugin.py 2011-06-15 04:36:33 +0000
@@ -26,12 +26,12 @@
###############################################################################
import logging
-import mimetypes
-
-from PyQt4.phonon import Phonon
+import os
from openlp.core.lib import Plugin, StringContent, build_icon, translate
-from openlp.plugins.media.lib import MediaMediaItem, MediaTab
+from openlp.core.utils import AppLocation
+from openlp.plugins.media.lib import MediaMediaItem, MediaTab, MediaManager, \
+ MediaAPI
log = logging.getLogger(__name__)
@@ -40,63 +40,34 @@
def __init__(self, plugin_helpers):
Plugin.__init__(self, u'Media', plugin_helpers,
- MediaMediaItem, MediaTab)
+ MediaMediaItem)
self.weight = -6
self.icon_path = u':/plugins/plugin_media.png'
self.icon = build_icon(self.icon_path)
# passed with drag and drop messages
self.dnd_id = u'Media'
- self.additional_extensions = {
- u'audio/ac3': [u'.ac3'],
- u'audio/flac': [u'.flac'],
- u'audio/x-m4a': [u'.m4a'],
- u'audio/midi': [u'.mid', u'.midi'],
- u'audio/x-mp3': [u'.mp3'],
- u'audio/mpeg': [u'.mp3', u'.mp2', u'.mpga', u'.mpega', u'.m4a'],
- u'audio/qcelp': [u'.qcp'],
- u'audio/x-wma': [u'.wma'],
- u'audio/x-ms-wma': [u'.wma'],
- u'video/x-flv': [u'.flv'],
- u'video/x-matroska': [u'.mpv', u'.mkv'],
- u'video/x-wmv': [u'.wmv'],
- u'video/x-ms-wmv': [u'.wmv']}
- self.audio_extensions_list = []
- self.video_extensions_list = []
- mimetypes.init()
- for mimetype in Phonon.BackendCapabilities.availableMimeTypes():
- mimetype = unicode(mimetype)
- if mimetype.startswith(u'audio/'):
- self._addToList(self.audio_extensions_list, mimetype)
- elif mimetype.startswith(u'video/'):
- self._addToList(self.video_extensions_list, mimetype)
+ self.mediaManager = MediaManager(self)
+ self.audio_extensions_list = \
+ self.mediaManager.get_audio_extensions_list()
+ self.video_extensions_list = \
+ self.mediaManager.get_video_extensions_list()
- def _addToList(self, list, mimetype):
- # Add all extensions which mimetypes provides us for supported types.
- extensions = mimetypes.guess_all_extensions(unicode(mimetype))
- for extension in extensions:
- ext = u'*%s' % extension
- if ext not in list:
- list.append(ext)
- self.serviceManager.supportedSuffixes(extension[1:])
- log.info(u'MediaPlugin: %s extensions: %s' % (mimetype,
- u' '.join(extensions)))
- # Add extensions for this mimetype from self.additional_extensions.
- # This hack clears mimetypes' and operating system's shortcomings
- # by providing possibly missing extensions.
- if mimetype in self.additional_extensions.keys():
- for extension in self.additional_extensions[mimetype]:
- ext = u'*%s' % extension
- if ext not in list:
- list.append(ext)
- self.serviceManager.supportedSuffixes(extension[1:])
- log.info(u'MediaPlugin: %s additional extensions: %s' % (mimetype,
- u' '.join(self.additional_extensions[mimetype])))
+ def getSettingsTab(self, parent):
+ """
+ Create the settings Tab
+ """
+ visible_name = self.getString(StringContent.VisibleName)
+ return MediaTab(parent, self.name, visible_name[u'title'],
+ self.mediaManager.APIs, self.icon_path)
def about(self):
about_text = translate('MediaPlugin', '<strong>Media Plugin</strong>'
'<br />The media plugin provides playback of audio and video.')
return about_text
+ def addControllerItems(self, controller, control_panel):
+ self.mediaManager.addControllerItems(controller, control_panel)
+
def setPluginTextStrings(self):
"""
Called to define all translatable texts of the plugin
@@ -123,3 +94,68 @@
'Add the selected media to the service.')
}
self.setPluginUiTextStrings(tooltips)
+
+ def finalise(self):
+ """
+ Time to tidy up on exit
+ """
+ log.info(u'Media Finalising')
+ self.mediaManager.Timer.stop()
+ self.mediaManager.video_reset(self.previewController)
+ self.mediaManager.video_reset(self.liveController)
+
+ def registerControllers(self, controller):
+ """
+ Register each media API controller (Webkit, Phonon, etc) and
+ store for later use
+ """
+ self.mediaManager.APIs[controller.name] = controller
+
+ def checkPreConditions(self):
+ """
+ Check to see if we have any media API's available
+ If Not do not install the plugin.
+ """
+ log.debug(u'checkPreConditions')
+ controller_dir = os.path.join(
+ AppLocation.get_directory(AppLocation.PluginsDir),
+ u'media', u'lib')
+ for filename in os.listdir(controller_dir):
+ if filename.endswith(u'api.py') and \
+ not filename == 'mediaapi.py':
+ path = os.path.join(controller_dir, filename)
+ if os.path.isfile(path):
+ modulename = u'openlp.plugins.media.lib.' + \
+ os.path.splitext(filename)[0]
+ log.debug(u'Importing controller %s', modulename)
+ try:
+ __import__(modulename, globals(), locals(), [])
+ except ImportError:
+ log.warn(u'Failed to import %s on path %s',
+ modulename, path)
+ controller_classes = MediaAPI.__subclasses__()
+ for controller_class in controller_classes:
+ controller = controller_class(self)
+ self.registerControllers(controller)
+ if self.mediaManager.APIs:
+ return True
+ else:
+ return False
+
+ def getDisplayCss(self):
+ """
+ Add css style sheets to htmlbuilder
+ """
+ return self.mediaManager.getDisplayCss()
+
+ def getDisplayJavascript(self):
+ """
+ Add javascript functions to htmlbuilder
+ """
+ return self.mediaManager.getDisplayJavascript()
+
+ def getDisplayHtml(self):
+ """
+ Add html code to htmlbuilder
+ """
+ return self.mediaManager.getDisplayHtml()
\ No newline at end of file
Follow ups