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