File size: 20,659 Bytes
dffe123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

#include "precomp.hpp"

#include "window_framebuffer.hpp"

#include <opencv2/core/utils/configuration.private.hpp>
#include <opencv2/core/utils/logger.defines.hpp>
#ifdef NDEBUG
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG + 1
#else
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE + 1
#endif
#include <opencv2/core/utils/logger.hpp>

#include <unistd.h>
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <stdlib.h>
#include <linux/fb.h>
#include <linux/input.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include "opencv2/imgproc.hpp"

#ifdef HAVE_FRAMEBUFFER_XVFB
#include <X11/XWDFile.h>
#include <X11/X.h>

#define C32INT(ptr) ((((unsigned char*)ptr)[0] << 24) | (((unsigned char*)ptr)[1] << 16) | \
  (((unsigned char*)ptr)[2] << 8) | (((unsigned char*)ptr)[3] << 0))
#endif


namespace cv {
namespace highgui_backend {

std::shared_ptr<UIBackend> createUIBackendFramebuffer()
{
    return std::make_shared<FramebufferBackend>();
}

static std::string& getFBMode()
{
    static std::string fbModeOpenCV =
    cv::utils::getConfigurationParameterString("OPENCV_HIGHGUI_FB_MODE", "FB");
    return fbModeOpenCV;
}

static std::string& getFBFileName()
{
    static std::string fbFileNameFB =
    cv::utils::getConfigurationParameterString("FRAMEBUFFER", "/dev/fb0");
    static std::string fbFileNameOpenCV =
    cv::utils::getConfigurationParameterString("OPENCV_HIGHGUI_FB_DEVICE", "");

    if (!fbFileNameOpenCV.empty()) return fbFileNameOpenCV;
    return fbFileNameFB;
}

FramebufferWindow::FramebufferWindow(FramebufferBackend &_backend, int _flags):
    backend(_backend), flags(_flags)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::FramebufferWindow()");
    FB_ID = "FramebufferWindow";
    windowRect = Rect(0,0, backend.getFBWidth(), backend.getFBHeight());
}

FramebufferWindow::~FramebufferWindow()
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::~FramebufferWindow()");
}

