File: xvideo.cpp

package info (click to toggle)
onetbb 2022.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,444 kB
  • sloc: cpp: 129,228; ansic: 9,745; python: 808; xml: 183; objc: 176; makefile: 66; sh: 66; awk: 41; javascript: 37
file content (468 lines) | stat: -rw-r--r-- 16,169 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
    Copyright (c) 2005-2022 Intel Corporation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

// Uncomment next line to disable shared memory features if you do not have libXext
// (http://www.xfree86.org/current/mit-shm.html)
//#define X_NOSHMEM

// Note that it may happen that the build environment supports the shared-memory extension
// (so there's no build-time reason to disable the relevant code by defining X_NOSHMEM),
// but that using shared memory still fails at run time.
// This situation will (ultimately) cause the error handler set by XSetErrorHandler()
// to be invoked with XErrorEvent::minor_code==X_ShmAttach. The code below tries to make
// such a determination at XShmAttach() time, which seems plausible, but unfortunately
// it has also been observed in a specific environment that the error may be reported
// at a later time instead, even after video::init_window() has returned.
// It is not clear whether this may happen in that way in any environment where it might
// depend on the kind of display, e.g., local vs. over "ssh -X", so #define'ing X_NOSHMEM
// may not always be the appropriate solution, therefore an environment variable
// has been introduced to disable shared memory at run time.
// A diagnostic has been added to advise the user about possible workarounds.
// X_ShmAttach macro was changed to 1 due to recent changes to X11/extensions/XShm.h header.

#include "video.hpp"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>

#ifndef X_NOSHMEM
#include <errno.h>
#include <X11/extensions/XShm.h>
#include <sys/ipc.h>
#include <sys/shm.h>

static XShmSegmentInfo shmseginfo;
static Pixmap pixmap = 0;
static bool already_called_X_ShmAttach = false;
static bool already_advised_about_NOSHMEM_workarounds = false;
#endif
static char *display_name = nullptr;
static Display *dpy = nullptr;
static Screen *scrn;
static Visual *vis;
static Colormap cmap;
static GC gc;
static Window win, rootW;
static int dispdepth = 0;
static XGCValues xgcv;
static XImage *ximage;
static int x_error = 0;
static int vidtype = 3;
int g_sizex, g_sizey;
static video *g_video = 0;
unsigned int *g_pImg = 0;
static int g_fps = 0;
struct timeval g_time;
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
Atom _XA_WM_DELETE_WINDOW = 0; // like in Xatom.h

///////////////////////////////////////////// public methods of video class ///////////////////////

video::video() {
    assert(g_video == 0);
    g_video = this;
    title = "Video";
    calc_fps = running = false;
    updating = true;
}

inline void mask2bits(unsigned int mask, unsigned int &save, depth_t &shift) {
    save = mask;
    if (!mask) {
        shift = dispdepth / 3;
        return;
    }
    shift = 0;
    while (!(mask & 1))
        ++shift, mask >>= 1;
    int bits = 0;
    while (mask & 1)
        ++bits, mask >>= 1;
    shift += bits - 8;
}

int xerr_handler(Display *dpy_, XErrorEvent *error) {
    x_error = error->error_code;
    if (g_video)
        g_video->running = false;
#ifndef X_NOSHMEM
    if (error->minor_code == 1 /*X_ShmAttach*/ && already_called_X_ShmAttach &&
        !already_advised_about_NOSHMEM_workarounds) {
        char err[256];
        XGetErrorText(dpy_, x_error, err, 255);
        fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
        fprintf(
            stderr,
            "If you are seeing a black output window, сheck if you have installed Xext library and rebuild project");
        already_advised_about_NOSHMEM_workarounds = true;
    }
#else
    (void)dpy_; // warning prevention
#endif
    return 0;
}

