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