summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: ab54508b128569e902b6540a8f7a8464ecaa801f (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
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
#![allow(unused)]

use anyhow::{anyhow, Result};
use std::sync::{Arc, Mutex};
use std::future::poll_fn;
use std::task::{Context, Poll, Waker};
use std::thread;

use gtk4::{self as gtk, glib, cairo};
use gtk4::prelude::*;
use glib::{clone, spawn_future_local};

use sshcamera::v4l2::{Device as V4l2, Field};
use sshcamera::color::yuv2rgb;
use jpeg_decoder::{self as jpeg, Decoder as JpegDec};

struct SignalChannel{
    waker: Option<Waker>,
    active: bool,
}
impl SignalChannel{
    fn new() -> Self{
        Self{
            waker: None,
            active: false,
        }
    }
    fn wake(&mut self){
        self.active = true;
        if let Some(w) = self.waker.take(){
            w.wake();
        }
    }
    fn poll(this: &Arc<Mutex<Self>>, ctx: &mut Context<'_>) -> Poll<()>{
        let mut l = this.lock().unwrap();
        if l.active{
            l.active = false;
            Poll::Ready(())
        }else{
            l.waker = Some(ctx.waker().clone());
            Poll::Pending
        }
    }
}

#[derive(Clone)]
struct AppState{
    frame_buf: Arc<Mutex<Option<cairo::ImageSurfaceDataOwned>>>,
    notify: Arc<Mutex<SignalChannel>>,
    fbpool: Arc<Mutex<Vec<cairo::ImageSurfaceDataOwned>>>,
}

fn videothread(apps: AppState) -> Result<()>{
    let v = V4l2::open("/dev/video0")?;

    // TODO: It should be better.
    let c = v.captstream_builder()?
        .set_pixelformat("MJPG".into())
        //.set_pixelformat("YUYV".into())
        .set_field(Field::None)
        .build()?;
    assert!(["YUYV", "MJPG"].contains(&c.pixelformat().as_str()));
    assert!(c.field() == Field::None);

    let (w, h) = (c.width(), c.height());
    let s = c.bytesperline();
    loop{
        let img: Result<cairo::ImageSurface> = c.next(|frame, _|{
            let mut img = None;
            let mut fbpool = apps.fbpool.lock().unwrap();
            while let Some(i) = fbpool.pop(){
                let i = i.into_inner();
                if i.width() as usize == w && i.height() as usize == h{
                    img = Some(i);
                    break;
                }
            }
            drop(fbpool);
            let mut img = match img{
                Some(i) => i,
                None    => {
                    cairo::ImageSurface::create(
                        cairo::Format::Rgb24,
                        w.try_into()?, h.try_into()?)?
                },
            };
            let stride: usize = img.stride().try_into()?;
            let mut imgslice = img.data()?;
            match c.pixelformat().as_str(){
                "YUYV" => {
                    for (x, y) in (0..h).map(
                            |y| (0..w).map(move |x|(x, y))).flatten(){
                        let p = s*y + x*2;
                        let (r, g, b) = yuv2rgb(
                            frame[p], frame[p/4*4 + 1], frame[p/4*4 + 3]);
                        imgslice[stride*y + x*4 + 0] = b;
                        imgslice[stride*y + x*4 + 1] = g;
                        imgslice[stride*y + x*4 + 2] = r;
                        imgslice[stride*y + x*4 + 3] = 0;
                    }
                    drop(imgslice);
                    Ok(img)
                },
                "MJPG" => {
                    // Jpeg is not placed in start of slice in some situation.
                    // It is even possible that there are no Jpeg data.
                    let jindex = (0..frame.len()-1)
                        .filter(|i| frame[*i] == 0xff && frame[i+1] == 0xd8)
                        .next()
                        .ok_or(anyhow!("jpeg not found"))?;

                    let mut jpeg = JpegDec::new(&frame[jindex..]);
                    let b = jpeg.decode()?;
                    let info = jpeg.info().unwrap();

                    assert!((info.width as usize, info.height as usize)
                        == (w, h));
                    for (x, y) in (0..h).map(
                            |y| (0..w).map(move |x|(x, y))).flatten(){
                        imgslice[stride*y + x*4 + 0] = b[(y*w+x)*3 + 2];
                        imgslice[stride*y + x*4 + 1] = b[(y*w+x)*3 + 1];
                        imgslice[stride*y + x*4 + 2] = b[(y*w+x)*3 + 0];
                        imgslice[stride*y + x*4 + 3] = 0;
                    }

                    drop(imgslice);
                    Ok(img)
                },
                _ => unreachable!(),
            }
        }).unwrap_or_else(|e| Err(e.into()));

        match img{
            Ok(img) => {
                *apps.frame_buf.lock().unwrap() = Some(img.take_data().unwrap());
                apps.notify.lock().unwrap().wake();
            },
            Err(err) => {
                println!("Skipping erroneous frame: {:?}", err);
            },
        }
    }
}

fn gtkmain(app: &gtk::Application){
    let apps = AppState{
        frame_buf: Arc::new(Mutex::new(None)),
        notify: Arc::new(Mutex::new(SignalChannel::new())),
        fbpool: Arc::new(Mutex::new(Vec::new())),
    };

    thread::spawn(clone!{
        #[strong] apps,
        move || videothread(apps).unwrap()
    });

    let draw = gtk::DrawingArea::new();
    let mut frame_cache: Option<cairo::ImageSurface> = None;
    draw.set_draw_func(clone!{
        #[strong(rename_to=frame_buf)] apps.frame_buf,
        #[strong(rename_to=fbpool)] apps.fbpool,
        move |_draw, ctx, canvas_w, canvas_h|{
            ctx.set_source_rgb(0., 0., 0.);
            ctx.paint().unwrap();

            if let Some(newfb) = frame_buf.lock().unwrap().take(){
                if let Some(mut lastframe) = frame_cache.take(){
                    let mut fbpool = fbpool.lock().unwrap();
                    if fbpool.len() < 8{
                        fbpool.push(lastframe.take_data().unwrap());
                    }
                }
                frame_cache = Some(newfb.into_inner());
            }
            if let Some(image) = frame_cache.clone(){
                let ipat = cairo::SurfacePattern::create(&image);
                let scale = ((canvas_w as f64) / (image.width() as f64)).min(
                    (canvas_h as f64) / (image.height() as f64));
                ctx.scale(scale, scale);
                ctx.set_source(&ipat).unwrap();
                ctx.paint().unwrap();
            }
        }
    });
    spawn_future_local(poll_fn(clone!{
        #[strong(rename_to=notify)] apps.notify,
        #[strong] draw,
        move |ctx|{
            loop{
                match SignalChannel::poll(&notify, ctx){
                    Poll::Ready(_) => {
                        draw.queue_draw();
                    },
                    pending => return pending,
                }
            }
        }
    }));

    let win = gtk::ApplicationWindow::builder()
        .application(app)
        .child(&draw)
        .build();
    win.present();
}

fn main() -> Result<glib::ExitCode>{
    let app = gtk::Application::builder()
        .build();
    app.connect_activate(gtkmain);
    Ok(app.run())
}