2 * Copyright 2007 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.j2me;
19 import com.google.zxing.MonochromeBitmapSource;
20 import com.google.zxing.MultiFormatReader;
21 import com.google.zxing.Reader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
25 import javax.microedition.lcdui.Image;
26 import javax.microedition.media.MediaException;
27 import javax.microedition.media.Player;
28 import javax.microedition.media.control.VideoControl;
31 * Thread which does the work of capturing a frame and decoding it.
33 * @author Sean Owen (srowen@google.com)
35 final class SnapshotThread implements Runnable {
37 private final ZXingMIDlet zXingMIDlet;
38 private final Object waitLock;
39 private volatile boolean done;
40 private final MultimediaManager multimediaManager;
42 SnapshotThread(ZXingMIDlet zXingMIDlet) {
43 this.zXingMIDlet = zXingMIDlet;
44 waitLock = new Object();
46 multimediaManager = new DefaultMultimediaManager();
50 synchronized (waitLock) {
55 private void waitForSignal() {
56 synchronized (waitLock) {
59 } catch (InterruptedException ie) {
71 Player player = zXingMIDlet.getPlayer();
75 multimediaManager.setFocus(player);
76 byte[] snapshot = takeSnapshot();
77 Image capturedImage = Image.createImage(snapshot, 0, snapshot.length);
78 MonochromeBitmapSource source = new LCDUIImageMonochromeBitmapSource(capturedImage);
79 Reader reader = new MultiFormatReader();
80 Result result = reader.decode(source);
81 zXingMIDlet.handleDecodedText(result);
82 } catch (ReaderException re) {
83 // Show a friendlier message on a mere failure to read the barcode
84 zXingMIDlet.showError("Sorry, no barcode was found.");
85 } catch (MediaException me) {
86 zXingMIDlet.showError(me);
87 } catch (RuntimeException re) {
88 zXingMIDlet.showError(re);
93 private byte[] takeSnapshot() throws MediaException {
94 VideoControl videoControl = zXingMIDlet.getVideoControl();
95 byte[] snapshot = null;
97 snapshot = videoControl.getSnapshot(null);
98 } catch (MediaException me) {
100 if (snapshot == null) {
101 // Fall back on JPEG; seems that some cameras default to PNG even
102 // when PNG isn't supported!
103 snapshot = videoControl.getSnapshot("encoding=jpeg");
104 if (snapshot == null) {
105 throw new MediaException("Can't obtain a snapshot");