1db5c2c7611cc18f25a84e6506564efd66204b7d
[kaka/cakelight.git] / src / kaka / cakelight / FrameGrabber.java
1 package kaka.cakelight;
2
3 import java.io.*;
4 import java.util.Optional;
5
6 import static kaka.cakelight.Main.log;
7
8 public class FrameGrabber implements Closeable {
9     private Configuration config;
10     private File file;
11     private int bytesPerFrame;
12     private InputStream fileStream;
13
14     private FrameGrabber() {
15     }
16
17     public static FrameGrabber from(File videoDevice, Configuration config) {
18         FrameGrabber fg = new FrameGrabber();
19         fg.config = config;
20         fg.file = videoDevice;
21         fg.bytesPerFrame = config.video.width * config.video.height * config.video.bpp;
22         fg.prepare();
23         return fg;
24     }
25
26     private boolean prepare() {
27         try {
28             fileStream = new FileInputStream(file);
29             return true;
30         } catch (FileNotFoundException e) {
31             // TODO: handle java.io.FileNotFoundException: /dev/video1 (Permission denied)
32             e.printStackTrace();
33             return false;
34         }
35     }
36
37     /**
38      * Must be run in the same thread as {@link #prepare}.
39      */
40     public Optional<VideoFrame> grabFrame() {
41         try {
42             byte[] data = new byte[bytesPerFrame];
43             int count = fileStream.read(data);
44             log("# of bytes read = " + count);
45             return Optional.of(VideoFrame.of(data, config));
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49
50         return Optional.empty();
51     }
52
53     @Override
54     public void close() throws IOException {
55         fileStream.close();
56     }
57 }