void FramebufferWindow::imshow(InputArray image)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::imshow(InputArray image)");
    currentImg = image.getMat().clone();

    CV_LOG_INFO(NULL, "UI: InputArray image: "
    << cv::typeToString(image.type()) << " size " << image.size());

    if (currentImg.empty())
    {
        CV_LOG_WARNING(NULL, "UI: image is empty");
        return;
    }
    CV_CheckEQ(currentImg.dims, 2, "UI: dims != 2");

    Mat img = image.getMat();
    switch (img.channels())
    {
        case 1:
            {
                Mat tmp;
                switch(img.type())
                {
                    case CV_8U:
                        tmp = img;
                        break;
                    case CV_8S:
                        cv::convertScaleAbs(img, tmp, 1, 127);
                        break;
                    case CV_16S:
                        cv::convertScaleAbs(img, tmp, 1/255., 127);
                        break;
                    case CV_16U:
                        cv::convertScaleAbs(img, tmp, 1/255.);
                        break;
                    case CV_32F:
                    case CV_64F: // assuming image has values in range [0, 1)
                        img.convertTo(tmp, CV_8U, 255., 0.);
                        break;
                }
                Mat rgb(img.rows, img.cols, CV_8UC3);
                cvtColor(tmp, rgb, COLOR_GRAY2RGB);
                img = rgb;
            }
            break;
        case 3:
        case 4:
            {
                Mat tmp(img.rows, img.cols, CV_8UC3);
                convertToShow(img, tmp, true);
                img = tmp;
            }
            break;
        default:
            CV_Error(cv::Error::StsBadArg, "Bad image: wrong number of channels");
    }
    {
        Mat bgra(img.rows, img.cols, CV_8UC4);
        cvtColor(img, bgra, COLOR_RGB2BGRA, bgra.channels());
        img = bgra;
    }

    int newWidth = windowRect.width;
    int newHeight = windowRect.height;
    int cntChannel = img.channels();
    cv::Size imgSize = currentImg.size();

    if (flags & WINDOW_AUTOSIZE)
    {
        windowRect.width = imgSize.width;
        windowRect.height = imgSize.height;
        newWidth = windowRect.width;
        newHeight = windowRect.height;
    }

    if (flags & WINDOW_FREERATIO)
    {
        newWidth = windowRect.width;
        newHeight = windowRect.height;
    }
    else //WINDOW_KEEPRATIO
    {
        double aspect_ratio = ((double)img.cols) / img.rows;
        newWidth = windowRect.width;
        newHeight = (int)(windowRect.width / aspect_ratio);

        if (newHeight > windowRect.height)
        {
            newWidth = (int)(windowRect.height * aspect_ratio);
            newHeight = windowRect.height;
        }
    }

    if ((newWidth != img.cols) && (newHeight != img.rows))
    {
        Mat imResize;
        cv::resize(img, imResize, cv::Size(newWidth, newHeight), INTER_LINEAR);
        img = imResize;
    }

    CV_LOG_INFO(NULL, "UI: Formated image: "
    << cv::typeToString(img.type()) << " size " << img.size());

    if (backend.getMode() == FB_MODE_EMU)
    {
        CV_LOG_WARNING(NULL, "UI: FramebufferWindow::imshow is used in EMU mode");
        return;
    }

    if (backend.getFBPointer() == MAP_FAILED)
    {
        CV_LOG_ERROR(NULL, "UI: Framebuffer is not mapped");
        return;
    }

    int xOffset = backend.getFBXOffset();
    int yOffset = backend.getFBYOffset();
    int fbHeight = backend.getFBHeight();
    int fbWidth = backend.getFBWidth();
    int lineLength = backend.getFBLineLength();

    int img_start_x;
    int img_start_y;
    int img_end_x;
    int img_end_y;
    int fb_start_x;
    int fb_start_y;

    if (windowRect.y - yOffset < 0)
    {
        img_start_y = - (windowRect.y - yOffset);
    }
    else
    {
        img_start_y = 0;
    }
    if (windowRect.x - xOffset < 0)
    {
        img_start_x = - (windowRect.x - xOffset);
    }
    else
    {
        img_start_x = 0;
    }

    if (windowRect.y + yOffset + img.rows > fbHeight)
    {
        img_end_y = fbHeight - windowRect.y - yOffset;
    }
    else
    {
        img_end_y = img.rows;
    }
    if (windowRect.x + xOffset + img.cols > fbWidth)
    {
        img_end_x = fbWidth - windowRect.x - xOffset;
    }
    else
    {
        img_end_x = img.cols;
    }

    if (windowRect.y + yOffset >= 0)
    {
        fb_start_y = windowRect.y + yOffset;
    }
    else
    {
        fb_start_y = 0;
    }
    if (windowRect.x + xOffset >= 0)
    {
        fb_start_x = windowRect.x + xOffset;
    }
    else
    {
        fb_start_x = 0;
    }

    for (int y = img_start_y; y < img_end_y; y++)
    {
        std::memcpy(backend.getFBPointer() +
        (fb_start_y + y - img_start_y) * lineLength + fb_start_x * cntChannel,
        img.ptr<unsigned char>(y) + img_start_x * cntChannel,
        (img_end_x - img_start_x) * cntChannel);
    }
}

double FramebufferWindow::getProperty(int /*prop*/) const
{
    CV_LOG_WARNING(NULL, "UI: getProperty (not supported)");
    return 0.0;
}

bool FramebufferWindow::setProperty(int /*prop*/, double /*value*/)
{
    CV_LOG_WARNING(NULL, "UI: setProperty (not supported)");
    return false;
}

