Move all modes to package kaka.cakelight.mode
[kaka/cakelight.git] / src / kaka / cakelight / mode / VideoMode.java
CommitLineData
67b0a758
TW
1package kaka.cakelight.mode;
2
3import kaka.cakelight.Configuration;
4import kaka.cakelight.FrameGrabber;
5import kaka.cakelight.VideoDeviceListener;
6import kaka.cakelight.VideoFrame;
4a2d6056 7
03670958 8import java.io.File;
4a2d6056
TW
9import java.io.IOException;
10import java.util.Optional;
100b82fe 11import java.util.function.Consumer;
4a2d6056 12
d182b8cc 13public class VideoMode extends Mode {
4a2d6056 14 private Configuration config;
8418fbda 15 private Thread grabberThread;
adc29b9a 16 private Consumer<VideoFrame> frameConsumer;
03670958
TW
17 private VideoDeviceListener deviceListener;
18
19 public VideoMode() {
20 deviceListener = new VideoDeviceListener();
d182b8cc 21 deviceListener.onVideoDeviceChange(this::onVideoDeviceChange);
03670958 22 }
4a2d6056
TW
23
24 @Override
25 public void enter(Configuration config) {
26 this.config = config;
03670958 27 deviceListener.startListening();
4a2d6056
TW
28 }
29
30 @Override
31 public void exit() {
8418fbda 32 grabberThread.interrupt();
03670958 33 deviceListener.stopListening();
4a2d6056
TW
34 }
35
03670958 36 private void startGrabberThread(File videoDevice) {
100b82fe 37 assert frameConsumer != null;
8418fbda 38 grabberThread = new Thread() {
4a2d6056 39 public void run() {
03670958 40 try (FrameGrabber grabber = FrameGrabber.from(videoDevice, config)) {
4a2d6056 41 while (!isInterrupted()) {
adc29b9a 42 Optional<VideoFrame> frame = grabber.grabFrame();
03b67a73 43 if (frameConsumer != null) frame.ifPresent(frameConsumer);
adc29b9a 44 frame.ifPresent(VideoMode.this::onVideoFrame);
100b82fe 45// timeIt("frame", grabber::grabFrame);
4a2d6056
TW
46 }
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50 }
51 };
8418fbda 52 grabberThread.start();
4a2d6056 53 }
100b82fe 54
adc29b9a 55 public void onVideoFrame(Consumer<VideoFrame> consumer) {
100b82fe
TW
56 frameConsumer = consumer;
57 }
03670958 58
adc29b9a 59 private void onVideoFrame(VideoFrame frame) {
6b569670 60 updateWithFrame(frame.getLedFrame());
03b67a73
TW
61 }
62
d182b8cc 63 public void onVideoDeviceChange(Optional<File> videoDevice) {
03670958 64 // Should only happen when this mode is active!
8418fbda
TW
65 if (grabberThread != null) {
66 grabberThread.interrupt();
03670958
TW
67 }
68 videoDevice.ifPresent(this::startGrabberThread);
69 }
4a2d6056 70}