Only output bytes read when something's wrong
[kaka/cakelight.git] / src / kaka / cakelight / FrameGrabber.java
... / ...
CommitLineData
1package kaka.cakelight;
2
3import java.io.*;
4import java.util.Optional;
5
6import static kaka.cakelight.Main.log;
7
8public class FrameGrabber implements Closeable {
9 private Configuration config;
10 private File file;
11 private int bytesPerFrame;
12 private InputStream fileStream;
13
14 private FrameGrabber() {
15 }
16
17 public static FrameGrabber from(File videoDevice, Configuration config) {
18 FrameGrabber fg = new FrameGrabber();
19 fg.config = config;
20 fg.file = videoDevice;
21 fg.bytesPerFrame = config.video.width * config.video.height * config.video.bpp;
22 fg.prepare();
23 return fg;
24 }
25
26 private boolean prepare() {
27 try {
28 fileStream = new FileInputStream(file);
29 return true;
30 } catch (FileNotFoundException e) {
31 // TODO: handle java.io.FileNotFoundException: /dev/video1 (Permission denied)
32 e.printStackTrace();
33 return false;
34 }
35 }
36
37 /**
38 * Must be run in the same thread as {@link #prepare}.
39 */
40 public Optional<VideoFrame> grabFrame() {
41 try {
42 byte[] data = new byte[bytesPerFrame];
43 int count = fileStream.read(data);
44 if (count != bytesPerFrame) {
45 log("Expected to read " + bytesPerFrame + " bytes per frame but read " + count);
46 }
47 return Optional.of(VideoFrame.of(data, config));
48 } catch (IOException e) {
49 e.printStackTrace();
50 }
51
52 return Optional.empty();
53 }
54
55 @Override
56 public void close() throws IOException {
57 fileStream.close();
58 }
59}