summaryrefslogtreecommitdiffhomepage
path: root/video/video-widget.cpp
blob: fb380fc409cc0ec17e60a1f43cab2c39e091c5f0 (plain)
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
#include "video-widget.hpp"

#include "compat/check-visible.hpp"
#include "compat/math.hpp"

#include <cstddef>
#include <cstring>

#include <QPainter>

void video_widget::init_image_nolock()
{
    texture = QImage(W, H, QImage::Format_ARGB32);
    texture.setDevicePixelRatio(devicePixelRatioF());
}

video_widget::video_widget(QWidget* parent) : QWidget(parent)
{
    W = width(); H = height();
    init_image_nolock(); texture.fill(Qt::gray);

    connect(&timer, &QTimer::timeout, this, &video_widget::update_and_repaint, Qt::DirectConnection);
    timer.start(65);
}

void video_widget::update_image(const QImage& img)
{
    if (freshp.load(std::memory_order_relaxed))
        return;

    QMutexLocker l(&mtx);

    unsigned nbytes = (unsigned)(img.bytesPerLine() * img.height());
    vec.resize(nbytes); vec.shrink_to_fit();
    std::memcpy(vec.data(), img.constBits(), nbytes);

    texture = QImage((const unsigned char*) vec.data(), img.width(), img.height(), img.bytesPerLine(), img.format());
    texture.setDevicePixelRatio(devicePixelRatioF());

    freshp.store(true, std::memory_order_relaxed);
}

void video_widget::paintEvent(QPaintEvent*)
{
    QMutexLocker foo(&mtx);

    QPainter painter(this);
    painter.drawImage(rect(), texture);
}

void video_widget::update_and_repaint()
{
    if (!freshp.load(std::memory_order_relaxed))
        return;

    if (!check_is_visible())
        return;

    QMutexLocker l(&mtx);
    repaint();
    freshp.store(false, std::memory_order_relaxed);
}

void video_widget::resizeEvent(QResizeEvent*)
{
    QMutexLocker l(&mtx);
    double dpr = devicePixelRatioF();
    W = iround(width() * dpr);
    H = iround(height() * dpr);
    init_image_nolock();
}

void video_widget::get_preview_size(int& w, int& h)
{
    QMutexLocker l(&mtx);
    w = W; h = H;
}