bool video::init_window(int xsize, int ysize) {
    { //enclose local variables before fail label
        g_sizex = xsize;
        g_sizey = ysize;

        // Open the display
        if (!dpy) {
            dpy = XOpenDisplay(display_name);
            if (!dpy) {
                fprintf(stderr, "Can't open X11 display %s\n", XDisplayName(display_name));
                goto fail;
            }
        }
        int theScreen = DefaultScreen(dpy);
        scrn = ScreenOfDisplay(dpy, theScreen);
        dispdepth = DefaultDepth(dpy, theScreen);
        XVisualInfo vinfo;
        if (!((dispdepth >= 15 && dispdepth <= 32 &&
               XMatchVisualInfo(dpy, theScreen, dispdepth, TrueColor, &vinfo)) ||
              XMatchVisualInfo(dpy, theScreen, 24, TrueColor, &vinfo) ||
              XMatchVisualInfo(dpy, theScreen, 32, TrueColor, &vinfo) ||
              XMatchVisualInfo(dpy, theScreen, 16, TrueColor, &vinfo) ||
              XMatchVisualInfo(dpy, theScreen, 15, TrueColor, &vinfo))) {
            fprintf(stderr, "Display has no appropriate True Color visual\n");
            goto fail;
        }
        vis = vinfo.visual;
        depth = dispdepth = vinfo.depth;
        mask2bits(vinfo.red_mask, red_mask, red_shift);
        mask2bits(vinfo.green_mask, green_mask, green_shift);
        mask2bits(vinfo.blue_mask, blue_mask, blue_shift);
        rootW = RootWindow(dpy, theScreen);
        cmap = XCreateColormap(dpy, rootW, vis, AllocNone);
        XSetWindowAttributes attrs;
        attrs.backing_store = Always;
        attrs.colormap = cmap;
        attrs.event_mask = StructureNotifyMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask;
        attrs.background_pixel = BlackPixelOfScreen(scrn);
        attrs.border_pixel = WhitePixelOfScreen(scrn);
        win = XCreateWindow(dpy,
                            rootW,
                            0,
                            0,
                            xsize,
                            ysize,
                            2,
                            dispdepth,
                            InputOutput,
                            vis,
                            CWBackingStore | CWColormap | CWEventMask | CWBackPixel | CWBorderPixel,
                            &attrs);
        if (!win) {
            fprintf(stderr, "Can't create the window\n");
            goto fail;
        }
        XSizeHints sh;
        sh.flags = PSize | PMinSize | PMaxSize;
        sh.width = sh.min_width = sh.max_width = xsize;
        sh.height = sh.min_height = sh.max_height = ysize;
        XSetStandardProperties(dpy, win, g_video->title, g_video->title, None, nullptr, 0, &sh);
        _XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", false);
        XSetWMProtocols(dpy, win, &_XA_WM_DELETE_WINDOW, 1);
        gc = XCreateGC(dpy, win, 0L, &xgcv);
        XMapRaised(dpy, win);
        XFlush(dpy);
#ifdef X_FULLSYNC
        XSynchronize(dpy, true);
#endif
        XSetErrorHandler(xerr_handler);

        int imgbytes = xsize * ysize * (dispdepth <= 16 ? 2 : 4);
        const char *vidstr;
#ifndef X_NOSHMEM
        int major, minor, pixmaps;
        if (XShmQueryExtension(dpy) &&
            XShmQueryVersion(dpy, &major, &minor, &pixmaps)) { // Shared memory
            shmseginfo.shmid = shmget(IPC_PRIVATE, imgbytes, IPC_CREAT | 0777);
            if (shmseginfo.shmid < 0) {
                fprintf(stderr, "Warning: Can't get shared memory: %s\n", strerror(errno));
                goto generic;
            }
            g_pImg = (unsigned int *)(shmseginfo.shmaddr = (char *)shmat(shmseginfo.shmid, 0, 0));
            if (g_pImg == (unsigned int *)-1) {
                fprintf(stderr, "Warning: Can't attach to shared memory: %s\n", strerror(errno));
                shmctl(shmseginfo.shmid, IPC_RMID, nullptr);
                goto generic;
            }
            shmseginfo.readOnly = false;
            if (!XShmAttach(dpy, &shmseginfo) || x_error) {
                char err[256];
                XGetErrorText(dpy, x_error, err, 255);
                fprintf(stderr,
                        "Warning: Can't attach shared memory to display: %s (%d)\n",
                        err,
                        x_error);
                shmdt(shmseginfo.shmaddr);
                shmctl(shmseginfo.shmid, IPC_RMID, nullptr);
                goto generic;
            }
            already_called_X_ShmAttach = true;

#ifndef X_NOSHMPIX
            if (pixmaps && XShmPixmapFormat(dpy) == ZPixmap) { // Pixmaps
                vidtype = 2;
                vidstr = "X11 shared memory pixmap";
                pixmap = XShmCreatePixmap(
                    dpy, win, (char *)g_pImg, &shmseginfo, xsize, ysize, dispdepth);
                XSetWindowBackgroundPixmap(dpy, win, pixmap);
            }
            else
#endif //!X_NOSHMPIX
            { // Standard
                vidtype = 1;
                vidstr = "X11 shared memory";
                ximage =
                    XShmCreateImage(dpy, vis, dispdepth, ZPixmap, 0, &shmseginfo, xsize, ysize);
                if (!ximage) {
                    fprintf(stderr, "Can't create the shared image\n");
                    goto fail;
                }
                assert(ximage->bytes_per_line == xsize * (dispdepth <= 16 ? 2 : 4));
                ximage->data = shmseginfo.shmaddr;
            }
        }
        else
#endif
        {
#ifndef X_NOSHMEM
        generic:
#endif
            vidtype = 0;
            vidstr = "generic X11";
            g_pImg = new unsigned int[imgbytes / sizeof(int)];
            ximage = XCreateImage(dpy,
                                  vis,
                                  dispdepth,
                                  ZPixmap,
                                  0,
                                  (char *)g_pImg,
                                  xsize,
                                  ysize,
                                  32,
                                  imgbytes / ysize);
            if (!ximage) {
                fprintf(stderr, "Can't create the image\n");
                goto fail;
            }
        }
        if (ximage) {
            // Note: It may be more efficient to adopt the server's byte order
            //       and swap once per get_color() call instead of once per pixel.
            const uint32_t probe = 0x03020100;
            const bool big_endian = (((const char *)(&probe))[0] == 0x03);
            ximage->byte_order = big_endian ? MSBFirst : LSBFirst;
        }
        printf("Note: using %s with %s visual for %d-bit color depth\n",
               vidstr,
               vis == DefaultVisual(dpy, theScreen) ? "default" : "non-default",
               dispdepth);
        running = true;
        return true;
    } // end of enclosing local variables
fail:
    terminate();
    init_console();
    return false;
}