void FramebufferWindow::resize(int width, int height)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::resize(int width "
    << width <<", height " << height << ")");

    CV_Assert(width > 0);
    CV_Assert(height > 0);

    if (!(flags & WINDOW_AUTOSIZE))
    {
        windowRect.width = width;
        windowRect.height = height;

        if (!currentImg.empty())
        {
            imshow(currentImg);
        }
    }
}

void FramebufferWindow::move(int x, int y)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::move(int x " << x << ", y " << y <<")");

    windowRect.x = x;
    windowRect.y = y;

    if (!currentImg.empty())
    {
        imshow(currentImg);
    }
}

Rect FramebufferWindow::getImageRect() const
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::getImageRect()");
    return windowRect;
}

void FramebufferWindow::setTitle(const std::string& /*title*/)
{
    CV_LOG_WARNING(NULL, "UI: setTitle (not supported)");
}

void FramebufferWindow::setMouseCallback(MouseCallback /*onMouse*/, void* /*userdata*/)
{
    CV_LOG_WARNING(NULL, "UI: setMouseCallback (not supported)");
}

std::shared_ptr<UITrackbar> FramebufferWindow::createTrackbar(
        const std::string& /*name*/,
        int /*count*/,
        TrackbarCallback /*onChange*/,
        void* /*userdata*/)
{
    CV_LOG_WARNING(NULL, "UI: createTrackbar (not supported)");
    return nullptr;
}

std::shared_ptr<UITrackbar> FramebufferWindow::findTrackbar(const std::string& /*name*/)
{
    CV_LOG_WARNING(NULL, "UI: findTrackbar (not supported)");
    return nullptr;
}

const std::string& FramebufferWindow::getID() const
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::getID()");
    return FB_ID;
}

bool FramebufferWindow::isActive() const
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::isActive()");
    return true;
}

void FramebufferWindow::destroy()
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::destroy()");
}

int FramebufferBackend::fbOpenAndGetInfo()
{
    std::string fbFileName = getFBFileName();
    CV_LOG_INFO(NULL, "UI: FramebufferWindow::The following is used as a framebuffer file: \n"
    << fbFileName);

    int fb_fd = open(fbFileName.c_str(), O_RDWR);
    if (fb_fd == -1)
    {
        CV_LOG_ERROR(NULL, "UI: can't open framebuffer");
        return -1;
    }

    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &fixInfo))
    {
        CV_LOG_ERROR(NULL, "UI: can't read fix info for framebuffer");
        return -1;
    }

    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &varInfo))
    {
        CV_LOG_ERROR(NULL, "UI: can't read var info for framebuffer");
        return -1;
    }

    CV_LOG_INFO(NULL, "UI: framebuffer info: \n"
    << "   red offset  " << varInfo.red.offset << " length " << varInfo.red.length << "\n"
    << " green offset  " << varInfo.green.offset << " length " << varInfo.green.length << "\n"
    << "  blue offset  " << varInfo.blue.offset << " length " << varInfo.blue.length << "\n"
    << "transp offset  " << varInfo.transp.offset << " length " <<varInfo.transp.length << "\n"
    << "bits_per_pixel " << varInfo.bits_per_pixel);

    if ((varInfo.red.offset != 16) && (varInfo.red.length != 8) &&
        (varInfo.green.offset != 8) && (varInfo.green.length != 8) &&
        (varInfo.blue.offset != 0) && (varInfo.blue.length != 8) &&
        (varInfo.bits_per_pixel != 32) )
    {
        close(fb_fd);
        CV_LOG_ERROR(NULL, "UI: Framebuffer format is not supported "
        << "(use BGRA format with bits_per_pixel = 32)");
        return -1;
    }

    fbWidth = varInfo.xres;
    fbHeight = varInfo.yres;
    fbXOffset = varInfo.xoffset;
    fbYOffset = varInfo.yoffset;
    fbBitsPerPixel = varInfo.bits_per_pixel;
    fbLineLength = fixInfo.line_length;

    fbScreenSize = max(varInfo.xres, varInfo.xres_virtual) *
    max(varInfo.yres, varInfo.yres_virtual) *
    fbBitsPerPixel / 8;

    fbPointer = (unsigned char*)
    mmap(0, fbScreenSize, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd, 0);

    if (fbPointer == MAP_FAILED)
    {
        CV_LOG_ERROR(NULL, "UI: can't mmap framebuffer");
        return -1;
    }

    return fb_fd;
}

