PlayerQuickItem.cpp 10 KB

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