bool video::init_console() {
    if (!g_pImg && g_sizex && g_sizey) {
        dispdepth = 24;
        red_shift = 16;
        vidtype = 3; // fake video
        g_pImg = new unsigned int[g_sizex * g_sizey];
        running = true;
    }
    return true;
}

void video::terminate() {
    running = false;
    if (dpy) {
        vidtype = 3; // stop video
        if (threaded) {
            pthread_mutex_lock(&g_mutex);
            pthread_mutex_unlock(&g_mutex);
        }
        if (ximage) {
            XDestroyImage(ximage);
            ximage = 0;
            g_pImg = 0;
        } // it frees g_pImg for vidtype == 0
#ifndef X_NOSHMEM
        if (pixmap)
            XFreePixmap(dpy, pixmap);
        if (shmseginfo.shmaddr) {
            XShmDetach(dpy, &shmseginfo);
            shmdt(shmseginfo.shmaddr);
            g_pImg = 0;
        }
        if (shmseginfo.shmid >= 0)
            shmctl(shmseginfo.shmid, IPC_RMID, nullptr);
#endif
        if (gc)
            XFreeGC(dpy, gc);
        if (win)
            XDestroyWindow(dpy, win);
        XCloseDisplay(dpy);
        dpy = 0;
    }
    if (g_pImg) {
        delete[] g_pImg;
        g_pImg = 0;
    } // if was allocated for console mode
}

