PlayerQuickItem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 "QsLog.h"
  10. #include "utils/Utils.h"
  11. #ifdef USE_X11EXTRAS
  12. #include <QX11Info>
  13. #endif
  14. #if defined(Q_OS_WIN32)
  15. #include <windows.h>
  16. #include <d3d9.h>
  17. #include <dwmapi.h>
  18. #include <avrt.h>
  19. typedef IDirect3D9* WINAPI pDirect3DCreate9(UINT);
  20. static IDirect3DDevice9* d3ddevice;
  21. // This must be run before the konvergo main window switches to FS mode.
  22. void initD3DDevice(void)
  23. {
  24. // Boilerplate for creating a "blank" D3D device.
  25. // Most of this is copied from FFmpeg (LGPL).
  26. pDirect3DCreate9 *createD3D = NULL;
  27. HRESULT hr;
  28. D3DPRESENT_PARAMETERS d3dpp = {};
  29. D3DDISPLAYMODE d3ddm;
  30. UINT adapter = D3DADAPTER_DEFAULT;
  31. if (QCoreApplication::testAttribute(Qt::AA_UseOpenGLES))
  32. return;
  33. HMODULE d3dlib = LoadLibraryW(L"d3d9.dll");
  34. if (!d3dlib) {
  35. QLOG_ERROR() << "Failed to load D3D9 library";
  36. return;
  37. }
  38. createD3D = (pDirect3DCreate9 *)GetProcAddress(d3dlib, "Direct3DCreate9");
  39. if (!createD3D) {
  40. QLOG_ERROR() << "Failed to locate Direct3DCreate9";
  41. return;
  42. }
  43. IDirect3D9 *d3d9 = createD3D(D3D_SDK_VERSION);
  44. if (!d3d9) {
  45. QLOG_ERROR() << "Failed to create IDirect3D object";
  46. return;
  47. }
  48. IDirect3D9_GetAdapterDisplayMode(d3d9, adapter, &d3ddm);
  49. d3dpp.Windowed = TRUE;
  50. d3dpp.BackBufferWidth = 640;
  51. d3dpp.BackBufferHeight = 480;
  52. d3dpp.BackBufferCount = 0;
  53. d3dpp.BackBufferFormat = d3ddm.Format;
  54. d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  55. d3dpp.Flags = D3DPRESENTFLAG_VIDEO;
  56. hr = IDirect3D9_CreateDevice(d3d9, adapter, D3DDEVTYPE_HAL, GetShellWindow(),
  57. D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
  58. &d3dpp, &d3ddevice);
  59. if (FAILED(hr)) {
  60. QLOG_ERROR() << "Failed to create Direct3D device";
  61. return;
  62. }
  63. QLOG_INFO() << "Successfully created a Direct3D device";
  64. };
  65. // Special libmpv-specific pseudo extension for better behavior with OpenGL
  66. // fullscreen modes. This is needed with some drivers which do not allow the
  67. // libmpv DXVA code to create a new D3D device.
  68. static void* __stdcall MPGetNativeDisplay(const char* name)
  69. {
  70. QLOG_INFO() << "Asking for " << qPrintable(QString::fromUtf8((name)));
  71. if (strcmp(name, "IDirect3DDevice9") == 0)
  72. {
  73. QLOG_INFO() << "Returning device " << (void *)d3ddevice;
  74. if (d3ddevice)
  75. IDirect3DDevice9_AddRef(d3ddevice);
  76. return (void *)d3ddevice;
  77. }
  78. return NULL;
  79. }
  80. // defined(Q_OS_WIN32)
  81. #elif defined(USE_X11EXTRAS)
  82. // Linux
  83. static void* MPGetNativeDisplay(const char* name)
  84. {
  85. if (strcmp(name, "x11") == 0)
  86. return QX11Info::display();
  87. return nullptr;
  88. }
  89. #else
  90. // Unsupported or not needed. Also, not using Windows-specific calling convention.
  91. static void* MPGetNativeDisplay(const char* name)
  92. {
  93. return nullptr;
  94. }
  95. #endif
  96. ///////////////////////////////////////////////////////////////////////////////////////////////////
  97. static void* get_proc_address(void* ctx, const char* name)
  98. {
  99. Q_UNUSED(ctx);
  100. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  101. if (!glctx)
  102. return nullptr;
  103. void *res = (void *)glctx->getProcAddress(QByteArray(name));
  104. if (strcmp(name, "glMPGetNativeDisplay") == 0)
  105. {
  106. return (void *)&MPGetNativeDisplay;
  107. }
  108. #ifdef Q_OS_WIN32
  109. // wglGetProcAddress(), which is used by Qt, does not always resolve all
  110. // builtin functions with all drivers (only extensions). Qt compensates this
  111. // for a degree, but does this only for functions Qt happens to need. So
  112. // we need our own falback as well.
  113. if (!res)
  114. {
  115. HMODULE handle = (HMODULE)QOpenGLContext::openGLModuleHandle();
  116. if (handle)
  117. res = (void *)GetProcAddress(handle, name);
  118. }
  119. #endif
  120. return res;
  121. }
  122. namespace {
  123. /////////////////////////////////////////////////////////////////////////////////////////
  124. class RequestRepaintJob : public QRunnable
  125. {
  126. public:
  127. explicit RequestRepaintJob(QQuickWindow *window) : m_window(window) { }
  128. void run() override
  129. {
  130. // QSGThreadedRenderLoop::update has a special code path that will render
  131. // without syncing the render and GUI threads unless asked elsewhere to support
  132. // QQuickAnimator animations. This is currently triggered by the fact that
  133. // QQuickWindow::update() is called from the render thread.
  134. // This allows continuing rendering video while the GUI thread is busy.
  135. //
  136. m_window->update();
  137. }
  138. private:
  139. QQuickWindow *m_window;
  140. };
  141. }
  142. ///////////////////////////////////////////////////////////////////////////////////////////////////
  143. PlayerRenderer::PlayerRenderer(mpv::qt::Handle mpv, QQuickWindow* window)
  144. : m_mpv(mpv), m_mpvGL(nullptr), m_window(window), m_size(), m_hAvrtHandle(nullptr), m_videoRectangle(-1, -1, -1, -1), m_fbo(0)
  145. {
  146. m_mpvGL = (mpv_opengl_cb_context *)mpv_get_sub_api(m_mpv, MPV_SUB_API_OPENGL_CB);
  147. }
  148. ///////////////////////////////////////////////////////////////////////////////////////////////////
  149. bool PlayerRenderer::init()
  150. {
  151. #ifdef Q_OS_WIN32
  152. // Request Multimedia Class Schedule Service.
  153. DwmEnableMMCSS(TRUE);
  154. #endif
  155. mpv_opengl_cb_set_update_callback(m_mpvGL, on_update, (void *)this);
  156. // Signals presence of MPGetNativeDisplay().
  157. const char *extensions = "GL_MP_MPGetNativeDisplay";
  158. return mpv_opengl_cb_init_gl(m_mpvGL, extensions, get_proc_address, nullptr) >= 0;
  159. }
  160. ///////////////////////////////////////////////////////////////////////////////////////////////////
  161. PlayerRenderer::~PlayerRenderer()
  162. {
  163. // Keep in mind that the m_mpv handle must be held until this is done.
  164. if (m_mpvGL)
  165. mpv_opengl_cb_uninit_gl(m_mpvGL);
  166. delete m_fbo;
  167. }
  168. ///////////////////////////////////////////////////////////////////////////////////////////////////
  169. void PlayerRenderer::render()
  170. {
  171. QOpenGLContext *context = QOpenGLContext::currentContext();
  172. GLint fbo = 0;
  173. context->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
  174. bool flip = true;
  175. #if HAVE_OPTIMALORIENTATION
  176. flip = !(context->format().orientationFlags() & QSurfaceFormat::MirrorVertically);
  177. #endif
  178. bool screenFlip = flip;
  179. QSize fboSize = m_size;
  180. QOpenGLFramebufferObject *blitFbo = 0;
  181. m_window->resetOpenGLState();
  182. QRect fullWindow(0, 0, m_size.width(), m_size.height());
  183. if (m_videoRectangle.width() > 0 && m_videoRectangle.height() > 0 && m_videoRectangle != fullWindow && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit() && QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  184. {
  185. if (!m_fbo || !m_fbo->isValid() || m_fbo->size() != m_videoRectangle.size())
  186. {
  187. delete m_fbo;
  188. m_fbo = new QOpenGLFramebufferObject(m_videoRectangle.size());
  189. }
  190. if (m_fbo && m_fbo->isValid())
  191. {
  192. blitFbo = m_fbo;
  193. fboSize = m_fbo->size();
  194. fbo = m_fbo->handle();
  195. flip = false;
  196. // Need to clear the background manually, since nothing else knows it has to be done.
  197. context->functions()->glClearColor(0, 0, 0, 0);
  198. context->functions()->glClear(GL_COLOR_BUFFER_BIT);
  199. }
  200. }
  201. // The negative height signals to mpv that the video should be flipped
  202. // (according to the flipped OpenGL coordinate system).
  203. mpv_opengl_cb_draw(m_mpvGL, fbo, fboSize.width(), (flip ? -1 : 1) * fboSize.height());
  204. m_window->resetOpenGLState();
  205. if (blitFbo)
  206. {
  207. QRect dstRect = m_videoRectangle;
  208. if (screenFlip)
  209. dstRect = QRect(dstRect.x(), m_size.height() - dstRect.y(), dstRect.width(), dstRect.top() - dstRect.bottom());
  210. QOpenGLFramebufferObject::blitFramebuffer(0, dstRect, blitFbo, QRect(QPoint(0, 0), blitFbo->size()));
  211. }
  212. }
  213. ///////////////////////////////////////////////////////////////////////////////////////////////////
  214. void PlayerRenderer::swap()
  215. {
  216. mpv_opengl_cb_report_flip(m_mpvGL, 0);
  217. }
  218. ///////////////////////////////////////////////////////////////////////////////////////////////////
  219. void PlayerRenderer::onVideoPlaybackActive(bool active)
  220. {
  221. #ifdef Q_OS_WIN32
  222. if (active && !m_hAvrtHandle)
  223. {
  224. DWORD handle = 0;
  225. m_hAvrtHandle = AvSetMmThreadCharacteristicsW(L"Low Latency", &handle);
  226. }
  227. else if (!active && m_hAvrtHandle)
  228. {
  229. AvRevertMmThreadCharacteristics(m_hAvrtHandle);
  230. m_hAvrtHandle = 0;
  231. }
  232. #endif
  233. }
  234. ///////////////////////////////////////////////////////////////////////////////////////////////////
  235. void PlayerRenderer::on_update(void *ctx)
  236. {
  237. PlayerRenderer *self = (PlayerRenderer *)ctx;
  238. // QQuickWindow::scheduleRenderJob is expected to be called from the GUI thread but
  239. // is thread-safe when using the QSGThreadedRenderLoop. We can detect a non-threaded render
  240. // loop by checking if QQuickWindow::beforeSynchronizing was called from the GUI thread
  241. // (which affects the QObject::thread() of the PlayerRenderer).
  242. //
  243. if (self->thread() == self->m_window->thread())
  244. QMetaObject::invokeMethod(self->m_window, "update", Qt::QueuedConnection);
  245. else
  246. self->m_window->scheduleRenderJob(new RequestRepaintJob(self->m_window), QQuickWindow::NoStage);
  247. }
  248. ///////////////////////////////////////////////////////////////////////////////////////////////////
  249. PlayerQuickItem::PlayerQuickItem(QQuickItem* parent)
  250. : QQuickItem(parent), m_mpvGL(nullptr), m_renderer(nullptr)
  251. {
  252. connect(this, &QQuickItem::windowChanged, this, &PlayerQuickItem::onWindowChanged, Qt::DirectConnection);
  253. connect(this, &PlayerQuickItem::onFatalError, this, &PlayerQuickItem::onHandleFatalError, Qt::QueuedConnection);
  254. }
  255. ///////////////////////////////////////////////////////////////////////////////////////////////////
  256. PlayerQuickItem::~PlayerQuickItem()
  257. {
  258. if (m_mpvGL)
  259. mpv_opengl_cb_set_update_callback(m_mpvGL, nullptr, nullptr);
  260. }
  261. ///////////////////////////////////////////////////////////////////////////////////////////////////
  262. void PlayerQuickItem::onWindowChanged(QQuickWindow* win)
  263. {
  264. if (win)
  265. {
  266. connect(win, &QQuickWindow::beforeSynchronizing, this, &PlayerQuickItem::onSynchronize, Qt::DirectConnection);
  267. connect(win, &QQuickWindow::sceneGraphInvalidated, this, &PlayerQuickItem::onInvalidate, Qt::DirectConnection);
  268. }
  269. }
  270. ///////////////////////////////////////////////////////////////////////////////////////////////////
  271. void PlayerQuickItem::onHandleFatalError(QString message)
  272. {
  273. throw FatalException(message);
  274. }
  275. ///////////////////////////////////////////////////////////////////////////////////////////////////
  276. void PlayerQuickItem::onSynchronize()
  277. {
  278. if (!m_renderer && m_mpv)
  279. {
  280. m_renderer = new PlayerRenderer(m_mpv, window());
  281. if (!m_renderer->init())
  282. {
  283. delete m_renderer;
  284. m_renderer = nullptr;
  285. emit onFatalError(tr("Could not initialize OpenGL."));
  286. return;
  287. }
  288. connect(window(), &QQuickWindow::beforeRendering, m_renderer, &PlayerRenderer::render, Qt::DirectConnection);
  289. connect(window(), &QQuickWindow::frameSwapped, m_renderer, &PlayerRenderer::swap, Qt::DirectConnection);
  290. connect(&PlayerComponent::Get(), &PlayerComponent::videoPlaybackActive, m_renderer, &PlayerRenderer::onVideoPlaybackActive, Qt::QueuedConnection);
  291. connect(&PlayerComponent::Get(), &PlayerComponent::onVideoRecangleChanged, window(), &QQuickWindow::update, Qt::QueuedConnection);
  292. window()->setPersistentOpenGLContext(true);
  293. window()->setPersistentSceneGraph(true);
  294. window()->setClearBeforeRendering(false);
  295. m_debugInfo = "";
  296. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  297. if (glctx && glctx->isValid())
  298. {
  299. m_debugInfo += "\nOpenGL:\n";
  300. int syms[4] = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION};
  301. for (auto sym : syms)
  302. {
  303. auto s = (char *)glctx->functions()->glGetString(sym);
  304. if (s)
  305. m_debugInfo += QString(" ") + QString::fromUtf8(s) + "\n";
  306. }
  307. m_debugInfo += "\n";
  308. }
  309. }
  310. if (m_renderer)
  311. {
  312. m_renderer->m_size = window()->size() * window()->devicePixelRatio();
  313. m_renderer->m_videoRectangle = PlayerComponent::Get().videoRectangle();
  314. }
  315. }
  316. ///////////////////////////////////////////////////////////////////////////////////////////////////
  317. void PlayerQuickItem::onInvalidate()
  318. {
  319. if (m_renderer)
  320. delete m_renderer;
  321. m_renderer = nullptr;
  322. }
  323. ///////////////////////////////////////////////////////////////////////////////////////////////////
  324. void PlayerQuickItem::initMpv(PlayerComponent* player)
  325. {
  326. m_mpv = player->getMpvHandle();
  327. m_mpvGL = (mpv_opengl_cb_context *)mpv_get_sub_api(m_mpv, MPV_SUB_API_OPENGL_CB);
  328. if (!m_mpvGL)
  329. throw FatalException(tr("OpenGL not enabled in libmpv."));
  330. connect(player, &PlayerComponent::windowVisible, this, &QQuickItem::setVisible);
  331. window()->update();
  332. }