PlayerQuickItem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #include "PlayerQuickItem.h"
  2. #include <stdexcept>
  3. #include <QCoreApplication>
  4. #include <QGuiApplication>
  5. #include <QOpenGLContext>
  6. #include <QRunnable>
  7. #include <QtGui/QOpenGLFramebufferObject>
  8. #include <QtQuick/QQuickWindow>
  9. #include <QOpenGLFunctions>
  10. #include <mpv/render_gl.h>
  11. #include "utils/Utils.h"
  12. #if defined(Q_OS_WIN32)
  13. #include <windows.h>
  14. #include <dwmapi.h>
  15. #include <avrt.h>
  16. #endif
  17. #ifdef USE_X11EXTRAS
  18. #include <QX11Info>
  19. #include <qpa/qplatformnativeinterface.h>
  20. #endif
  21. ///////////////////////////////////////////////////////////////////////////////////////////////////
  22. static void* get_proc_address(void* ctx, const char* name)
  23. {
  24. Q_UNUSED(ctx);
  25. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  26. if (!glctx)
  27. return nullptr;
  28. void *res = (void *)glctx->getProcAddress(QByteArray(name));
  29. #ifdef Q_OS_WIN32
  30. // wglGetProcAddress(), which is used by Qt, does not always resolve all
  31. // builtin functions with all drivers (only extensions). Qt compensates this
  32. // for a degree, but does this only for functions Qt happens to need. So
  33. // we need our own falback as well.
  34. if (!res)
  35. {
  36. HMODULE handle = (HMODULE)QOpenGLContext::openGLModuleHandle();
  37. if (handle)
  38. res = (void *)GetProcAddress(handle, name);
  39. }
  40. #endif
  41. return res;
  42. }
  43. namespace {
  44. /////////////////////////////////////////////////////////////////////////////////////////
  45. class RequestRepaintJob : public QRunnable
  46. {
  47. public:
  48. explicit RequestRepaintJob(QQuickWindow *window) : m_window(window) { }
  49. void run() override
  50. {
  51. // QSGThreadedRenderLoop::update has a special code path that will render
  52. // without syncing the render and GUI threads unless asked elsewhere to support
  53. // QQuickAnimator animations. This is currently triggered by the fact that
  54. // QQuickWindow::update() is called from the render thread.
  55. // This allows continuing rendering video while the GUI thread is busy.
  56. //
  57. m_window->update();
  58. }
  59. private:
  60. QQuickWindow *m_window;
  61. };
  62. }
  63. ///////////////////////////////////////////////////////////////////////////////////////////////////
  64. PlayerRenderer::PlayerRenderer(mpv::qt::Handle mpv, QQuickWindow* window)
  65. : m_mpv(mpv), m_mpvGL(nullptr), m_window(window), m_size(), m_hAvrtHandle(nullptr), m_videoRectangle(-1, -1, -1, -1), m_fbo(0)
  66. {
  67. }
  68. ///////////////////////////////////////////////////////////////////////////////////////////////////
  69. bool PlayerRenderer::init()
  70. {
  71. #ifdef Q_OS_WIN32
  72. // Request Multimedia Class Schedule Service.
  73. DwmEnableMMCSS(TRUE);
  74. #endif
  75. mpv_opengl_init_params opengl_params = {
  76. #ifdef Q_OS_WIN32
  77. get_proc_address,
  78. NULL,
  79. #else
  80. .get_proc_address = get_proc_address,
  81. .get_proc_address_ctx = NULL,
  82. #endif
  83. };
  84. const QString platformName = QGuiApplication::platformName();
  85. mpv_render_param params[] = {
  86. {MPV_RENDER_PARAM_API_TYPE, (void*)MPV_RENDER_API_TYPE_OPENGL},
  87. {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &opengl_params},
  88. {MPV_RENDER_PARAM_INVALID},
  89. {MPV_RENDER_PARAM_INVALID},
  90. };
  91. #ifdef USE_X11EXTRAS
  92. if (platformName.contains("xcb")) {
  93. params[2].type = MPV_RENDER_PARAM_X11_DISPLAY;
  94. params[2].data = QX11Info::display();
  95. } else if (platformName.contains("wayland")) {
  96. QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
  97. params[2].type = MPV_RENDER_PARAM_WL_DISPLAY;
  98. params[2].data = native->nativeResourceForWindow("display", NULL);
  99. }
  100. #endif
  101. int err = mpv_render_context_create(&m_mpvGL, m_mpv, params);
  102. if (err >= 0) {
  103. mpv_render_context_set_update_callback(m_mpvGL, on_update, (void *)this);
  104. return true;
  105. }
  106. return false;
  107. }
  108. ///////////////////////////////////////////////////////////////////////////////////////////////////
  109. PlayerRenderer::~PlayerRenderer()
  110. {
  111. // Keep in mind that the m_mpv handle must be held until this is done.
  112. if (m_mpvGL)
  113. mpv_render_context_free(m_mpvGL);
  114. m_mpvGL = nullptr;
  115. delete m_fbo;
  116. }
  117. ///////////////////////////////////////////////////////////////////////////////////////////////////
  118. void PlayerRenderer::render()
  119. {
  120. QOpenGLContext *context = QOpenGLContext::currentContext();
  121. GLint fbo = 0;
  122. context->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
  123. bool flip = true;
  124. #if HAVE_OPTIMALORIENTATION
  125. flip = !(context->format().orientationFlags() & QSurfaceFormat::MirrorVertically);
  126. #endif
  127. bool screenFlip = flip;
  128. QSize fboSize = m_size;
  129. QOpenGLFramebufferObject *blitFbo = 0;
  130. m_window->resetOpenGLState();
  131. QRect fullWindow(0, 0, m_size.width(), m_size.height());
  132. if (m_videoRectangle.width() > 0 && m_videoRectangle.height() > 0 && m_videoRectangle != fullWindow && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit() && QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  133. {
  134. if (!m_fbo || !m_fbo->isValid() || m_fbo->size() != m_videoRectangle.size())
  135. {
  136. delete m_fbo;
  137. m_fbo = new QOpenGLFramebufferObject(m_videoRectangle.size());
  138. }
  139. if (m_fbo && m_fbo->isValid())
  140. {
  141. blitFbo = m_fbo;
  142. fboSize = m_fbo->size();
  143. fbo = m_fbo->handle();
  144. flip = false;
  145. // Need to clear the background manually, since nothing else knows it has to be done.
  146. context->functions()->glClearColor(0, 0, 0, 0);
  147. context->functions()->glClear(GL_COLOR_BUFFER_BIT);
  148. }
  149. }
  150. mpv_opengl_fbo mpv_fbo = {
  151. #ifdef Q_OS_WIN32
  152. fbo,
  153. fboSize.width(),
  154. fboSize.height(),
  155. #else
  156. .fbo = fbo,
  157. .w = fboSize.width(),
  158. .h = fboSize.height(),
  159. #endif
  160. };
  161. int mpv_flip = flip ? -1 : 0;
  162. mpv_render_param params[] = {
  163. {MPV_RENDER_PARAM_OPENGL_FBO, &mpv_fbo},
  164. {MPV_RENDER_PARAM_FLIP_Y, &mpv_flip},
  165. {MPV_RENDER_PARAM_INVALID}
  166. };
  167. mpv_render_context_render(m_mpvGL, params);
  168. m_window->resetOpenGLState();
  169. if (blitFbo)
  170. {
  171. QRect dstRect = m_videoRectangle;
  172. if (screenFlip)
  173. dstRect = QRect(dstRect.x(), m_size.height() - dstRect.y(), dstRect.width(), dstRect.top() - dstRect.bottom());
  174. QOpenGLFramebufferObject::blitFramebuffer(0, dstRect, blitFbo, QRect(QPoint(0, 0), blitFbo->size()));
  175. }
  176. }
  177. ///////////////////////////////////////////////////////////////////////////////////////////////////
  178. void PlayerRenderer::swap()
  179. {
  180. if (m_mpvGL)
  181. mpv_render_context_report_swap(m_mpvGL);
  182. }
  183. ///////////////////////////////////////////////////////////////////////////////////////////////////
  184. void PlayerRenderer::onVideoPlaybackActive(bool active)
  185. {
  186. #ifdef Q_OS_WIN32
  187. if (active && !m_hAvrtHandle)
  188. {
  189. DWORD handle = 0;
  190. m_hAvrtHandle = AvSetMmThreadCharacteristicsW(L"Low Latency", &handle);
  191. }
  192. else if (!active && m_hAvrtHandle)
  193. {
  194. AvRevertMmThreadCharacteristics(m_hAvrtHandle);
  195. m_hAvrtHandle = 0;
  196. }
  197. #endif
  198. }
  199. ///////////////////////////////////////////////////////////////////////////////////////////////////
  200. void PlayerRenderer::on_update(void *ctx)
  201. {
  202. PlayerRenderer *self = (PlayerRenderer *)ctx;
  203. // QQuickWindow::scheduleRenderJob is expected to be called from the GUI thread but
  204. // is thread-safe when using the QSGThreadedRenderLoop. We can detect a non-threaded render
  205. // loop by checking if QQuickWindow::beforeSynchronizing was called from the GUI thread
  206. // (which affects the QObject::thread() of the PlayerRenderer).
  207. //
  208. if (self->thread() == self->m_window->thread())
  209. QMetaObject::invokeMethod(self->m_window, "update", Qt::QueuedConnection);
  210. else
  211. self->m_window->scheduleRenderJob(new RequestRepaintJob(self->m_window), QQuickWindow::NoStage);
  212. }
  213. ///////////////////////////////////////////////////////////////////////////////////////////////////
  214. PlayerQuickItem::PlayerQuickItem(QQuickItem* parent)
  215. : QQuickItem(parent), m_mpvGL(nullptr), m_renderer(nullptr)
  216. {
  217. connect(this, &QQuickItem::windowChanged, this, &PlayerQuickItem::onWindowChanged, Qt::DirectConnection);
  218. connect(this, &PlayerQuickItem::onFatalError, this, &PlayerQuickItem::onHandleFatalError, Qt::QueuedConnection);
  219. }
  220. ///////////////////////////////////////////////////////////////////////////////////////////////////
  221. PlayerQuickItem::~PlayerQuickItem()
  222. {
  223. if (m_mpvGL)
  224. mpv_render_context_set_update_callback(m_mpvGL, nullptr, nullptr);
  225. }
  226. ///////////////////////////////////////////////////////////////////////////////////////////////////
  227. void PlayerQuickItem::onWindowChanged(QQuickWindow* win)
  228. {
  229. if (win)
  230. {
  231. connect(win, &QQuickWindow::beforeSynchronizing, this, &PlayerQuickItem::onSynchronize, Qt::DirectConnection);
  232. connect(win, &QQuickWindow::sceneGraphInvalidated, this, &PlayerQuickItem::onInvalidate, Qt::DirectConnection);
  233. }
  234. }
  235. ///////////////////////////////////////////////////////////////////////////////////////////////////
  236. void PlayerQuickItem::onHandleFatalError(QString message)
  237. {
  238. throw FatalException(message);
  239. }
  240. ///////////////////////////////////////////////////////////////////////////////////////////////////
  241. void PlayerQuickItem::onSynchronize()
  242. {
  243. if (!m_renderer && m_mpv)
  244. {
  245. m_renderer = new PlayerRenderer(m_mpv, window());
  246. if (!m_renderer->init())
  247. {
  248. delete m_renderer;
  249. m_renderer = nullptr;
  250. emit onFatalError(tr("Could not initialize OpenGL."));
  251. return;
  252. }
  253. connect(window(), &QQuickWindow::beforeRendering, m_renderer, &PlayerRenderer::render, Qt::DirectConnection);
  254. connect(window(), &QQuickWindow::frameSwapped, m_renderer, &PlayerRenderer::swap, Qt::DirectConnection);
  255. connect(&PlayerComponent::Get(), &PlayerComponent::videoPlaybackActive, m_renderer, &PlayerRenderer::onVideoPlaybackActive, Qt::QueuedConnection);
  256. connect(&PlayerComponent::Get(), &PlayerComponent::onVideoRecangleChanged, window(), &QQuickWindow::update, Qt::QueuedConnection);
  257. window()->setPersistentOpenGLContext(true);
  258. window()->setPersistentSceneGraph(true);
  259. window()->setClearBeforeRendering(false);
  260. m_debugInfo = "";
  261. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  262. if (glctx && glctx->isValid())
  263. {
  264. m_debugInfo += "\nOpenGL:\n";
  265. int syms[4] = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION};
  266. for (auto sym : syms)
  267. {
  268. auto s = (char *)glctx->functions()->glGetString(sym);
  269. if (s)
  270. m_debugInfo += QString(" ") + QString::fromUtf8(s) + "\n";
  271. }
  272. m_debugInfo += "\n";
  273. }
  274. }
  275. if (m_renderer)
  276. {
  277. m_renderer->m_size = window()->size() * window()->devicePixelRatio();
  278. m_renderer->m_videoRectangle = PlayerComponent::Get().videoRectangle();
  279. }
  280. }
  281. ///////////////////////////////////////////////////////////////////////////////////////////////////
  282. void PlayerQuickItem::onInvalidate()
  283. {
  284. if (m_renderer)
  285. delete m_renderer;
  286. m_renderer = nullptr;
  287. }
  288. ///////////////////////////////////////////////////////////////////////////////////////////////////
  289. void PlayerQuickItem::initMpv(PlayerComponent* player)
  290. {
  291. m_mpv = player->getMpvHandle();
  292. connect(player, &PlayerComponent::windowVisible, this, &QQuickItem::setVisible);
  293. window()->update();
  294. }