Debian Codegraph @

libglfork.cpp

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