Debian Codegraph @

libglfork.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 #include <dlfcn.h>
2 #include <pthread.h>
3 #include <semaphore.h>
4 #include <time.h>
5 #include <unistd.h>
6 #include <sys/socket.h>
7 #include <sys/un.h>
8 #include <errno.h>
9 #include <cstdlib>
10 #include <cstring>
11 #include <cstdio>
12 #include <cassert>
13 #include <map>
14 #include <string>
15 #include <X11/Xatom.h>
16 #pragma GCC visibility push(default)
17 #define GLX_GLXEXT_PROTOTYPES
18 #define GL_GLEXT_PROTOTYPES
19 #include <GL/glx.h>
20 #pragma GCC visibility pop
21
22 #define primus_print(c, ...) do { if (c) fprintf(stderr, "primus: " __VA_ARGS__); } while (0)
23
24 #define die_if(cond, ...) do {if (cond) {primus_print(true, "fatal: " __VA_ARGS__); exit(1);} } while (0)
25 #define primus_warn(...) primus_print(primus.loglevel >= 1, "warning: " __VA_ARGS__)
26 #define primus_perf(...) primus_print(primus.loglevel >= 2, "profiling: " __VA_ARGS__)
27
28 // Try to load any of the colon-separated libraries
29 static void *mdlopen(const char *paths, int flag)
30 {
31 char *p = strdupa(paths);
32 char errors[1024], *errors_ptr = errors, *errors_end = errors + 1024;
33 for (char *c = p; c; p = c + 1)
34 {
35 if ((c = strchr(p, ':')))
36 *c = 0;
37 die_if(p[0] != '/', "need absolute library path: %s\n", p);
38 void *handle = dlopen(p, flag);
39 if (handle)
40 return handle;
41 errors_ptr += snprintf(errors_ptr, errors_end - errors_ptr, "%s\n", dlerror());
42 }
43 die_if(true, "failed to load any of the libraries: %s\n%s", paths, errors);
44 }
45
46 static void *real_dlsym(void *handle, const char *symbol)
47 {
48 typedef void* (*dlsym_fn)(void *, const char*);
49 static dlsym_fn pdlsym = (dlsym_fn) dlsym(dlopen("libdl.so.2", RTLD_LAZY), "dlsym");
50 return pdlsym(handle, symbol);
51 }
52
53 // Pointers to implemented/forwarded GLX and OpenGL functions
54 struct CapturedFns {
55 void *handle;
56 // Declare functions as fields of the struct
57 #define DEF_GLX_PROTO(ret, name, args, ...) ret (*name) args;
58 #include "glx-reimpl.def"
59 #include "glx-dpyredir.def"
60 #include "glxext-reimpl.def"
61 #include "gl-passthru.def"
62 #include "gl-needed.def"
63 #undef DEF_GLX_PROTO
64 CapturedFns(const char *lib)
65 {
66 handle = mdlopen(lib, RTLD_LAZY);
67 #define DEF_GLX_PROTO(ret, name, args, ...) name = (ret (*) args)real_dlsym(handle, #name);
68 #include "glx-reimpl.def"
69 #include "glx-dpyredir.def"
70 #undef DEF_GLX_PROTO
71 #define DEF_GLX_PROTO(ret, name, args, ...) name = (ret (*) args)this->glXGetProcAddress((GLubyte*)#name);
72 #include "glxext-reimpl.def"
73 #include "gl-passthru.def"
74 #include "gl-needed.def"
75 #undef DEF_GLX_PROTO
76 }
77 ~CapturedFns()
78 {
79 dlclose(handle);
80 }
81 };
82
83 // Drawable tracking info
84 struct DrawableInfo {
85 // Only XWindow is not explicitely created via GLX
86 enum {XWindow, Window, Pixmap, Pbuffer} kind;
87 GLXFBConfig fbconfig;
88 GLXPbuffer pbuffer;
89 Drawable window;
90 int width, height;
91 enum ReinitTodo {NONE, RESIZE, SHUTDOWN} reinit;
92 GLvoid *pixeldata;
93 GLsync sync;
94 GLXContext actx;
95
96 struct {
97 pthread_t worker;
98 sem_t acqsem, relsem;
99 ReinitTodo reinit;
100
101 void spawn_worker(GLXDrawable draw, void* (*work)(void*))
102 {
103 reinit = RESIZE;
104 sem_init(&acqsem, 0, 0);
105 sem_init(&relsem, 0, 0);
106 pthread_create(&worker, NULL, work, (void*)draw);
107 }
108 void reap_worker()
109 {
110 //pthread_cancel(worker);
111 pthread_join(worker, NULL);
112 sem_destroy(&relsem);
113 sem_destroy(&acqsem);
114 worker = 0;
115 }
116 } r, d;
117 void reap_workers()
118 {
119 if (r.worker)
120 {
121 r.reinit = SHUTDOWN;
122 sem_post(&r.acqsem);
123 sem_wait(&r.relsem);
124 r.reap_worker();
125 d.reap_worker();
126 }
127 }
128 void update_geometry(int width, int height)
129 {
130 if (this->width == width && this->height == height)
131 return;
132 this->width = width; this->height = height;
133 __sync_synchronize();
134 reinit = RESIZE;
135 }
136 ~DrawableInfo();
137 };
138
139 struct DrawablesInfo: public std::map<GLXDrawable, DrawableInfo> {
140 bool known(GLXDrawable draw)
141 {
142 return this->find(draw) != this->end();
143 }
144 };
145
146 struct ContextInfo {
147 GLXFBConfig fbconfig;
148 int sharegroup;
149 };
150
151 struct ContextsInfo: public std::map<GLXContext, ContextInfo> {
152 void record(GLXContext ctx, GLXFBConfig config, GLXContext share)
153 {
154 static int nsharegroups;
155 int sharegroup = share ? (*this)[share].sharegroup : nsharegroups++;
156 (*this)[ctx] = (ContextInfo){config, sharegroup};
157 }
158 };
159
160 // Shorthand for obtaining compile-time configurable value that can be
161 // overridden by environment
162 #define getconf(V) (getenv(#V) ? getenv(#V) : V)
163
164 // Runs before all other initialization takes place
165 struct EarlyInitializer {
166 EarlyInitializer(const char **adpy_strp, const char **libgla_strp)
167 {
168 // Allow multiple glvnd libGL.so.1 instances to be loaded into a process
169 // and OpenGL calls dispatched to them depending on context.
170 setenv("__GLVND_DISALLOW_PATCHING", "1", 0);
171 #ifdef BUMBLEBEE_SOCKET
172 // Signal the Bumblebee daemon to bring up secondary X
173 int sock = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
174 struct sockaddr_un addr;
175 addr.sun_family = AF_UNIX;
176 strncpy(addr.sun_path, getconf(BUMBLEBEE_SOCKET), sizeof(addr.sun_path));
177 die_if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0,
178 "failed to connect to Bumblebee daemon: %s\n", strerror(errno));
179 static char c[256];
180 if (!getenv("PRIMUS_DISPLAY"))
181 {
182 send(sock, "Q VirtualDisplay", strlen("Q VirtualDisplay") + 1, 0);
183 recv(sock, &c, 255, 0);
184 die_if(memcmp(c, "Value: ", strlen("Value: ")), "unexpected query response\n");
185 *strchrnul(c, '\n') = 0;
186 *adpy_strp = strdup(c + 7);
187 }
188 if (!getenv("PRIMUS_libGLa"))
189 {
190 send(sock, "Q LibraryPath", strlen("Q LibraryPath") + 1, 0);
191 recv(sock, &c, 255, 0);
192 die_if(memcmp(c, "Value: ", strlen("Value: ")), "unexpected query response\n");
193 *strchrnul(c, '\n') = 0;
194 int npaths = 0;
195 for (char *p = c + 7; *p; npaths++, p = strchrnul(p + 1, ':'));
196 if (npaths)
197 {
198 char *bblibs = new char[strlen(c + 7) + npaths * strlen("/libGL.so.1") + 1], *b = bblibs, *n, *p;
199 for (p = c + 7; *p; p = n)
200 {
201 n = strchrnul(p + 1, ':');
202 b += sprintf(b, "%.*s/libGL.so.1", (int)(n - p), p);
203 }
204 *libgla_strp = bblibs;
205 }
206 }
207 send(sock, "C", 1, 0);
208 recv(sock, &c, 255, 0);
209 die_if(c[0] == 'N', "Bumblebee daemon reported: %s\n", c + 5);
210 die_if(c[0] != 'Y', "failure contacting Bumblebee daemon\n");
211 // the socket will be closed when the application quits, then bumblebee will shut down the secondary X
212 #else
213 #warning Building without Bumblebee daemon support
214 #endif
215 }
216 };
217
218 // Process-wide data
219 static struct PrimusInfo {
220 const char *adpy_str, *libgla_str;
221 EarlyInitializer ei;
222 // Readback-display synchronization method
223 // 0: no sync, 1: D lags behind one frame, 2: fully synced
224 int sync;
225 // 0: only errors, 1: warnings, 2: profiling
226 int loglevel;
227 // 0: autodetect, 1: texture, 2: PBO glDrawPixels
228 int dispmethod;
229 // sleep ratio in readback thread, percent
230 int autosleep;
231 // The "accelerating" X display
232 Display *adpy;
233 // The "displaying" X display. The same as the application is using, but
234 // primus opens its own connection.
235 Display *ddpy;
236 // An artifact: primus needs to make symbols from libglapi.so globally
237 // visible before loading Mesa
238 const void *needed_global;
239 CapturedFns afns;
240 CapturedFns dfns;
241 // FIXME: there are race conditions in accesses to these
242 DrawablesInfo drawables;
243 ContextsInfo contexts;
244
245 PrimusInfo():
246 adpy_str(getconf(PRIMUS_DISPLAY)),
247 libgla_str(getconf(PRIMUS_libGLa)),
248 ei(&adpy_str, &libgla_str),
249 sync(atoi(getconf(PRIMUS_SYNC))),
250 loglevel(atoi(getconf(PRIMUS_VERBOSE))),
251 dispmethod(atoi(getconf(PRIMUS_UPLOAD))),
252 autosleep(atoi(getconf(PRIMUS_SLEEP))),
253 adpy(XOpenDisplay(adpy_str)),
254 ddpy(XOpenDisplay(NULL)),
255 needed_global(dlopen(getconf(PRIMUS_LOAD_GLOBAL), RTLD_LAZY | RTLD_GLOBAL)),
256 afns(libgla_str),
257 dfns(getconf(PRIMUS_libGLd))
258 {
259 die_if(!adpy, "failed to open secondary X display\n");
260 die_if(!ddpy, "failed to open main X display\n");
261 die_if(!needed_global, "failed to load PRIMUS_LOAD_GLOBAL\n");
262 }
263 } primus;
264
265 // Thread-specific data
266 static __thread struct {
267 Display *dpy;
268 GLXDrawable drawable, read_drawable;
269 void make_current(Display *dpy, GLXDrawable draw, GLXDrawable read)
270 {
271 this->dpy = dpy;
272 this->drawable = draw;
273 this->read_drawable = read;
274 }
275 } tsdata;
276
277 // Profiler
278 struct Profiler {
279 const char *name;
280 const char * const *state_names;
281
282 double state_time[6], prev_timestamp, print_timestamp;
283 int state, nframes, width, height;
284
285 static double get_timestamp()
286 {
287 struct timespec tp;
288 clock_gettime(CLOCK_MONOTONIC, &tp);
289 return tp.tv_sec + 1e-9 * tp.tv_nsec;
290 }
291
292 Profiler(const char *name, const char * const *state_names):
293 name(name),
294 state_names(state_names),
295 state(0), nframes(0), width(0), height(0)
296 {
297 memset(state_time, 0, sizeof(state_time));
298 prev_timestamp = print_timestamp = get_timestamp();
299 }
300
301 void tick(bool state_reset = false)
302 {
303 if (primus.loglevel < 2)
304 return;
305 double timestamp = get_timestamp();
306 assert(state_reset || state_names[state]);
307 if (state_reset)
308 state = 0;
309 assert(state * sizeof(state_time[0]) < sizeof(state_time));
310 state_time[state++] += timestamp - prev_timestamp;
311 prev_timestamp = timestamp;
312 if (state_names[state])
313 return;
314 nframes++;
315 // check if it's time to print again
316 double period = timestamp - print_timestamp; // time since we printed
317 if (period < 5)
318 return;
319 // construct output
320 char buf[128], *cbuf = buf, *end = buf+128;
321 for (int i = 0; i < state; i++)
322 cbuf += snprintf(cbuf, end - cbuf, ", %.1f%% %s", 100 * state_time[i] / period, state_names[i]);
323 primus_perf("%s: %dx%d, %.1f fps%s\n", name, width, height, nframes / period, buf);
324 // start counting again
325 print_timestamp = timestamp;
326 nframes = 0;
327 memset(state_time, 0, sizeof(state_time));
328 }
329 };
330
331 // Find out the dimensions of the window
332 static void note_geometry(Display *dpy, Drawable draw, int *width, int *height)
333 {
334 Window root;
335 int x, y;
336 unsigned bw, d;
337 XGetGeometry(dpy, draw, &root, &x, &y, (unsigned *)width, (unsigned *)height, &bw, &d);
338 }
339
340 static GLXFBConfig* get_dconfigs(Display *dpy)
341 {
342 static const int attrs[] = {GLX_DOUBLEBUFFER, GL_TRUE, None};
343 int ncfg;
344 GLXFBConfig *dconfigs = primus.dfns.glXChooseFBConfig(dpy, 0, attrs, &ncfg);
345 die_if(!dconfigs, "broken GLX on main X display\n");
346 return dconfigs;
347 }
348
349 static bool test_drawpixels_fast(Display *dpy, GLXContext ctx, GLXFBConfig dconfig)
350 {
351 int width = 1920, height = 1080;
352 int pbattrs[] = {GLX_PBUFFER_WIDTH, width, GLX_PBUFFER_HEIGHT, height, GLX_PRESERVED_CONTENTS, True, None};
353 GLXPbuffer pbuffer = primus.dfns.glXCreatePbuffer(dpy, dconfig, pbattrs);
354 primus.dfns.glXMakeCurrent(dpy, pbuffer, ctx);
355 GLuint pbo;
356 primus.dfns.glGenBuffers(1, &pbo);
357 primus.dfns.glBindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, pbo);
358 primus.dfns.glBufferData(GL_PIXEL_UNPACK_BUFFER_EXT, width*height*4, NULL, GL_STREAM_DRAW);
359 void *pixeldata = malloc(width*height*4);
360
361 double end = 0.2 + Profiler::get_timestamp();
362 int iters = 0;
363 do {
364 primus.dfns.glBufferSubData(GL_PIXEL_UNPACK_BUFFER_EXT, 0, width*height*4, pixeldata);
365 primus.dfns.glDrawPixels(width, height, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
366 primus.dfns.glXSwapBuffers(dpy, pbuffer);
367 iters++;
368 } while (end > Profiler::get_timestamp());
369
370 free(pixeldata);
371 primus.dfns.glDeleteBuffers(1, &pbo);
372 primus.dfns.glXDestroyPbuffer(dpy, pbuffer);
373
374 bool is_fast = iters >= 12;
375 primus_perf("upload autodetection: will use %s path (%d iters)\n", is_fast ? "PBO" : "texture", iters);
376 return is_fast;
377 }
378
379 static void* display_work(void *vd)
380 {
381 GLXDrawable drawable = (GLXDrawable)vd;
382 DrawableInfo &di = primus.drawables[drawable];
383 int width, height;
384 static const float quad_vertex_coords[] = {-1, -1, -1, 1, 1, 1, 1, -1};
385 static const float quad_texture_coords[] = { 0, 0, 0, 1, 1, 1, 1, 0};
386 GLuint textures[2] = {0}, pbos[2] = {0};
387 int ctex = 0;
388 static const char *state_names[] = {"wait", "upload", "draw+swap", NULL};
389 Profiler profiler("display", state_names);
390 Display *ddpy = XOpenDisplay(NULL);
391 if (!ddpy) // Chromium sandbox prevents opening new connections
392 {
393 ddpy = primus.ddpy;
394 primus_warn("reusing initial X connection for display thread\n");
395 }
396 assert(di.kind == di.XWindow || di.kind == di.Window);
397 XSelectInput(ddpy, di.window, StructureNotifyMask);
398 note_geometry(ddpy, di.window, &width, &height);
399 di.update_geometry(width, height);
400 GLXFBConfig *dconfigs = get_dconfigs(ddpy);
401 GLXContext context = primus.dfns.glXCreateNewContext(ddpy, *dconfigs, GLX_RGBA_TYPE, NULL, True);
402 die_if(!primus.dfns.glXIsDirect(ddpy, context),
403 "failed to acquire direct rendering context for display thread\n");
404 if (!primus.dispmethod)
405 primus.dispmethod = test_drawpixels_fast(ddpy, context, *dconfigs) ? 2 : 1;
406 XFree(dconfigs);
407 primus.dfns.glXMakeCurrent(ddpy, di.window, context);
408 bool use_textures = (primus.dispmethod == 1);
409 if (use_textures)
410 {
411 primus.dfns.glVertexPointer (2, GL_FLOAT, 0, quad_vertex_coords);
412 primus.dfns.glTexCoordPointer(2, GL_FLOAT, 0, quad_texture_coords);
413 primus.dfns.glEnableClientState(GL_VERTEX_ARRAY);
414 primus.dfns.glEnableClientState(GL_TEXTURE_COORD_ARRAY);
415 primus.dfns.glGenTextures(2, textures);
416 primus.dfns.glEnable(GL_TEXTURE_2D);
417 }
418 else
419 primus.dfns.glGenBuffers(2, pbos);
420 for (;;)
421 {
422 sem_wait(&di.d.acqsem);
423 profiler.tick(true);
424 if (di.d.reinit)
425 {
426 if (di.d.reinit == di.SHUTDOWN)
427 {
428 if (use_textures)
429 primus.dfns.glDeleteTextures(2, textures);
430 else
431 primus.dfns.glDeleteBuffers(2, pbos);
432 primus.dfns.glXMakeCurrent(ddpy, 0, NULL);
433 primus.dfns.glXDestroyContext(ddpy, context);
434 if (ddpy != primus.ddpy)
435 XCloseDisplay(ddpy);
436 sem_post(&di.d.relsem);
437 return NULL;
438 }
439 di.d.reinit = di.NONE;
440 profiler.width = width = di.width;
441 profiler.height = height = di.height;
442 primus.dfns.glViewport(0, 0, width, height);
443 if (use_textures)
444 {
445 primus.dfns.glBindTexture(GL_TEXTURE_2D, textures[ctex ^ 1]);
446 primus.dfns.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
447 primus.dfns.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
448 primus.dfns.glBindTexture(GL_TEXTURE_2D, textures[ctex]);
449 primus.dfns.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
450 primus.dfns.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
451 }
452 else
453 {
454 primus.dfns.glBindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, pbos[ctex ^ 1]);
455 primus.dfns.glBufferData(GL_PIXEL_UNPACK_BUFFER_EXT, width*height*4, NULL, GL_STREAM_DRAW);
456 primus.dfns.glBindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, pbos[ctex]);
457 primus.dfns.glBufferData(GL_PIXEL_UNPACK_BUFFER_EXT, width*height*4, NULL, GL_STREAM_DRAW);
458 }
459 sem_post(&di.d.relsem);
460 continue;
461 }
462 if (use_textures)
463 primus.dfns.glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, di.pixeldata);
464 else
465 primus.dfns.glBufferSubData(GL_PIXEL_UNPACK_BUFFER_EXT, 0, width*height*4, di.pixeldata);
466 if (!primus.sync)
467 sem_post(&di.d.relsem); // Unlock as soon as possible
468 profiler.tick();
469 if (use_textures)
470 {
471 primus.dfns.glDrawArrays(GL_QUADS, 0, 4);
472 primus.dfns.glBindTexture(GL_TEXTURE_2D, textures[ctex ^= 1]);
473 }
474 else
475 {
476 primus.dfns.glDrawPixels(width, height, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
477 primus.dfns.glBindBuffer(GL_PIXEL_UNPACK_BUFFER_EXT, pbos[ctex ^= 1]);
478 }
479 primus.dfns.glXSwapBuffers(ddpy, di.window);
480 for (int pending = XPending(ddpy); pending > 0; pending--)
481 {
482 XEvent event;
483 XNextEvent(ddpy, &event);
484 if (event.type == ConfigureNotify)
485 di.update_geometry(event.xconfigure.width, event.xconfigure.height);
486 }
487 if (primus.sync)
488 sem_post(&di.d.relsem); // Unlock only after drawing
489 profiler.tick();
490 }
491 return NULL;
492 }
493
494 static void* readback_work(void *vd)
495 {
496 GLXDrawable drawable = (GLXDrawable)vd;
497 DrawableInfo &di = primus.drawables[drawable];
498 int width, height;
499 GLuint pbos[2] = {0};
500 int cbuf = 0;
501 unsigned sleep_usec = 0;
502 static const char *state_names[] = {"app", "sleep", "map", "wait", NULL};
503 Profiler profiler("readback", state_names);
504 struct timespec tp;
505 if (!primus.sync)
506 sem_post(&di.d.relsem); // No PBO is mapped initially
507 GLXContext context = primus.afns.glXCreateNewContext(primus.adpy, di.fbconfig, GLX_RGBA_TYPE, di.actx, True);
508 die_if(!primus.afns.glXIsDirect(primus.adpy, context),
509 "failed to acquire direct rendering context for readback thread\n");
510 primus.afns.glXMakeCurrent(primus.adpy, di.pbuffer, context);
511 primus.afns.glGenBuffers(2, &pbos[0]);
512 primus.afns.glReadBuffer(GL_FRONT);
513 for (;;)
514 {
515 sem_wait(&di.r.acqsem);
516 profiler.tick(true);
517 if (di.r.reinit)
518 {
519 clock_gettime(CLOCK_REALTIME, &tp);
520 tp.tv_sec += 1;
521 // Wait for D worker, if active
522 if (!primus.sync && sem_timedwait(&di.d.relsem, &tp))
523 {
524 pthread_cancel(di.d.worker);
525 sem_post(&di.d.relsem); // Pretend that D worker completed reinit
526 primus_warn("timeout waiting for display worker\n");
527 die_if(di.r.reinit != di.SHUTDOWN, "killed worker on resize\n");
528 }
529 di.d.reinit = di.r.reinit;
530 sem_post(&di.d.acqsem); // Signal D worker to reinit
531 sem_wait(&di.d.relsem); // Wait until reinit was completed
532 if (!primus.sync)
533 sem_post(&di.d.relsem); // Unlock as no PBO is currently mapped
534 if (di.r.reinit == di.SHUTDOWN)
535 {
536 primus.afns.glBindBuffer(GL_PIXEL_PACK_BUFFER_EXT, pbos[cbuf ^ 1]);
537 primus.afns.glUnmapBuffer(GL_PIXEL_PACK_BUFFER_EXT);
538 primus.afns.glDeleteBuffers(2, &pbos[0]);
539 primus.afns.glXMakeCurrent(primus.adpy, 0, NULL);
540 primus.afns.glXDestroyContext(primus.adpy, context);
541 sem_post(&di.r.relsem);
542 return NULL;
543 }
544 di.r.reinit = di.NONE;
545 profiler.width = width = di.width;
546 profiler.height = height = di.height;
547 primus.afns.glXMakeCurrent(primus.adpy, di.pbuffer, context);
548 primus.afns.glBindBuffer(GL_PIXEL_PACK_BUFFER_EXT, pbos[cbuf ^ 1]);
549 primus.afns.glBufferData(GL_PIXEL_PACK_BUFFER_EXT, width*height*4, NULL, GL_STREAM_READ);
550 primus.afns.glBindBuffer(GL_PIXEL_PACK_BUFFER_EXT, pbos[cbuf]);
551 primus.afns.glBufferData(GL_PIXEL_PACK_BUFFER_EXT, width*height*4, NULL, GL_STREAM_READ);
552 }
553 primus.afns.glWaitSync(di.sync, 0, GL_TIMEOUT_IGNORED);
554 primus.afns.glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
555 if (!primus.sync)
556 sem_post(&di.r.relsem); // Unblock main thread as soon as possible
557 usleep(sleep_usec);
558 profiler.tick();
559 if (primus.sync == 1) // Get the previous framebuffer
560 primus.afns.glBindBuffer(GL_PIXEL_PACK_BUFFER_EXT, pbos[cbuf ^ 1]);
561 double map_time = Profiler::get_timestamp();
562 GLvoid *pixeldata = primus.afns.glMapBuffer(GL_PIXEL_PACK_BUFFER_EXT, GL_READ_ONLY);
563 map_time = Profiler::get_timestamp() - map_time;
564 sleep_usec = (map_time * 1e6 + sleep_usec) * primus.autosleep / 100;
565 profiler.tick();
566 clock_gettime(CLOCK_REALTIME, &tp);
567 tp.tv_sec += 1;
568 if (!primus.sync && sem_timedwait(&di.d.relsem, &tp))
569 primus_warn("dropping a frame to avoid deadlock\n");
570 else
571 {
572 di.pixeldata = pixeldata;
573 sem_post(&di.d.acqsem);
574 if (primus.sync)
575 {
576 sem_wait(&di.d.relsem);
577 sem_post(&di.r.relsem); // Unblock main thread only after D::work has completed
578 }
579 cbuf ^= 1;
580 primus.afns.glBindBuffer(GL_PIXEL_PACK_BUFFER_EXT, pbos[cbuf]);
581 }
582 primus.afns.glUnmapBuffer(GL_PIXEL_PACK_BUFFER_EXT);
583 profiler.tick();
584 }
585 return NULL;
586 }
587
588 // Find appropriate FBConfigs on adpy for a given Visual on ddpy
589 static GLXFBConfig* match_fbconfig(Display *dpy, XVisualInfo *vis)
590 {
591 int ncfg, attrs[] = {
592 GLX_DOUBLEBUFFER, 0, GLX_STEREO, 0, GLX_AUX_BUFFERS, 0,
593 GLX_RED_SIZE, 0, GLX_GREEN_SIZE, 0, GLX_BLUE_SIZE, 0,
594 GLX_ALPHA_SIZE, 0, GLX_DEPTH_SIZE, 0, GLX_STENCIL_SIZE, 0,
595 GLX_ACCUM_RED_SIZE, 0, GLX_ACCUM_GREEN_SIZE, 0, GLX_ACCUM_BLUE_SIZE, 0, GLX_ACCUM_ALPHA_SIZE, 0,
596 GLX_SAMPLE_BUFFERS, 0, GLX_SAMPLES, 0, None
597 };
598 for (int i = 0; attrs[i] != None; i += 2)
599 primus.dfns.glXGetConfig(dpy, vis, attrs[i], &attrs[i+1]);
600 return primus.afns.glXChooseFBConfig(primus.adpy, 0, attrs, &ncfg);
601 }
602
603 GLXContext glXCreateContext(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct)
604 {
605 GLXFBConfig *acfgs = match_fbconfig(dpy, vis);
606 GLXContext actx = primus.afns.glXCreateNewContext(primus.adpy, *acfgs, GLX_RGBA_TYPE, shareList, direct);
607 primus.contexts.record(actx, *acfgs, shareList);
608 return actx;
609 }
610
611 GLXContext glXCreateNewContext(Display *dpy, GLXFBConfig config, int renderType, GLXContext shareList, Bool direct)
612 {
613 GLXContext actx = primus.afns.glXCreateNewContext(primus.adpy, config, renderType, shareList, direct);
614 primus.contexts.record(actx, config, shareList);
615 return actx;
616 }
617
618 GLXContext glXCreateContextAttribsARB(Display *dpy, GLXFBConfig config, GLXContext shareList, Bool direct, const int *attrib_list)
619 {
620 GLXContext actx = primus.afns.glXCreateContextAttribsARB(primus.adpy, config, shareList, direct, attrib_list);
621 primus.contexts.record(actx, config, shareList);
622 return actx;
623 }
624
625 void glXDestroyContext(Display *dpy, GLXContext ctx)
626 {
627 primus.contexts.erase(ctx);
628 // kludge: reap background tasks when deleting the last context
629 // otherwise something will deadlock during unloading the library
630 if (primus.contexts.empty())
631 for (DrawablesInfo::iterator i = primus.drawables.begin(); i != primus.drawables.end(); i++)
632 i->second.reap_workers();
633 primus.afns.glXDestroyContext(primus.adpy, ctx);
634 }
635
636 static GLXPbuffer create_pbuffer(DrawableInfo &di)
637 {
638 int pbattrs[] = {GLX_PBUFFER_WIDTH, di.width, GLX_PBUFFER_HEIGHT, di.height, GLX_PRESERVED_CONTENTS, True, None};
639 return primus.afns.glXCreatePbuffer(primus.adpy, di.fbconfig, pbattrs);
640 }
641
642 // Create or recall backing Pbuffer for the drawable
643 static GLXPbuffer lookup_pbuffer(Display *dpy, GLXDrawable draw, GLXContext ctx)
644 {
645 if (!draw)
646 return 0;
647 bool known = primus.drawables.known(draw);
648 DrawableInfo &di = primus.drawables[draw];
649 if (!known)
650 {
651 // Drawable is a plain X Window. Get the FBConfig from the context
652 if (ctx)
653 di.fbconfig = primus.contexts[ctx].fbconfig;
654 else
655 {
656 XWindowAttributes attrs;
657 die_if(!XGetWindowAttributes(dpy, draw, &attrs), "failed to query attributes");
658 int nvis;
659 XVisualInfo tmpl = {0}, *vis;
660 tmpl.visualid = XVisualIDFromVisual(attrs.visual);
661 die_if(!(vis = XGetVisualInfo(dpy, VisualIDMask, &tmpl, &nvis)), "no visuals");
662 di.fbconfig = *match_fbconfig(dpy, vis);
663 XFree(vis);
664 }
665 di.kind = di.XWindow;
666 di.window = draw;
667 note_geometry(dpy, draw, &di.width, &di.height);
668 }
669 else if (ctx && di.fbconfig != primus.contexts[ctx].fbconfig)
670 {
671 if (di.pbuffer)
672 {
673 primus_warn("recreating incompatible pbuffer\n");
674 di.reap_workers();
675 primus.afns.glXDestroyPbuffer(primus.adpy, di.pbuffer);
676 di.pbuffer = 0;
677 }
678 di.fbconfig = primus.contexts[ctx].fbconfig;
679 }
680 if (!di.pbuffer)
681 di.pbuffer = create_pbuffer(di);
682 return di.pbuffer;
683 }
684
685 Bool glXMakeCurrent(Display *dpy, GLXDrawable drawable, GLXContext ctx)
686 {
687 GLXPbuffer pbuffer = lookup_pbuffer(dpy, drawable, ctx);
688 tsdata.make_current(dpy, drawable, drawable);
689 return primus.afns.glXMakeCurrent(primus.adpy, pbuffer, ctx);
690 }
691
692 Bool glXMakeContextCurrent(Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx)
693 {
694 if (draw == read)
695 return glXMakeCurrent(dpy, draw, ctx);
696 GLXPbuffer pbuffer = lookup_pbuffer(dpy, draw, ctx);
697 GLXPbuffer pb_read = lookup_pbuffer(dpy, read, ctx);
698 tsdata.make_current(dpy, draw, read);
699 return primus.afns.glXMakeContextCurrent(primus.adpy, pbuffer, pb_read, ctx);
700 }
701
702 void glXSwapBuffers(Display *dpy, GLXDrawable drawable)
703 {
704 XFlush(dpy);
705 assert(primus.drawables.known(drawable));
706 DrawableInfo &di = primus.drawables[drawable];
707 primus.afns.glXSwapBuffers(primus.adpy, di.pbuffer);
708 if (di.kind == di.Pbuffer || di.kind == di.Pixmap)
709 return;
710 GLXContext ctx = glXGetCurrentContext();
711 if (!ctx)
712 primus_warn("glXSwapBuffers: no current context\n");
713 else if (drawable != tsdata.drawable)
714 primus_warn("glXSwapBuffers: drawable not current\n");
715 if (di.r.worker && ctx && (!di.actx || primus.contexts[di.actx].sharegroup != primus.contexts[ctx].sharegroup))
716 {
717 primus_warn("glXSwapBuffers: respawning threads after context change\n");
718 di.reap_workers();
719 }
720 if (!di.r.worker)
721 {
722 // Need to create a sharing context to use GL sync objects
723 di.actx = ctx;
724 di.d.spawn_worker(drawable, display_work);
725 di.r.spawn_worker(drawable, readback_work);
726 }
727 // Readback thread needs a sync object to avoid reading an incomplete frame
728 di.sync = primus.afns.glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
729 sem_post(&di.r.acqsem); // Signal the readback worker thread
730 sem_wait(&di.r.relsem); // Wait until it has issued glReadBuffer
731 primus.afns.glDeleteSync(di.sync);
732 if (di.reinit == di.RESIZE)
733 {
734 __sync_synchronize();
735 primus.afns.glXDestroyPbuffer(primus.adpy, di.pbuffer);
736 di.pbuffer = create_pbuffer(di);
737 if (ctx) // FIXME: drawable can be current in other threads
738 glXMakeContextCurrent(dpy, tsdata.drawable, tsdata.read_drawable, ctx);
739 di.r.reinit = di.reinit;
740 di.reinit = di.NONE;
741 }
742 }
743
744 GLXWindow glXCreateWindow(Display *dpy, GLXFBConfig config, Window win, const int *attribList)
745 {
746 GLXFBConfig *dconfigs = get_dconfigs(dpy);
747 GLXWindow glxwin = primus.dfns.glXCreateWindow(dpy, *dconfigs, win, attribList);
748 XFree(dconfigs);
749 DrawableInfo &di = primus.drawables[glxwin];
750 di.kind = di.Window;
751 di.fbconfig = config;
752 di.window = win;
753 note_geometry(dpy, win, &di.width, &di.height);
754 return glxwin;
755 }
756
757 DrawableInfo::~DrawableInfo()
758 {
759 reap_workers();
760 if (pbuffer)
761 primus.afns.glXDestroyPbuffer(primus.adpy, pbuffer);
762 }
763
764 void glXDestroyWindow(Display *dpy, GLXWindow window)
765 {
766 assert(primus.drawables.known(window));
767 primus.drawables.erase(window);
768 primus.dfns.glXDestroyWindow(dpy, window);
769 }
770
771 GLXPbuffer glXCreatePbuffer(Display *dpy, GLXFBConfig config, const int *attribList)
772 {
773 GLXFBConfig *dconfigs = get_dconfigs(dpy);
774 GLXPbuffer pbuffer = primus.dfns.glXCreatePbuffer(dpy, *dconfigs, attribList);
775 XFree(dconfigs);
776 DrawableInfo &di = primus.drawables[pbuffer];
777 di.kind = di.Pbuffer;
778 di.fbconfig = config;
779 for (int i = 0; attribList[i] != None; i++)
780 if (attribList[i] == GLX_PBUFFER_WIDTH)
781 di.width = attribList[i+1];
782 else if (attribList[i] == GLX_PBUFFER_HEIGHT)
783 di.height = attribList[i+1];
784 return pbuffer;
785 }
786
787 void glXDestroyPbuffer(Display *dpy, GLXPbuffer pbuf)
788 {
789 assert(primus.drawables.known(pbuf));
790 primus.drawables.erase(pbuf);
791 primus.dfns.glXDestroyPbuffer(dpy, pbuf);
792 }
793
794 GLXPixmap glXCreatePixmap(Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attribList)
795 {
796 GLXFBConfig *dconfigs = get_dconfigs(dpy);
797 GLXPixmap glxpix = primus.dfns.glXCreatePixmap(dpy, *dconfigs, pixmap, attribList);
798 XFree(dconfigs);
799 DrawableInfo &di = primus.drawables[glxpix];
800 di.kind = di.Pixmap;
801 di.fbconfig = config;
802 note_geometry(dpy, pixmap, &di.width, &di.height);
803 return glxpix;
804 }
805
806 void glXDestroyPixmap(Display *dpy, GLXPixmap pixmap)
807 {
808 assert(primus.drawables.known(pixmap));
809 primus.drawables.erase(pixmap);
810 primus.dfns.glXDestroyPixmap(dpy, pixmap);
811 }
812
813 GLXPixmap glXCreateGLXPixmap(Display *dpy, XVisualInfo *visual, Pixmap pixmap)
814 {
815 GLXPixmap glxpix = primus.dfns.glXCreateGLXPixmap(dpy, visual, pixmap);
816 DrawableInfo &di = primus.drawables[glxpix];
817 di.kind = di.Pixmap;
818 note_geometry(dpy, pixmap, &di.width, &di.height);
819 GLXFBConfig *acfgs = match_fbconfig(dpy, visual);
820 di.fbconfig = *acfgs;
821 return glxpix;
822 }
823
824 void glXDestroyGLXPixmap(Display *dpy, GLXPixmap pixmap)
825 {
826 glXDestroyPixmap(dpy, pixmap);
827 }
828
829 static XVisualInfo *match_visual(Display *dpy, int attrs[])
830 {
831 XVisualInfo *vis = glXChooseVisual(dpy, 0, attrs);
832 for (int i = 2; attrs[i] != None && vis; i += 2)
833 {
834 int tmp = attrs[i+1];
835 primus.dfns.glXGetConfig(dpy, vis, attrs[i], &attrs[i+1]);
836 if (tmp != attrs[i+1])
837 vis = NULL;
838 }
839 return vis;
840 }
841
842 XVisualInfo *glXGetVisualFromFBConfig(Display *dpy, GLXFBConfig config)
843 {
844 if (!primus.afns.glXGetVisualFromFBConfig(primus.adpy, config))
845 return NULL;
846 int i, attrs[] = {
847 GLX_RGBA, GLX_DOUBLEBUFFER,
848 GLX_RED_SIZE, 0, GLX_GREEN_SIZE, 0, GLX_BLUE_SIZE, 0,
849 GLX_ALPHA_SIZE, 0, GLX_DEPTH_SIZE, 0, GLX_STENCIL_SIZE, 0,
850 GLX_SAMPLE_BUFFERS, 0, GLX_SAMPLES, 0, None
851 };
852 for (i = 2; attrs[i] != None; i += 2)
853 primus.afns.glXGetFBConfigAttrib(primus.adpy, config, attrs[i], &attrs[i+1]);
854 XVisualInfo *vis = NULL;
855 for (i -= 2; i >= 0 && !vis; i -= 2)
856 {
857 vis = match_visual(dpy, attrs);
858 attrs[i] = None;
859 }
860 return vis;
861 }
862
863 int glXGetFBConfigAttrib(Display *dpy, GLXFBConfig config, int attribute, int *value)
864 {
865 int r = primus.afns.glXGetFBConfigAttrib(primus.adpy, config, attribute, value);
866 if (attribute == GLX_VISUAL_ID && *value)
867 return primus.dfns.glXGetConfig(dpy, glXGetVisualFromFBConfig(dpy, config), attribute, value);
868 return r;
869 }
870
871 void glXQueryDrawable(Display *dpy, GLXDrawable draw, int attribute, unsigned int *value)
872 {
873 primus.afns.glXQueryDrawable(primus.adpy, lookup_pbuffer(dpy, draw, NULL), attribute, value);
874 }
875
876 void glXUseXFont(Font font, int first, int count, int list)
877 {
878 unsigned long prop;
879 Display *dpy = glXGetCurrentDisplay();
880 XFontStruct *fs = XQueryFont(dpy, font);
881 XGetFontProperty(fs, XA_FONT, &prop);
882 char *xlfd = XGetAtomName(dpy, prop);
883 Font afont = XLoadFont(primus.adpy, xlfd);
884 primus.afns.glXUseXFont(afont, first, count, list);
885 XUnloadFont(primus.adpy, afont);
886 XFree(xlfd);
887 XFreeFontInfo(NULL, fs, 1);
888 }
889
890 GLXContext glXGetCurrentContext(void)
891 {
892 return primus.afns.glXGetCurrentContext();
893 }
894
895 GLXDrawable glXGetCurrentDrawable(void)
896 {
897 return tsdata.drawable;
898 }
899
900 void glXWaitGL(void)
901 {
902 }
903
904 void glXWaitX(void)
905 {
906 }
907
908 Display *glXGetCurrentDisplay(void)
909 {
910 return tsdata.dpy;
911 }
912
913 GLXDrawable glXGetCurrentReadDrawable(void)
914 {
915 return tsdata.read_drawable;
916 }
917
918 // Application sees ddpy-side Visuals, but adpy-side FBConfigs and Contexts
919 XVisualInfo* glXChooseVisual(Display *dpy, int screen, int *attribList)
920 {
921 return primus.dfns.glXChooseVisual(dpy, screen, attribList);
922 }
923
924 int glXGetConfig(Display *dpy, XVisualInfo *visual, int attrib, int *value)
925 {
926 return primus.dfns.glXGetConfig(dpy, visual, attrib, value);
927 }
928
929 // GLX forwarders that reroute to adpy
930 #define DEF_GLX_PROTO(ret, name, par, ...) \
931 ret name par \
932 { return primus.afns.name(primus.adpy, __VA_ARGS__); }
933 #include "glx-dpyredir.def"
934 #undef DEF_GLX_PROTO
935
936 // OpenGL forwarders
937 #define DEF_GLX_PROTO(ret, name, par, ...) \
938 void ifunc_##name(void) asm(#name) __attribute__((visibility("default"),ifunc("i" #name))); \
939 extern "C" { \
940 static ret l##name par \
941 { return primus.afns.name(__VA_ARGS__); } \
942 static void *i##name(void) \
943 { return primus.afns.handle ? real_dlsym(primus.afns.handle, #name) : (void*)l##name; } }
944 #include "gl-passthru.def"
945 #undef DEF_GLX_PROTO
946
947 // GLX extensions
948
949 int glXSwapIntervalSGI(int interval)
950 {
951 return 1; // Indicate failure to set swapinterval
952 }
953
954 __GLXextFuncPtr glXGetProcAddress(const GLubyte *procName)
955 {
956 static const char * const redefined_names[] = {
957 #define DEF_GLX_PROTO(ret, name, args, ...) #name,
958 #include "glx-reimpl.def"
959 #include "glxext-reimpl.def"
960 #include "glx-dpyredir.def"
961 #undef DEF_GLX_PROTO
962 };
963 static const __GLXextFuncPtr redefined_fns[] = {
964 #define DEF_GLX_PROTO(ret, name, args, ...) (__GLXextFuncPtr)name,
965 #include "glx-reimpl.def"
966 #include "glxext-reimpl.def"
967 #include "glx-dpyredir.def"
968 #undef DEF_GLX_PROTO
969 };
970 enum {n_redefined = sizeof(redefined_fns) / sizeof(redefined_fns[0])};
971 // Non-GLX functions are forwarded to the accelerating libGL
972 if (memcmp(procName, "glX", 3))
973 return primus.afns.glXGetProcAddress(procName);
974 // All GLX functions are either implemented in primus or not available
975 for (int i = 0; i < n_redefined; i++)
976 if (!strcmp((const char *)procName, redefined_names[i]))
977 return redefined_fns[i];
978 return NULL;
979 }
980
981 __GLXextFuncPtr glXGetProcAddressARB(const GLubyte *procName)
982 {
983 return glXGetProcAddress(procName);
984 }
985
986 static const char glxext_clientside[] = "GLX_ARB_get_proc_address ";
987 static const char glxext_adpy[] = "GLX_ARB_create_context GLX_ARB_create_context_profile ";
988 static const char glxext_ddpy[] = "";
989
990 const char *glXGetClientString(Display *dpy, int name)
991 {
992 static std::string exts(std::string(glxext_clientside) + glxext_adpy + glxext_ddpy);
993 switch (name)
994 {
995 case GLX_VENDOR: return "primus";
996 case GLX_VERSION: return "1.4";
997 case GLX_EXTENSIONS: return exts.c_str();
998 default: return NULL;
999 }
1000 }
1001
1002 static std::string intersect_exts(const char *set1, const char *set2)
1003 {
1004 std::string r;
1005 for (const char *p; *set1; set1 = p + 1)
1006 {
1007 p = strchr(set1, ' ');
1008 if (memmem(set2, strlen(set2), set1, p - set1))
1009 r.append(set1, p - set1 + 1);
1010 }
1011 return r;
1012 }
1013
1014 const char *glXQueryExtensionsString(Display *dpy, int screen)
1015 {
1016 static std::string exts
1017 (std::string(glxext_clientside)
1018 + intersect_exts(glxext_adpy, primus.afns.glXQueryExtensionsString(primus.adpy, 0))
1019 + intersect_exts(glxext_ddpy, primus.dfns.glXQueryExtensionsString(dpy, 0)));
1020 return exts.c_str();
1021 }
1022
1023 // OpenGL ABI specifies that anything above OpenGL 1.2 + ARB_multitexture must
1024 // be obtained via glXGetProcAddress, but some applications link against
1025 // extension functions, and Mesa and vendor libraries let them
1026 #ifndef PRIMUS_STRICT
1027 #warning Enabled workarounds for applications demanding more than promised by the OpenGL ABI
1028
1029 // OpenGL extension forwarders
1030 #define P(name) \
1031 void ifunc_##name(void) asm(#name) __attribute__((visibility("default"),ifunc("i" #name))); \
1032 extern "C" { static void *i##name(void) \
1033 { return primus.afns.handle ? real_dlsym(primus.afns.handle, #name) : NULL; } }
1034 #include "glext-passthru.def"
1035 #undef P
1036 #endif