#pragma once #include <QAbstractVideoSurface> #include <QVideoSurfaceFormat> class DesktopVideoProducer : public QObject { Q_OBJECT public: // Qml static void registerQmlType(); explicit DesktopVideoProducer( QObject *parent = 0 ); ~DesktopVideoProducer(); // property, Q_PROPERTY( QAbstractVideoSurface* videoSurface READ videoSurface WRITE setVideoSurface ) QAbstractVideoSurface* videoSurface() const; void setVideoSurface( QAbstractVideoSurface* s ); protected: void timerEvent( QTimerEvent* ); private: void closeSurface(); private: QAbstractVideoSurface* _surface; QVideoSurfaceFormat _format; };
#include "DesktopVideoProducer.h" #include <QtQml/qqml.h> #include <QApplication> #include <QScreen> #include <QDesktopWidget> void DesktopVideoProducer::registerQmlType() { // DesktopVideoProducer, // 0.1, DesktopVideoProducer. // QtCreator, // . // @uri DesktopVideoProducer qmlRegisterType<DesktopVideoProducer>( "DesktopVideoProducer", 0, 1, "DesktopVideoProducer" ); } DesktopVideoProducer::DesktopVideoProducer( QObject *parent ) : QObject( parent ), _surface( 0 ) { startTimer( 1000 / 15 ); //15 fps } DesktopVideoProducer::~DesktopVideoProducer() { closeSurface(); } QAbstractVideoSurface* DesktopVideoProducer::videoSurface() const { return _surface; } void DesktopVideoProducer::setVideoSurface( QAbstractVideoSurface* s ) { closeSurface(); _surface = s; } void DesktopVideoProducer::closeSurface() { if( _surface && _surface->isActive() ) _surface->stop(); } void DesktopVideoProducer::timerEvent( QTimerEvent* ) { if( !_surface ) return; QScreen* screen = QGuiApplication::primaryScreen(); QDesktopWidget* desktop = QApplication::desktop(); if( !screen || !desktop ) return; // screenshot QVideoFrame QPixmap screenPixmap = screen->grabWindow( desktop->screen()->winId() ); QImage screenImage = screenPixmap.toImage(); QVideoFrame::PixelFormat pixelFormat = QVideoFrame::pixelFormatFromImageFormat( screenImage.format() ); // - ( )- // () surface if( screenPixmap.size() != _format.frameSize() || pixelFormat != _format.pixelFormat() ) { closeSurface(); _format = QVideoSurfaceFormat( screenPixmap.size(), pixelFormat ); _surface->start( _format ); } // _surface->present( QVideoFrame( screenImage ) ); }
import QtQuick 2.2 import QtQuick.Window 2.1 import QtMultimedia 5.0 import DesktopVideoProducer 0.1 Window { visible: true width: 360 height: 360 DesktopVideoProducer { id: videoProducer; } VideoOutput { anchors.fill: parent; source: videoProducer; } }
#include <QApplication> #include <QQmlApplicationEngine> #include"DesktopVideoProducer.h" int main(int argc, char *argv[]) { // DesktopVideoProducer Qml DesktopVideoProducer::registerQmlType(); // QApplication::desktop() QGuiApplication //QGuiApplication app(argc, argv); QApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); return app.exec(); }
Source: https://habr.com/ru/post/229747/
All Articles