PlayerQuickItem.cpp 11 KB

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