Advertisement
Guest User

videoWidget.py

a guest
Mar 22nd, 2016
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.53 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """The Video Widget example shows how to implement a video widget
  5. using QtMultimedia's QAbstractVideoSurface.
  6.  
  7. The following is a translation into PyQt5 from the C++ example found in
  8. C:\QtEnterprise\5.1.1\msvc2010\examples\multimediawidgets\customvideosurface\customvideowidget."""
  9.  
  10. import sys
  11. import os
  12. from PyQt5.QtGui import *
  13. from PyQt5.QtWidgets import *
  14. from PyQt5.QtCore import *
  15. from PyQt5.QtMultimedia import *
  16.  
  17.  
  18. class VideoWidgetSurface(QAbstractVideoSurface):
  19.  
  20.     def __init__(self, widget, parent=None):
  21.         super(VideoWidgetSurface, self).__init__(parent)
  22.  
  23.         self.widget = widget
  24.         self.imageFormat = QImage.Format_Invalid
  25.  
  26.     def supportedPixelFormats(self, handleType=QAbstractVideoBuffer.NoHandle):
  27.         formats = [QVideoFrame.PixelFormat()]
  28.         if handleType == QAbstractVideoBuffer.NoHandle:
  29.             for f in [QVideoFrame.Format_RGB32,
  30.                    QVideoFrame.Format_ARGB32,
  31.                     QVideoFrame.Format_ARGB32_Premultiplied,
  32.                    QVideoFrame.Format_RGB565,
  33.                    QVideoFrame.Format_RGB555
  34.                    ]:
  35.              formats.append(f)
  36.         return formats
  37.  
  38.     def isFormatSupported(self, _format):
  39.         imageFormat = QVideoFrame.imageFormatFromPixelFormat(_format.pixelFormat())
  40.         size = _format.frameSize()
  41.         _bool = False
  42.         if (imageFormat != QImage.Format_Invalid and not
  43.             size.isEmpty() and
  44.             _format.handleType() == QAbstractVideoBuffer.NoHandle):
  45.             _bool = True
  46.         return _bool
  47.  
  48.     def start(self, _format):
  49.         imageFormat = QVideoFrame.imageFormatFromPixelFormat(_format.pixelFormat())
  50.         size = _format.frameSize()
  51.         if (imageFormat != QImage.Format_Invalid and not size.isEmpty()):
  52.             self.imageFormat = imageFormat
  53.             self.imageSize = size
  54.             self.sourceRect = _format.viewport()
  55.             QAbstractVideoSurface.start(self, _format)
  56.             self.widget.updateGeometry()
  57.             self.updateVideoRect()
  58.             return True
  59.         else:
  60.             return False
  61.  
  62.     def stop(self):
  63.         self.currentFrame = QVideoFrame()
  64.         self.targetRect = QRect()
  65.         QAbstractVideoSurface.stop(self)
  66.         self.widget.update()
  67.  
  68.     def present(self, frame):
  69.         if (self.surfaceFormat().pixelFormat() != frame.pixelFormat() or
  70.                      self.surfaceFormat().frameSize() != frame.size()):
  71.             self.setError(QAbstractVideoSurface.IncorrectFormatError)
  72.             self.stop()
  73.             return False
  74.         else:
  75.             self.currentFrame = frame
  76.             self.widget.repaint(self.targetRect)
  77.             return True
  78.  
  79.     def videoRect(self):
  80.         return self.targetRect
  81.  
  82.     def updateVideoRect(self):
  83.         size = self.surfaceFormat().sizeHint()
  84.         size.scale(self.widget.size().boundedTo(size), Qt.KeepAspectRatio)
  85.         self.targetRect = QRect(QPoint(0, 0), size); self.targetRect.moveCenter(self.widget.rect().center())
  86.  
  87.     def paint(self, painter):
  88.         if (self.currentFrame.map(QAbstractVideoBuffer.ReadOnly)):
  89.             oldTransform = painter.transform()
  90.  
  91.             if (self.surfaceFormat().scanLineDirection() == QVideoSurfaceFormat.BottomToTop):
  92.                 painter.scale(1, -1);
  93.                 painter.translate(0, -self.widget.height())
  94.  
  95.             image = QImage(self.currentFrame.bits(),
  96.                         self.currentFrame.width(),
  97.                         self.currentFrame.height(),
  98.                         self.currentFrame.bytesPerLine(),
  99.                         self.imageFormat
  100.                         )
  101.  
  102.             painter.drawImage(self.targetRect, image, self.sourceRect)
  103.             painter.setTransform(oldTransform)
  104.  
  105.             self.currentFrame.unmap()
  106.  
  107.  
  108. class VideoWidget(QWidget):
  109.  
  110.     def __init__(self, parent=None):
  111.         super(VideoWidget, self).__init__(parent)
  112.  
  113.         self.setAutoFillBackground(False)
  114.         self.setAttribute(Qt.WA_NoSystemBackground, True)
  115.         self.setAttribute(Qt.WA_PaintOnScreen, True)
  116.         palette = self.palette()
  117.         palette.setColor(QPalette.Background, Qt.black)
  118.         self.setPalette(palette)
  119.         self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
  120.         self.surface = VideoWidgetSurface(self)
  121.  
  122.     def videoSurface(self):
  123.         return self.surface
  124.  
  125.     def closeEvent(self, event):
  126.         del self.surface
  127.  
  128.     def sizeHint(self):
  129.         return self.surface.surfaceFormat().sizeHint()
  130.  
  131.     def paintEvent(self, event):
  132.         painter = QPainter(self)
  133.         if (self.surface.isActive()):
  134.             videoRect = self.surface.videoRect()
  135.             if not videoRect.contains(event.rect()):
  136.                 region = event.region()
  137.                 region.subtract(videoRect)
  138.                 brush = self.palette().background()
  139.                 for rect in region.rects():
  140.                     painter.fillRect(rect, brush)
  141.             self.surface.paint(painter)
  142.         else:
  143.             painter.fillRect(event.rect(), self.palette().window())
  144.  
  145.     def resizeEvent(self, event):
  146.         QWidget.resizeEvent(self, event)
  147.         self.surface.updateVideoRect()
  148.  
  149.  
  150. class VideoPlayer(QWidget):
  151.     def __init__(self, parent=None):
  152.         super(VideoPlayer, self).__init__(parent)
  153.  
  154.         self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
  155.         self.videoWidget = VideoWidget()
  156.         #self.openButton = QPushButton("Open...")
  157.         #self.openButton.clicked.connect(self.openFile)
  158.         #self.playButton = QPushButton()
  159.         #self.playButton.setEnabled(False)
  160.         #self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
  161.         #self.playButton.clicked.connect(self.play)
  162.         self.nextButton = QPushButton()
  163.         self.nextButton.setEnabled(False)
  164.         self.nextButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipForward))
  165.         self.prevButton = QPushButton()
  166.         self.prevButton.setEnabled(False)
  167.         self.prevButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipBackward))
  168.  
  169.         self.positionSlider = QSlider(Qt.Horizontal)
  170.         self.positionSlider.setRange(0, 0)
  171.         self.positionSlider.sliderMoved.connect(self.setPosition)
  172.         self.controlLayout = QHBoxLayout()
  173.         self.controlLayout.setContentsMargins(0, 0, 0, 0)
  174.         #self.controlLayout.addWidget(self.openButton)
  175.         #self.controlLayout.addWidget(self.playButton)
  176.         self.controlLayout.addWidget(self.prevButton)
  177.         self.controlLayout.addWidget(self.nextButton)
  178.         self.controlLayout.addWidget(self.positionSlider)
  179.         layout = QVBoxLayout()
  180.         layout.addWidget(self.videoWidget)
  181.         layout.addLayout(self.controlLayout)
  182.  
  183.         self.setLayout(layout)
  184.  
  185.         self.mediaPlayer.setVideoOutput(self.videoWidget.videoSurface())
  186.         #self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
  187.         self.mediaPlayer.positionChanged.connect(self.positionChanged)
  188.         self.mediaPlayer.durationChanged.connect(self.durationChanged)
  189.  
  190.         ''' below loads video and plays it '''
  191.  
  192.         #url = 'http://mediadownloads.mlb.com/mlbam/2015/06/19/14-414657-2015-06-18/web_cut/mlbtv_177201883_1200K.mp4'
  193.         #self.mediaPlayer.setMedia(QMediaContent(QUrl(url)))
  194.         #self.mediaPlayer.play()
  195.  
  196.     def closeEvent(self, QCloseEvent):
  197.         self.mediaPlayer.stop()
  198.         del self.mediaPlayer  # deletes the window. needed to open it later.
  199.     '''
  200.    def openFile(self):
  201.        file_name = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath())[0]
  202.        if os.path.exists(file_name):
  203.            self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(file_name)))
  204.            self.playButton.setEnabled(True)
  205.  
  206.    def play(self):
  207.        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
  208.            self.mediaPlayer.pause()
  209.        else:
  210.            self.mediaPlayer.play()
  211.  
  212.    def mediaStateChanged(self, state):
  213.        if state == QMediaPlayer.PlayingState:
  214.            self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
  215.        else:
  216.            self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
  217.    '''
  218.     def positionChanged(self, position):
  219.         self.positionSlider.setValue(position)
  220.  
  221.     def durationChanged(self, duration):
  222.         self.positionSlider.setRange(0, duration)
  223.  
  224.     def setPosition(self, position):
  225.         self.mediaPlayer.setPosition(position)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement