Debian Codegraph @

libglfork.cpp

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