PlayerQuickItem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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)
  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. }
  167. ///////////////////////////////////////////////////////////////////////////////////////////////////
  168. void PlayerRenderer::render()
  169. {
  170. QOpenGLContext *context = QOpenGLContext::currentContext();
  171. GLint fbo = 0;
  172. context->functions()->glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
  173. m_window->resetOpenGLState();
  174. bool flip = true;
  175. #if HAVE_OPTIMALORIENTATION
  176. flip = !(context->format().orientationFlags() & QSurfaceFormat::MirrorVertically);
  177. #endif
  178. // The negative height signals to mpv that the video should be flipped
  179. // (according to the flipped OpenGL coordinate system).
  180. mpv_opengl_cb_draw(m_mpvGL, fbo, m_size.width(), (flip ? -1 : 1) * m_size.height());
  181. m_window->resetOpenGLState();
  182. }
  183. ///////////////////////////////////////////////////////////////////////////////////////////////////
  184. void PlayerRenderer::swap()
  185. {
  186. mpv_opengl_cb_report_flip(m_mpvGL, 0);
  187. }
  188. ///////////////////////////////////////////////////////////////////////////////////////////////////
  189. void PlayerRenderer::onVideoPlaybackActive(bool active)
  190. {
  191. #ifdef Q_OS_WIN32
  192. if (active && !m_hAvrtHandle)
  193. {
  194. DWORD handle = 0;
  195. m_hAvrtHandle = AvSetMmThreadCharacteristicsW(L"Low Latency", &handle);
  196. }
  197. else if (!active && m_hAvrtHandle)
  198. {
  199. AvRevertMmThreadCharacteristics(m_hAvrtHandle);
  200. m_hAvrtHandle = 0;
  201. }
  202. #endif
  203. }
  204. ///////////////////////////////////////////////////////////////////////////////////////////////////
  205. void PlayerRenderer::on_update(void *ctx)
  206. {
  207. PlayerRenderer *self = (PlayerRenderer *)ctx;
  208. // QQuickWindow::scheduleRenderJob is expected to be called from the GUI thread but
  209. // is thread-safe when using the QSGThreadedRenderLoop. We can detect a non-threaded render
  210. // loop by checking if QQuickWindow::beforeSynchronizing was called from the GUI thread
  211. // (which affects the QObject::thread() of the PlayerRenderer).
  212. //
  213. if (self->thread() == self->m_window->thread())
  214. QMetaObject::invokeMethod(self->m_window, "update", Qt::QueuedConnection);
  215. else
  216. self->m_window->scheduleRenderJob(new RequestRepaintJob(self->m_window), QQuickWindow::NoStage);
  217. }
  218. ///////////////////////////////////////////////////////////////////////////////////////////////////
  219. PlayerQuickItem::PlayerQuickItem(QQuickItem* parent)
  220. : QQuickItem(parent), m_mpvGL(nullptr), m_renderer(nullptr)
  221. {
  222. connect(this, &QQuickItem::windowChanged, this, &PlayerQuickItem::onWindowChanged, Qt::DirectConnection);
  223. connect(this, &PlayerQuickItem::onFatalError, this, &PlayerQuickItem::onHandleFatalError, Qt::QueuedConnection);
  224. }
  225. ///////////////////////////////////////////////////////////////////////////////////////////////////
  226. PlayerQuickItem::~PlayerQuickItem()
  227. {
  228. if (m_mpvGL)
  229. mpv_opengl_cb_set_update_callback(m_mpvGL, nullptr, nullptr);
  230. }
  231. ///////////////////////////////////////////////////////////////////////////////////////////////////
  232. void PlayerQuickItem::onWindowChanged(QQuickWindow* win)
  233. {
  234. if (win)
  235. {
  236. connect(win, &QQuickWindow::beforeSynchronizing, this, &PlayerQuickItem::onSynchronize, Qt::DirectConnection);
  237. connect(win, &QQuickWindow::sceneGraphInvalidated, this, &PlayerQuickItem::onInvalidate, Qt::DirectConnection);
  238. }
  239. }
  240. ///////////////////////////////////////////////////////////////////////////////////////////////////
  241. void PlayerQuickItem::onHandleFatalError(QString message)
  242. {
  243. throw FatalException(message);
  244. }
  245. ///////////////////////////////////////////////////////////////////////////////////////////////////
  246. void PlayerQuickItem::onSynchronize()
  247. {
  248. if (!m_renderer && m_mpv)
  249. {
  250. m_renderer = new PlayerRenderer(m_mpv, window());
  251. if (!m_renderer->init())
  252. {
  253. delete m_renderer;
  254. m_renderer = nullptr;
  255. emit onFatalError(tr("Could not initialize OpenGL."));
  256. return;
  257. }
  258. connect(window(), &QQuickWindow::beforeRendering, m_renderer, &PlayerRenderer::render, Qt::DirectConnection);
  259. connect(window(), &QQuickWindow::frameSwapped, m_renderer, &PlayerRenderer::swap, Qt::DirectConnection);
  260. connect(&PlayerComponent::Get(), &PlayerComponent::videoPlaybackActive, m_renderer, &PlayerRenderer::onVideoPlaybackActive, Qt::QueuedConnection);
  261. window()->setPersistentOpenGLContext(true);
  262. window()->setPersistentSceneGraph(true);
  263. window()->setClearBeforeRendering(false);
  264. m_debugInfo = "";
  265. QOpenGLContext* glctx = QOpenGLContext::currentContext();
  266. if (glctx && glctx->isValid())
  267. {
  268. m_debugInfo += "\nOpenGL:\n";
  269. int syms[4] = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION};
  270. for (auto sym : syms)
  271. {
  272. auto s = (char *)glctx->functions()->glGetString(sym);
  273. if (s)
  274. m_debugInfo += QString(" ") + QString::fromUtf8(s) + "\n";
  275. }
  276. m_debugInfo += "\n";
  277. }
  278. }
  279. if (m_renderer)
  280. m_renderer->m_size = window()->size() * window()->devicePixelRatio();
  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. m_mpvGL = (mpv_opengl_cb_context *)mpv_get_sub_api(m_mpv, MPV_SUB_API_OPENGL_CB);
  294. if (!m_mpvGL)
  295. throw FatalException(tr("OpenGL not enabled in libmpv."));
  296. connect(player, &PlayerComponent::windowVisible, this, &QQuickItem::setVisible);
  297. window()->update();
  298. }