int FramebufferBackend::XvfbOpenAndGetInfo()
{
    int fb_fd = -1;

#ifdef HAVE_FRAMEBUFFER_XVFB
    std::string fbFileName = getFBFileName();
    CV_LOG_INFO(NULL, "UI: FramebufferWindow::The following is used as a framebuffer file: \n"
    << fbFileName);

    fb_fd = open(fbFileName.c_str(), O_RDWR);
    if (fb_fd == -1)
    {
        CV_LOG_ERROR(NULL, "UI: can't open framebuffer");
        return -1;
    }

    XWDFileHeader *xwd_header;

    xwd_header = (XWDFileHeader*)
    mmap(NULL, sizeof(XWDFileHeader), PROT_READ, MAP_SHARED, fb_fd, 0);

    if (xwd_header == MAP_FAILED)
    {
        CV_LOG_ERROR(NULL, "UI: can't mmap xwd header");
        return -1;
    }

    if (C32INT(&(xwd_header->pixmap_format)) != ZPixmap)
    {
        CV_LOG_ERROR(NULL, "Unsupported pixmap format: " << xwd_header->pixmap_format);
        return -1;
    }

    if (xwd_header->xoffset != 0)
    {
        CV_LOG_ERROR(NULL, "UI: Unsupported xoffset value: " << xwd_header->xoffset );
        return -1;
    }

    unsigned int r = C32INT(&(xwd_header->red_mask));
    unsigned int g = C32INT(&(xwd_header->green_mask));
    unsigned int b = C32INT(&(xwd_header->blue_mask));

    fbWidth = C32INT(&(xwd_header->pixmap_width));
    fbHeight = C32INT(&(xwd_header->pixmap_height));
    fbXOffset = 0;
    fbYOffset = 0;
    fbLineLength = C32INT(&(xwd_header->bytes_per_line));
    fbBitsPerPixel = C32INT(&(xwd_header->bits_per_pixel));

    CV_LOG_INFO(NULL, "UI: XVFB info: \n"
    << "   red_mask " << r << "\n"
    << " green_mask " << g << "\n"
    << "  blue_mask " << b << "\n"
    << "bits_per_pixel " << fbBitsPerPixel);

    if ((r != 16711680 ) && (g != 65280 ) && (b != 255 ) &&
        (fbBitsPerPixel != 32))
    {
        CV_LOG_ERROR(NULL, "UI: Framebuffer format is not supported "
        << "(use BGRA format with bits_per_pixel = 32)");
        return -1;
    }

    xvfb_len_header = C32INT(&(xwd_header->header_size));
    xvfb_len_colors = sizeof(XWDColor) * C32INT(&(xwd_header->ncolors));
    xvfb_len_pixmap = C32INT(&(xwd_header->bytes_per_line)) *
    C32INT(&(xwd_header->pixmap_height));

    munmap(xwd_header, sizeof(XWDFileHeader));

    fbScreenSize = xvfb_len_header + xvfb_len_colors + xvfb_len_pixmap;
    xwd_header = (XWDFileHeader*)
    mmap(NULL, fbScreenSize, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd, 0);

    fbPointer = (unsigned char*)xwd_header;
    fbPointer_dist = xvfb_len_header + xvfb_len_colors;

#else
    CV_LOG_WARNING(NULL, "UI: To use virtual framebuffer, "
    << "compile OpenCV with the WITH_FRAMEBUFFER_XVFB=ON");
#endif

    return fb_fd;
}

