Slightly smarter version of last change
[zxing.git] / javame / src / com / google / zxing / client / j2me / SnapshotThread.java
index b6c3e39..3777be9 100644 (file)
@@ -30,20 +30,21 @@ import javax.microedition.media.control.VideoControl;
 /**
  * Thread which does the work of capturing a frame and decoding it.
  *
- * @author Sean Owen (srowen@google.com)
+ * @author Sean Owen
  */
 final class SnapshotThread implements Runnable {
 
   private final ZXingMIDlet zXingMIDlet;
   private final Object waitLock;
-  private boolean done;
+  private volatile boolean done;
   private final MultimediaManager multimediaManager;
+  private String bestEncoding;
 
   SnapshotThread(ZXingMIDlet zXingMIDlet) {
     this.zXingMIDlet = zXingMIDlet;
     waitLock = new Object();
     done = false;
-    multimediaManager = new DefaultMultimediaManager();
+    multimediaManager = ZXingMIDlet.buildMultimediaManager();
   }
 
   void continueRun() {
@@ -91,10 +92,13 @@ final class SnapshotThread implements Runnable {
   }
 
   private byte[] takeSnapshot() throws MediaException {
+
+    String bestEncoding = guessBestEncoding();
+
     VideoControl videoControl = zXingMIDlet.getVideoControl();
     byte[] snapshot = null;
     try {
-      snapshot = videoControl.getSnapshot(null);
+      snapshot = videoControl.getSnapshot("".equals(bestEncoding) ? null : bestEncoding);
     } catch (MediaException me) {
     }
     if (snapshot == null) {
@@ -108,4 +112,29 @@ final class SnapshotThread implements Runnable {
     return snapshot;
   }
 
+  private synchronized String guessBestEncoding() throws MediaException {
+    if (bestEncoding == null) {
+      // Check this property, present on some Nokias?
+      String supportsVideoCapture = System.getProperty("supports.video.capture");
+      if ("false".equals(supportsVideoCapture)) {
+        throw new MediaException("supports.video.capture is false");
+      }
+
+      bestEncoding = "";
+      String videoSnapshotEncodings = System.getProperty("video.snapshot.encodings");
+      if (videoSnapshotEncodings != null) {
+        // We know explicitly what the camera supports; see if PNG is among them since
+        // Image.createImage() should always support it
+        int pngEncodingStart = videoSnapshotEncodings.indexOf("encoding=png");
+        if (pngEncodingStart >= 0) {
+          int space = videoSnapshotEncodings.indexOf(' ', pngEncodingStart);
+          bestEncoding = space >= 0 ?
+              videoSnapshotEncodings.substring(pngEncodingStart, space) :
+              videoSnapshotEncodings.substring(pngEncodingStart);
+        }
+      }
+    }
+    return bestEncoding;
+  }
+
 }