Commit | Line | Data |
---|---|---|
e59e98fc TW |
1 | package kaka.cakelight; |
2 | ||
3 | import java.io.*; | |
4a2d6056 | 4 | import java.util.Optional; |
e59e98fc | 5 | |
4a2d6056 TW |
6 | import static kaka.cakelight.Main.log; |
7 | ||
8 | public 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) { | |
b72a3fc5 | 31 | // TODO: handle java.io.FileNotFoundException: /dev/video1 (Permission denied) |
e59e98fc TW |
32 | e.printStackTrace(); |
33 | return false; | |
34 | } | |
35 | } | |
36 | ||
4a2d6056 TW |
37 | /** |
38 | * Must be run in the same thread as {@link #prepare}. | |
39 | */ | |
adc29b9a | 40 | public Optional<VideoFrame> grabFrame() { |
e59e98fc TW |
41 | try { |
42 | byte[] data = new byte[bytesPerFrame]; | |
43 | int count = fileStream.read(data); | |
48d4699c TW |
44 | if (count != bytesPerFrame) { |
45 | log("Expected to read " + bytesPerFrame + " bytes per frame but read " + count); | |
46 | } | |
adc29b9a | 47 | return Optional.of(VideoFrame.of(data, config)); |
e59e98fc TW |
48 | } catch (IOException e) { |
49 | e.printStackTrace(); | |
50 | } | |
51 | ||
4a2d6056 | 52 | return Optional.empty(); |
e59e98fc TW |
53 | } |
54 | ||
4a2d6056 TW |
55 | @Override |
56 | public void close() throws IOException { | |
57 | fileStream.close(); | |
e59e98fc TW |
58 | } |
59 | } |