fb_var_screeninfo &FramebufferBackend::getVarInfo()
{
    return varInfo;
}

fb_fix_screeninfo &FramebufferBackend::getFixInfo()
{
    return fixInfo;
}

int FramebufferBackend::getFramebuffrerID()
{
    return fbID;
}

int FramebufferBackend::getFBWidth()
{
    return fbWidth;
}

int FramebufferBackend::getFBHeight()
{
    return fbHeight;
}

int FramebufferBackend::getFBXOffset()
{
    return fbXOffset;
}

int FramebufferBackend::getFBYOffset()
{
    return fbYOffset;
}

int FramebufferBackend::getFBBitsPerPixel()
{
    return fbBitsPerPixel;
}

int FramebufferBackend::getFBLineLength()
{
    return fbLineLength;
}

unsigned char* FramebufferBackend::getFBPointer()
{
    return fbPointer + fbPointer_dist;
}

Mat& FramebufferBackend::getBackgroundBuff()
{
    return backgroundBuff;
}

OpenCVFBMode FramebufferBackend::getMode()
{
    return mode;
}

FramebufferBackend::FramebufferBackend():mode(FB_MODE_FB), fbPointer_dist(0)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferWindow::FramebufferBackend()");

    std::string fbModeStr = getFBMode();

    if (fbModeStr == "EMU")
    {
        mode = FB_MODE_EMU;
        CV_LOG_WARNING(NULL, "UI: FramebufferWindow is trying to use EMU mode");
    }
    if (fbModeStr == "FB")
    {
        mode = FB_MODE_FB;
        CV_LOG_WARNING(NULL, "UI: FramebufferWindow is trying to use FB mode");
    }
    if (fbModeStr == "XVFB")
    {
        mode = FB_MODE_XVFB;
        CV_LOG_WARNING(NULL, "UI: FramebufferWindow is trying to use XVFB mode");
    }

    fbID = -1;
    if (mode == FB_MODE_FB)
    {
        fbID = fbOpenAndGetInfo();
    }
    if (mode == FB_MODE_XVFB)
    {
        fbID = XvfbOpenAndGetInfo();
    }

    CV_LOG_INFO(NULL, "UI: FramebufferWindow::fbID " << fbID);

    if (fbID == -1)
    {
        mode = FB_MODE_EMU;
        fbWidth = 640;
        fbHeight = 480;
        fbXOffset = 0;
        fbYOffset = 0;
        fbBitsPerPixel = 0;
        fbLineLength = 0;

        CV_LOG_WARNING(NULL, "UI: FramebufferWindow is used in EMU mode");
        return;
    }

    CV_LOG_INFO(NULL, "UI: Framebuffer's width, height, bits per pix: "
    << fbWidth << " " << fbHeight << " " << fbBitsPerPixel);

    CV_LOG_INFO(NULL, "UI: Framebuffer's offsets (x, y), line length: "
    << fbXOffset << " " << fbYOffset << " " << fbLineLength);

    backgroundBuff = Mat(fbHeight, fbWidth, CV_8UC4);
    int cntChannel = 4;
    for (int y = fbYOffset; y < backgroundBuff.rows + fbYOffset; y++)
    {
        std::memcpy(backgroundBuff.ptr<unsigned char>(y - fbYOffset),
        getFBPointer() + y * fbLineLength + fbXOffset * cntChannel,
        backgroundBuff.cols * cntChannel);
    }
}

