Renamed a thread
[kaka/cakelight.git] / src / kaka / cakelight / VideoMode.java
index 53cf09b..1f6d68f 100644 (file)
@@ -1,49 +1,65 @@
 package kaka.cakelight;
 
+import java.io.File;
 import java.io.IOException;
 import java.util.Optional;
 import java.util.function.Consumer;
 
-import static kaka.cakelight.Main.log;
-import static kaka.cakelight.Main.timeIt;
-
-public class VideoMode implements Mode {
+public class VideoMode extends Mode {
     private Configuration config;
-    private Thread thread;
+    private Thread grabberThread;
     private Consumer<Frame> frameConsumer;
+    private VideoDeviceListener deviceListener;
+
+    public VideoMode() {
+        deviceListener = new VideoDeviceListener();
+        deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
+    }
 
     @Override
     public void enter(Configuration config) {
         this.config = config;
-        startGrabberThread();
+        deviceListener.startListening();
     }
 
     @Override
     public void exit() {
-        thread.interrupt();
+        grabberThread.interrupt();
+        deviceListener.stopListening();
     }
 
-    private void startGrabberThread() {
+    private void startGrabberThread(File videoDevice) {
         assert frameConsumer != null;
-        thread = new Thread() {
+        grabberThread = new Thread() {
             public void run() {
-                try (FrameGrabber grabber = FrameGrabber.from(config)) {
+                try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
                     while (!isInterrupted()) {
-//                        Optional<Frame> frame = grabber.grabFrame();
-                        grabber.grabFrame().ifPresent(frameConsumer);
+                        Optional<Frame> frame = grabber.grabFrame();
+                        if (frameConsumer != null) frame.ifPresent(frameConsumer);
+                        frame.ifPresent(VideoMode.this::onFrame);
 //                        timeIt("frame", grabber::grabFrame);
-                        // TODO: process frame
-                        // TODO: save where the LedController can access it
                     }
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         };
-        thread.start();
+        grabberThread.start();
     }
 
-    public void onFrame(Consumer<Frame> consumer) {
+    public void onVideoFrame(Consumer<Frame> consumer) {
         frameConsumer = consumer;
     }
+
+    private void onFrame(Frame frame) {
+        updateWithFrame(frame.getLedFrame());
+    }
+
+    public void onVideoDeviceChange(Optional<File> videoDevice) {
+        // Should only happen when this mode is active!
+        if (grabberThread != null) {
+            grabberThread.interrupt();
+        }
+        videoDevice.ifPresent(this::startGrabberThread);
+    }
 }