PlayerQuickItem.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. #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. }
  96. #endif
  97. int err = mpv_render_context_create(&m_mpvGL, m_mpv, params);
  98. if (err >= 0) {
  99. mpv_render_context_set_update_callback(m_mpvGL, on_update, (void *)this);
  100. return true;
  101. }
  102. return false;
  103. }
  104. ///////////////////////////////////////////////////////////////////////////////////////////////////
  105. PlayerRenderer::~PlayerRenderer()
  106. {
  107. // Keep in mind that the m_mpv handle must be held until this is done.
  108. if (m_mpvGL)
  109. mpv_render_context_free(m_mpvGL);
  110. m_mpvGL = nullptr;
  111. delete m_fbo;
  112. }
  113. ///////////////////////////////////////////////////////////////////////////////////////////////////
  114. void PlayerRenderer::render()
  115. {
  116. QOpenGLContext *context = QOpenGLContext::currentContext();
  117. GLint fbo = 0;
  118. context->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
  119. bool flip = true;
  120. #if HAVE_OPTIMALORIENTATION
  121. flip = !(context->format().orientationFlags() & QSurfaceFormat::MirrorVertically);
  122. #endif
  123. bool screenFlip = flip;
  124. QSize fboSize = m_size;
  125. QOpenGLFramebufferObject *blitFbo = 0;
  126. m_window->resetOpenGLState();
  127. QRect fullWindow(0, 0, m_size.width(), m_size.height());
  128. if (m_videoRectangle.width() > 0 && m_videoRectangle.height() > 0 && m_videoRectangle != fullWindow && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit() && QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  129. {
  130. if (!m_fbo || !m_fbo->isValid() || m_fbo->size() != m_videoRectangle.size())
  131. {
  132. delete m_fbo;
  133. m_fbo = new QOpenGLFramebufferObject(m_videoRectangle.size());
  134. }
  135. if (m_fbo && m_fbo->isValid())
  136. {
  137. blitFbo = m_fbo;
  138. fboSize = m_fbo->size();
  139. fbo = m_fbo->handle();
  140. flip = false;
  141. // Need to clear the background manually, since nothing else knows it has to be done.
  142. context->functions()->glClearColor(0, 0, 0, 0);
  143. context->functions()->glClear(GL_COLOR_BUFFER_BIT);
  144. }
  145. }
  146. mpv_opengl_fbo mpv_fbo = {
  147. #ifdef Q_OS_WIN32
  148. fbo,
  149. fboSize.width(),
  150. fboSize.height(),
  151. #else
  152. .fbo = fbo,
  153. .w = fboSize.width(),
  154. .h = fboSize.height(),
  155. #endif
  156. };
  157. int mpv_flip = flip ? -1 : 0;
  158. mpv_render_param params[] = {
  159. {MPV_RENDER_PARAM_OPENGL_FBO, &mpv_fbo},
  160. {MPV_RENDER_PARAM_FLIP_Y, &mpv_flip},
  161. {MPV_RENDER_PARAM_INVALID}
  162. };
  163. mpv_render_context_render(m_mpvGL, params);
  164. m_window->resetOpenGLState();
  165. if (blitFbo)
  166. {
  167. QRect dstRect = m_videoRectangle;
  168. if (screenFlip)
  169. dstRect = QRect(dstRect.x(), m_size.height() - dstRect.y(), dstRect.width(), dstRect.top() - dstRect.bottom());
  170. QOpenGLFramebufferObject::blitFramebuffer(0, dstRect, blitFbo, QRect(QPoint(0, 0), blitFbo->size()));
  171. }
  172. }
  173. ///////////////////////////////////////////////////////////////////////////////////////////////////
  174. void PlayerRenderer::swap()
  175. {
  176. if (m_mpvGL)
  177. mpv_render_context_report_swap(m_mpvGL);
  178. }
  179. ///////////////////////////////////////////////////////////////////////////////////////////////////
  180. void PlayerRenderer::onVideoPlaybackActive(bool active)
  181. {
  182. #ifdef Q_OS_WIN32
  183. if (active && !m_hAvrtHandle)
  184. {
  185. DWORD handle = 0;
  186. m_hAvrtHandle = AvSetMmThreadCharacteristicsW(L"Low Latency", &handle);
  187. }
  188. else if (!active && m_hAvrtHandle)
  189. {
  190. AvRevertMmThreadCharacteristics(m_hAvrtHandle);
  191. m_hAvrtHandle = 0;
  192. }
  193. #endif
  194. }
  195. ///////////////////////////////////////////////////////////////////////////////////////////////////
  196. void PlayerRenderer::on_update(void *ctx)
  197. {
  198. PlayerRenderer *self = (PlayerRenderer *)ctx;
  199. // QQuickWindow::scheduleRenderJob is expected to be called from the GUI thread but
  200. // is thread-safe when using the QSGThreadedRenderLoop. We can detect a non-threaded render
  201. // loop by checking if QQuickWindow::beforeSynchronizing was called from the GUI thread
  202. // (which affects the QObject::thread() of the PlayerRenderer).
  203. //
  204. if (self->thread() == self->m_window->thread())
  205. QMetaObject::invokeMethod(self->m_window, "update", Qt::QueuedConnection);
  206. else
  207. self->m_window->scheduleRenderJob(new RequestRepaintJob(self->m_window), QQuickWindow::NoStage);
  208. }
  209. ///////////////////////////////////////////////////////////////////////////////////////////////////
  210. PlayerQuickItem::PlayerQuickItem(QQuickItem* parent)
  211. : QQuickItem(parent), m_mpvGL(nullptr), m_renderer(nullptr)
  212. {
  213. connect(this, &QQuickItem::windowChanged, this, &PlayerQuickItem::onWindowChanged, Qt::DirectConnection);
  214. connect(this, &PlayerQuickItem::onFatalError, this, &PlayerQuickItem::onHandleFatalError, Qt::QueuedConnection);
  215. }
  216. ///////////////////////////////////////////////////////////////////////////////////////////////////
  217. PlayerQuickItem::~PlayerQuickItem()
  218. {
  219. if (m_mpvGL)
  220. mpv_render_context_set_update_callback(m_mpvGL, nullptr, nullptr);
  221. }
  222. ///////////////////////////////////////////////////////////////////////////////////////////////////
  223. void PlayerQuickItem::onWindowChanged(QQuickWindow* win)
  224. {
  225. if (win)
  226. {
  227. connect(win, &QQuickWindow::beforeSynchronizing, this, &PlayerQuickItem::onSynchronize, Qt::DirectConnection);
  228. connect(win, &QQuickWindow::sceneGraphInvalidated, this, &PlayerQuickItem::onInvalidate, Qt::DirectConnection);
  229. }
  230. }
  231. ///////////////////////////////////////////////////////////////////////////////////////////////////
  232. void PlayerQuickItem::onHandleFatalError(QString message)
  233. {
  234. throw FatalException(message);
  235. }
  236. ///////////////////////////////////////////////////////////////////////////////////////////////////
  237. void PlayerQuickItem::onSynchronize()
  238. {
  239. if (!m_renderer && m_mpv)
  240. {
  241. m_renderer = new PlayerRenderer(m_mpv, window());
  242. if (!m_renderer->init())
  243. {
  244. delete m_renderer;
  245. m_renderer = nullptr;
  246. emit onFatalError(tr("Could not initialize OpenGL."));
  247. return;
  248. }
  249. connect(window(), &QQuickWindow::beforeRendering, m_renderer, &PlayerRenderer::render, Qt::DirectConnection);
  250. connect(window(), &QQuickWindow::frameSwapped, m_renderer, &PlayerRenderer::swap, Qt::DirectConnection);
  251. connect(&PlayerComponent::Get(), &PlayerComponent::videoPlaybackActive, m_renderer, &PlayerRenderer::onVideoPlaybackActive, Qt::QueuedConnection);
  252. connect(&PlayerComponent::Get(), &PlayerComponent::onVideoRecangleChanged, window(), &QQuickWindow::update, Qt::QueuedConnection);
  253. window()->setPersistentOpenGLContext(true);
  254. window()->setPersistentSceneGraph(true);
  255. window()->setClearBeforeRendering(false);
  256. m_debugInfo = "";
  257. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  258. if (glctx && glctx->isValid())
  259. {
  260. m_debugInfo += "\nOpenGL:\n";
  261. int syms[4] = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION};
  262. for (auto sym : syms)
  263. {
  264. auto s = (char *)glctx->functions()->glGetString(sym);
  265. if (s)
  266. m_debugInfo += QString(" ") + QString::fromUtf8(s) + "\n";
  267. }
  268. m_debugInfo += "\n";
  269. }
  270. }
  271. if (m_renderer)
  272. {
  273. m_renderer->m_size = window()->size() * window()->devicePixelRatio();
  274. m_renderer->m_videoRectangle = PlayerComponent::Get().videoRectangle();
  275. }
  276. }
  277. ///////////////////////////////////////////////////////////////////////////////////////////////////
  278. void PlayerQuickItem::onInvalidate()
  279. {
  280. if (m_renderer)
  281. delete m_renderer;
  282. m_renderer = nullptr;
  283. }
  284. ///////////////////////////////////////////////////////////////////////////////////////////////////
  285. void PlayerQuickItem::initMpv(PlayerComponent* player)
  286. {
  287. m_mpv = player->getMpvHandle();
  288. connect(player, &PlayerComponent::windowVisible, this, &QQuickItem::setVisible);
  289. window()->update();
  290. }