FramebufferBackend::~FramebufferBackend()
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferBackend::~FramebufferBackend()");
    if(fbID == -1) return;

    if (fbPointer != MAP_FAILED)
    {
        int cntChannel = 4;
        for (int y = fbYOffset; y < backgroundBuff.rows + fbYOffset; y++)
        {
            std::memcpy(getFBPointer() + y * fbLineLength + fbXOffset * cntChannel,
            backgroundBuff.ptr<cv::Vec4b>(y - fbYOffset),
            backgroundBuff.cols * cntChannel);
        }

        munmap(fbPointer, fbScreenSize);
    }
    close(fbID);
}

void FramebufferBackend::destroyAllWindows() {
    CV_LOG_DEBUG(NULL, "UI: FramebufferBackend::destroyAllWindows()");
}

// namedWindow
std::shared_ptr<UIWindow> FramebufferBackend::createWindow(
    const std::string& winname,
    int flags)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferBackend::createWindow("
    << winname << ", " << flags << ")");
    return std::make_shared<FramebufferWindow>(*this, flags);
}

void FramebufferBackend::initTermios(int echo, int wait)
{
    tcgetattr(0, &old);
    current = old;
    current.c_lflag &= ~ICANON;
    current.c_lflag &= ~ISIG;
    current.c_cc[VMIN] = wait;
    if (echo)
    {
        current.c_lflag |= ECHO;
    }
    else
    {
        current.c_lflag &= ~ECHO;
    }
    tcsetattr(0, TCSANOW, &current);
}

void FramebufferBackend::resetTermios(void)
{
    tcsetattr(0, TCSANOW, &old);
}

int FramebufferBackend::getch_(int echo, int wait)
{
    int ch;
    initTermios(echo, wait);
    ch = getchar();
    if (ch < 0)
    {
        rewind(stdin);
    }
    resetTermios();
    return ch;
}

bool FramebufferBackend::kbhit()
{
    int byteswaiting = 0;
    initTermios(0, 1);
    if (ioctl(0, FIONREAD, &byteswaiting) < 0)
    {
        CV_LOG_ERROR(NULL, "UI: Framebuffer ERR byteswaiting" );
    }
    resetTermios();

    return byteswaiting > 0;
}

int FramebufferBackend::waitKeyEx(int delay)
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferBackend::waitKeyEx(int delay = " << delay << ")");

    int code = -1;

    if (delay <= 0)
    {
        int ch = getch_(0, 1);
        CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = " << (int)ch);
        code = ch;

        while ((ch = getch_(0, 0)) >= 0)
        {
            CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = "
            << (int)ch << " (additional code on <stdin>)");
            code = ch;
        }
    }
    else
    {
        bool f_kbhit = false;
        while (!(f_kbhit = kbhit()) && (delay > 0))
        {
            delay -= 1;
            usleep(1000);
        }
        if (f_kbhit)
        {
            CV_LOG_INFO(NULL, "UI: FramebufferBackend kbhit is True ");

            int ch = getch_(0, 1);
            CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = " << (int)ch);
            code = ch;

            while ((ch = getch_(0, 0)) >= 0)
            {
                CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = "
                << (int)ch << " (additional code on <stdin>)");
                code = ch;
            }
        }
    }

    CV_LOG_INFO(NULL, "UI: FramebufferBackend::waitKeyEx() result code = " << code);
    return code;
}

int FramebufferBackend::pollKey()
{
    CV_LOG_DEBUG(NULL, "UI: FramebufferBackend::pollKey()");
    int code = -1;
    bool f_kbhit = false;
    f_kbhit = kbhit();

    if (f_kbhit)
    {
        CV_LOG_INFO(NULL, "UI: FramebufferBackend kbhit is True ");

        int ch = getch_(0, 1);
        CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = " << (int)ch);
        code = ch;

        while ((ch = getch_(0, 0)) >= 0)
        {
            CV_LOG_INFO(NULL, "UI: FramebufferBackend::getch_() take value = "
            << (int)ch << " (additional code on <stdin>)");
            code = ch;
        }
    }

    return code;
}

const std::string FramebufferBackend::getName() const
{
    return "FB";
}

}} // cv::highgui_backend::