PlayerQuickItem.cpp 10 KB

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