You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

393 lines
14 KiB

  1. /*
  2. Copyright 2005-2014 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. // Uncomment next line to disable shared memory features if you do not have libXext
  24. // (http://www.xfree86.org/current/mit-shm.html)
  25. //#define X_NOSHMEM
  26. // Note that it may happen that the build environment supports the shared-memory extension
  27. // (so there's no build-time reason to disable the relevant code by defining X_NOSHMEM),
  28. // but that using shared memory still fails at run time.
  29. // This situation will (ultimately) cause the error handler set by XSetErrorHandler()
  30. // to be invoked with XErrorEvent::minor_code==X_ShmAttach. The code below tries to make
  31. // such a determination at XShmAttach() time, which seems plausible, but unfortunately
  32. // it has also been observed in a specific environment that the error may be reported
  33. // at a later time instead, even after video::init_window() has returned.
  34. // It is not clear whether this may happen in that way in any environment where it might
  35. // depend on the kind of display, e.g., local vs. over "ssh -X", so #define'ing X_NOSHMEM
  36. // may not always be the appropriate solution, therefore an environment variable
  37. // has been introduced to disable shared memory at run time.
  38. // A diagnostic has been added to advise the user about possible workarounds.
  39. // X_ShmAttach macro was changed to 1 due to recent changes to X11/extensions/XShm.h header.
  40. #include "video.h"
  41. #include <string.h>
  42. #include <stdio.h>
  43. #include <stdlib.h>
  44. #include <math.h>
  45. #include <X11/Xlib.h>
  46. #include <X11/Xutil.h>
  47. #include <X11/keysym.h>
  48. #include <sys/time.h>
  49. #include <signal.h>
  50. #include <pthread.h>
  51. #ifndef X_NOSHMEM
  52. #include <errno.h>
  53. #include <X11/extensions/XShm.h>
  54. #include <sys/ipc.h>
  55. #include <sys/shm.h>
  56. static XShmSegmentInfo shmseginfo;
  57. static Pixmap pixmap = 0;
  58. static bool already_called_X_ShmAttach = false;
  59. static bool already_advised_about_NOSHMEM_workarounds = false;
  60. static const char* NOSHMEM_env_var_name = "TBB_EXAMPLES_X_NOSHMEM";
  61. #endif
  62. static char *display_name = NULL;
  63. static Display *dpy = NULL;
  64. static Screen *scrn;
  65. static Visual *vis;
  66. static Colormap cmap;
  67. static GC gc;
  68. static Window win, rootW;
  69. static int dispdepth = 0;
  70. static XGCValues xgcv;
  71. static XImage *ximage;
  72. static int x_error = 0;
  73. static int vidtype = 3;
  74. int g_sizex, g_sizey;
  75. static video *g_video = 0;
  76. unsigned int *g_pImg = 0;
  77. static int g_fps = 0;
  78. struct timeval g_time;
  79. static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
  80. Atom _XA_WM_DELETE_WINDOW = 0;// like in Xatom.h
  81. ///////////////////////////////////////////// public methods of video class ///////////////////////
  82. video::video()
  83. {
  84. assert(g_video == 0);
  85. g_video = this; title = "Video"; calc_fps = running = false; updating = true;
  86. }
  87. inline void mask2bits(unsigned int mask, unsigned int &save, depth_t &shift)
  88. {
  89. save = mask; if(!mask) { shift = dispdepth/3; return; }
  90. shift = 0; while(!(mask&1)) ++shift, mask >>= 1;
  91. int bits = 0; while(mask&1) ++bits, mask >>= 1;
  92. shift += bits - 8;
  93. }
  94. int xerr_handler(Display* dpy_, XErrorEvent *error)
  95. {
  96. x_error = error->error_code;
  97. if(g_video) g_video->running = false;
  98. #ifndef X_NOSHMEM
  99. if (error->minor_code==1/*X_ShmAttach*/ && already_called_X_ShmAttach && !already_advised_about_NOSHMEM_workarounds)
  100. {
  101. char err[256]; XGetErrorText(dpy_, x_error, err, 255);
  102. fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
  103. fprintf(stderr, "If you are seeing a black output window, try setting %s environment variable to 1"
  104. " to disable shared memory extensions (0 to re-enable, other values undefined),"
  105. " or rebuilding with X_NOSHMEM defined in " __FILE__ "\n", NOSHMEM_env_var_name);
  106. already_advised_about_NOSHMEM_workarounds = true;
  107. }
  108. #else
  109. (void) dpy_; // warning prevention
  110. #endif
  111. return 0;
  112. }
  113. bool video::init_window(int xsize, int ysize)
  114. {
  115. { //enclose local variables before fail label
  116. g_sizex = xsize; g_sizey = ysize;
  117. // Open the display
  118. if (!dpy) {
  119. dpy = XOpenDisplay(display_name);
  120. if (!dpy) {
  121. fprintf(stderr, "Can't open X11 display %s\n", XDisplayName(display_name));
  122. goto fail;
  123. }
  124. }
  125. int theScreen = DefaultScreen(dpy);
  126. scrn = ScreenOfDisplay(dpy, theScreen);
  127. dispdepth = DefaultDepth(dpy, theScreen);
  128. XVisualInfo vinfo;
  129. if (!( (dispdepth >= 15 && dispdepth <= 32 && XMatchVisualInfo(dpy, theScreen, dispdepth, TrueColor, &vinfo) )
  130. || XMatchVisualInfo(dpy, theScreen, 24, TrueColor, &vinfo)
  131. || XMatchVisualInfo(dpy, theScreen, 32, TrueColor, &vinfo)
  132. || XMatchVisualInfo(dpy, theScreen, 16, TrueColor, &vinfo)
  133. || XMatchVisualInfo(dpy, theScreen, 15, TrueColor, &vinfo)
  134. )) {
  135. fprintf(stderr, "Display has no appropriate True Color visual\n");
  136. goto fail;
  137. }
  138. vis = vinfo.visual;
  139. depth = dispdepth = vinfo.depth;
  140. mask2bits(vinfo.red_mask, red_mask, red_shift);
  141. mask2bits(vinfo.green_mask, green_mask, green_shift);
  142. mask2bits(vinfo.blue_mask, blue_mask, blue_shift);
  143. rootW = RootWindow(dpy, theScreen);
  144. cmap = XCreateColormap(dpy, rootW, vis, AllocNone);
  145. XSetWindowAttributes attrs;
  146. attrs.backing_store = Always;
  147. attrs.colormap = cmap;
  148. attrs.event_mask = StructureNotifyMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask;
  149. attrs.background_pixel = BlackPixelOfScreen(scrn);
  150. attrs.border_pixel = WhitePixelOfScreen(scrn);
  151. win = XCreateWindow(dpy, rootW,
  152. 0, 0, xsize, ysize, 2,
  153. dispdepth, InputOutput, vis,
  154. CWBackingStore | CWColormap | CWEventMask |
  155. CWBackPixel | CWBorderPixel,
  156. &attrs);
  157. if(!win) {
  158. fprintf(stderr, "Can't create the window\n");
  159. goto fail;
  160. }
  161. XSizeHints sh;
  162. sh.flags = PSize | PMinSize | PMaxSize;
  163. sh.width = sh.min_width = sh.max_width = xsize;
  164. sh.height = sh.min_height = sh.max_height = ysize;
  165. XSetStandardProperties( dpy, win, g_video->title, g_video->title, None, NULL, 0, &sh );
  166. _XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", false);
  167. XSetWMProtocols(dpy, win, &_XA_WM_DELETE_WINDOW, 1);
  168. gc = XCreateGC(dpy, win, 0L, &xgcv);
  169. XMapRaised(dpy, win);
  170. XFlush(dpy);
  171. #ifdef X_FULLSYNC
  172. XSynchronize(dpy, true);
  173. #endif
  174. XSetErrorHandler(xerr_handler);
  175. int imgbytes = xsize*ysize*(dispdepth<=16?2:4);
  176. const char *vidstr;
  177. #ifndef X_NOSHMEM
  178. int major, minor, pixmaps;
  179. if(XShmQueryExtension(dpy) &&
  180. XShmQueryVersion(dpy, &major, &minor, &pixmaps))
  181. { // Shared memory
  182. if(NULL!=getenv(NOSHMEM_env_var_name) && 0!=strcmp("0",getenv(NOSHMEM_env_var_name))) {
  183. goto generic;
  184. }
  185. shmseginfo.shmid = shmget(IPC_PRIVATE, imgbytes, IPC_CREAT|0777);
  186. if(shmseginfo.shmid < 0) {
  187. fprintf(stderr, "Warning: Can't get shared memory: %s\n", strerror(errno));
  188. goto generic;
  189. }
  190. g_pImg = (unsigned int*)(shmseginfo.shmaddr = (char*)shmat(shmseginfo.shmid, 0, 0));
  191. if(g_pImg == (unsigned int*)-1) {
  192. fprintf(stderr, "Warning: Can't attach to shared memory: %s\n", strerror(errno));
  193. shmctl(shmseginfo.shmid, IPC_RMID, NULL);
  194. goto generic;
  195. }
  196. shmseginfo.readOnly = false;
  197. if(!XShmAttach(dpy, &shmseginfo) || x_error) {
  198. char err[256]; XGetErrorText(dpy, x_error, err, 255);
  199. fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
  200. shmdt(shmseginfo.shmaddr); shmctl(shmseginfo.shmid, IPC_RMID, NULL);
  201. goto generic;
  202. }
  203. already_called_X_ShmAttach = true;
  204. #ifndef X_NOSHMPIX
  205. if(pixmaps && XShmPixmapFormat(dpy) == ZPixmap)
  206. { // Pixmaps
  207. vidtype = 2; vidstr = "X11 shared memory pixmap";
  208. pixmap = XShmCreatePixmap(dpy, win, (char*)g_pImg, &shmseginfo, xsize, ysize, dispdepth);
  209. XSetWindowBackgroundPixmap(dpy, win, pixmap);
  210. } else
  211. #endif//!X_NOSHMPIX
  212. { // Standard
  213. vidtype = 1; vidstr = "X11 shared memory";
  214. ximage = XShmCreateImage(dpy, vis, dispdepth,
  215. ZPixmap, 0, &shmseginfo, xsize, ysize);
  216. if(!ximage) {
  217. fprintf(stderr, "Can't create the shared image\n");
  218. goto fail;
  219. }
  220. assert(ximage->bytes_per_line == xsize*(dispdepth<=16?2:4));
  221. ximage->data = shmseginfo.shmaddr;
  222. }
  223. } else
  224. #endif
  225. {
  226. #ifndef X_NOSHMEM
  227. generic:
  228. #endif
  229. vidtype = 0; vidstr = "generic X11";
  230. g_pImg = new unsigned int[imgbytes/sizeof(int)];
  231. ximage = XCreateImage(dpy, vis, dispdepth, ZPixmap, 0, (char*)g_pImg, xsize, ysize, 32, imgbytes/ysize);
  232. if(!ximage) {
  233. fprintf(stderr, "Can't create the image\n");
  234. goto fail;
  235. }
  236. }
  237. // Note: It may be more efficient to adopt the server's byte order
  238. // and swap once per get_color() call instead of once per pixel.
  239. const uint32_t probe = 0x03020100;
  240. const bool big_endian = (((const char*)(&probe))[0]==0x03);
  241. ximage->byte_order = big_endian ? MSBFirst : LSBFirst;
  242. printf("Note: using %s with %s visual for %d-bit color depth\n", vidstr, vis==DefaultVisual(dpy, theScreen)?"default":"non-default", dispdepth);
  243. running = true;
  244. return true;
  245. } // end of enclosing local variables
  246. fail:
  247. terminate(); init_console();
  248. return false;
  249. }
  250. bool video::init_console()
  251. {
  252. if(!g_pImg && g_sizex && g_sizey) {
  253. dispdepth = 24; red_shift = 16; vidtype = 3; // fake video
  254. g_pImg = new unsigned int[g_sizex*g_sizey];
  255. running = true;
  256. }
  257. return true;
  258. }
  259. void video::terminate()
  260. {
  261. running = false;
  262. if(dpy) {
  263. vidtype = 3; // stop video
  264. if(threaded) { pthread_mutex_lock(&g_mutex); pthread_mutex_unlock(&g_mutex); }
  265. if(ximage) { XDestroyImage(ximage); ximage = 0; g_pImg = 0; } // it frees g_pImg for vidtype == 0
  266. #ifndef X_NOSHMEM
  267. if(pixmap) XFreePixmap(dpy, pixmap);
  268. if(shmseginfo.shmaddr) { XShmDetach(dpy, &shmseginfo); shmdt(shmseginfo.shmaddr); g_pImg = 0; }
  269. if(shmseginfo.shmid >= 0) shmctl(shmseginfo.shmid, IPC_RMID, NULL);
  270. #endif
  271. if(gc) XFreeGC(dpy, gc);
  272. if(win) XDestroyWindow(dpy, win);
  273. XCloseDisplay(dpy); dpy = 0;
  274. }
  275. if(g_pImg) { delete[] g_pImg; g_pImg = 0; } // if was allocated for console mode
  276. }
  277. video::~video()
  278. {
  279. if(g_video) terminate();
  280. g_video = 0;
  281. }
  282. //! Do standard event loop
  283. void video::main_loop()
  284. {
  285. struct timezone tz; gettimeofday(&g_time, &tz);
  286. on_process();
  287. }
  288. //! Check for pending events once
  289. bool video::next_frame()
  290. {
  291. if(!running) return false;
  292. //! try acquire mutex if threaded code, returns on failure
  293. if(vidtype == 3 || threaded && pthread_mutex_trylock(&g_mutex))
  294. return running;
  295. //! Refresh screen picture
  296. g_fps++;
  297. #ifndef X_NOSHMPIX
  298. if(vidtype == 2 && updating) XClearWindow(dpy, win);
  299. #endif
  300. while( XPending(dpy) ) {
  301. XEvent report; XNextEvent(dpy, &report);
  302. switch( report.type ) {
  303. case ClientMessage:
  304. if(report.xclient.format != 32 || report.xclient.data.l[0] != _XA_WM_DELETE_WINDOW) break;
  305. case DestroyNotify:
  306. running = false;
  307. case KeyPress:
  308. on_key( XLookupKeysym(&report.xkey, 0) ); break;
  309. case ButtonPress:
  310. on_mouse( report.xbutton.x, report.xbutton.y, report.xbutton.button ); break;
  311. case ButtonRelease:
  312. on_mouse( report.xbutton.x, report.xbutton.y, -report.xbutton.button ); break;
  313. }
  314. }
  315. struct timezone tz; struct timeval now_time; gettimeofday(&now_time, &tz);
  316. double sec = (now_time.tv_sec+1.0*now_time.tv_usec/1000000.0) - (g_time.tv_sec+1.0*g_time.tv_usec/1000000.0);
  317. if(sec > 1) {
  318. memcpy(&g_time, &now_time, sizeof(g_time));
  319. if(calc_fps) {
  320. double fps = g_fps; g_fps = 0;
  321. char buffer[256]; snprintf(buffer, 256, "%s%s: %d fps", title, updating?"":" (no updating)", int(fps/sec));
  322. XStoreName(dpy, win, buffer);
  323. }
  324. #ifndef X_FULLSYNC
  325. XSync(dpy, false); // It is often better then using XSynchronize(dpy, true)
  326. #endif//X_FULLSYNC
  327. }
  328. if(threaded) pthread_mutex_unlock(&g_mutex);
  329. return true;
  330. }
  331. //! Change window title
  332. void video::show_title()
  333. {
  334. if(vidtype < 3)
  335. XStoreName(dpy, win, title);
  336. }
  337. drawing_area::drawing_area(int x, int y, int sizex, int sizey)
  338. : start_x(x), start_y(y), size_x(sizex), size_y(sizey), pixel_depth(dispdepth),
  339. base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex), ptr32(g_pImg)
  340. {
  341. assert(x < g_sizex); assert(y < g_sizey);
  342. assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
  343. index = base_index; // current index
  344. }
  345. void drawing_area::update()
  346. {
  347. if(!g_video->updating) return;
  348. #ifndef X_NOSHMEM
  349. switch(vidtype) {
  350. case 0:
  351. #endif
  352. pthread_mutex_lock(&g_mutex);
  353. if(vidtype == 0) XPutImage(dpy, win, gc, ximage, start_x, start_y, start_x, start_y, size_x, size_y);
  354. pthread_mutex_unlock(&g_mutex);
  355. #ifndef X_NOSHMEM
  356. break;
  357. case 1:
  358. pthread_mutex_lock(&g_mutex);
  359. if(vidtype == 1) XShmPutImage(dpy, win, gc, ximage, start_x, start_y, start_x, start_y, size_x, size_y, false);
  360. pthread_mutex_unlock(&g_mutex);
  361. break;
  362. /*case 2: make it in next_frame(); break;*/
  363. }
  364. #endif
  365. }