WIP
[kaka/cakelight.git] / src / kaka / cakelight / FrameGrabber.java
index d228b7b..8fbb16f 100644 (file)
@@ -1,8 +1,11 @@
 package kaka.cakelight;
 
 import java.io.*;
+import java.util.Optional;
 
-public class FrameGrabber {
+import static kaka.cakelight.Main.log;
+
+public class FrameGrabber implements Closeable {
     private Configuration config;
     private File file;
     private int bytesPerFrame;
@@ -16,10 +19,11 @@ public class FrameGrabber {
         fg.config = config;
         fg.file = new File(config.video.device);
         fg.bytesPerFrame = config.video.width * config.video.height * config.video.bpp;
+        fg.prepare();
         return fg;
     }
 
-    public boolean prepare() {
+    private boolean prepare() {
         try {
             fileStream = new FileInputStream(file);
             return true;
@@ -29,24 +33,24 @@ public class FrameGrabber {
         }
     }
 
-    public Frame grabFrame() {
+    /**
+     * Must be run in the same thread as {@link #prepare}.
+     */
+    public Optional<Frame> grabFrame() {
         try {
             byte[] data = new byte[bytesPerFrame];
             int count = fileStream.read(data);
-            System.out.println("count = " + count);
-            return Frame.of(data, config);
+            log("# of bytes read = " + count);
+            return Optional.of(Frame.of(data, config));
         } catch (IOException e) {
             e.printStackTrace();
         }
 
-        return null;
+        return Optional.empty();
     }
 
-    public void close() {
-        try {
-            fileStream.close();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
+    @Override
+    public void close() throws IOException {
+        fileStream.close();
     }
 }