video::~video() {
    if (g_video)
        terminate();
    g_video = 0;
}

//! Do standard event loop
void video::main_loop() {
    struct timezone tz;
    gettimeofday(&g_time, &tz);
    on_process();
}

//! Check for pending events once
bool video::next_frame() {
    if (!running)
        return false;
    //! try acquire mutex if threaded code, returns on failure
    if (vidtype == 3 || threaded && pthread_mutex_trylock(&g_mutex))
        return running;
    //! Refresh screen picture
    g_fps++;
#ifndef X_NOSHMPIX
    if (vidtype == 2 && updating)
        XClearWindow(dpy, win);
#endif
    while (XPending(dpy)) {
        XEvent report;
        XNextEvent(dpy, &report);
        switch (report.type) {
            case ClientMessage:
                if (report.xclient.format != 32 || report.xclient.data.l[0] != _XA_WM_DELETE_WINDOW)
                    break;
            case DestroyNotify: running = false;
            case KeyPress: on_key(XLookupKeysym(&report.xkey, 0)); break;
            case ButtonPress:
                on_mouse(report.xbutton.x, report.xbutton.y, report.xbutton.button);
                break;
            case ButtonRelease:
                on_mouse(report.xbutton.x, report.xbutton.y, -report.xbutton.button);
                break;
        }
    }
    struct timezone tz;
    struct timeval now_time;
    gettimeofday(&now_time, &tz);
    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);
    if (sec > 1) {
        memcpy(&g_time, &now_time, sizeof(g_time));
        if (calc_fps) {
            double fps = g_fps;
            g_fps = 0;
            char buffer[256];
            snprintf(buffer,
                     256,
                     "%s%s: %d fps",
                     title,
                     updating ? "" : " (no updating)",
                     int(fps / sec));
            XStoreName(dpy, win, buffer);
        }
#ifndef X_FULLSYNC
        XSync(dpy, false); // It is often better then using XSynchronize(dpy, true)
#endif //X_FULLSYNC
    }
    if (threaded)
        pthread_mutex_unlock(&g_mutex);
    return true;
}

//! Change window title
void video::show_title() {
    if (vidtype < 3)
        XStoreName(dpy, win, title);
}

drawing_area::drawing_area(int x, int y, int sizex, int sizey)
        : base_index(y * g_sizex + x),
          max_index(g_sizex * g_sizey),
          index_stride(g_sizex),
          pixel_depth(dispdepth),
          ptr32(g_pImg),
          start_x(x),
          start_y(y),
          size_x(sizex),
          size_y(sizey) {
    assert(x < g_sizex);
    assert(y < g_sizey);
    assert(x + sizex <= g_sizex);
    assert(y + sizey <= g_sizey);

    index = base_index; // current index
}

void drawing_area::update() {
    if (!g_video->updating)
        return;
#ifndef X_NOSHMEM
    switch (vidtype) {
        case 0:
#endif
            pthread_mutex_lock(&g_mutex);
            if (vidtype == 0)
                XPutImage(dpy, win, gc, ximage, start_x, start_y, start_x, start_y, size_x, size_y);
            pthread_mutex_unlock(&g_mutex);
#ifndef X_NOSHMEM
            break;
        case 1:
            pthread_mutex_lock(&g_mutex);
            if (vidtype == 1)
                XShmPutImage(dpy,
                             win,
                             gc,
                             ximage,
                             start_x,
                             start_y,
                             start_x,
                             start_y,
                             size_x,
                             size_y,
                             false);
            pthread_mutex_unlock(&g_mutex);
            break;
            /*case 2: make it in next_frame(); break;*/
    }
#endif
}