-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Webcam.java
492 lines (407 loc) · 11.4 KB
/
Webcam.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package com.github.sarxos.webcam;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sarxos.webcam.ds.buildin.WebcamDefaultDevice;
import com.github.sarxos.webcam.ds.buildin.WebcamDefaultDriver;
/**
* Webcam class.
*
* @author Bartosz Firyn (bfiryn)
*/
public class Webcam {
private static final Logger LOG = LoggerFactory.getLogger(Webcam.class);
// @formatter:off
private static final String[] DRIVERS_DEFAULT = new String[] {
"com.github.sarxos.webcam.ds.openimaj.OpenImajDriver",
"com.github.sarxos.webcam.ds.civil.LtiCivilDriver",
"com.github.sarxos.webcam.ds.jmf.JmfDriver",
};
// @formatter:on
private static final List<String> DRIVERS_LIST = new ArrayList<String>(Arrays.asList(DRIVERS_DEFAULT));
private static final List<Class<?>> DRIVERS_CLASS_LIST = new ArrayList<Class<?>>();
private static class ShutdownHook extends Thread {
private Webcam webcam = null;
public ShutdownHook(Webcam webcam) {
this.webcam = webcam;
}
@Override
public void run() {
LOG.info("Automatic resource deallocation");
super.run();
webcam.dispose();
webcam.close0();
}
}
private static WebcamDriver driver = null;
private static List<Webcam> webcams = null;
/**
* Is automated deallocation on TERM signal enabled.
*/
private static volatile boolean deallocOnTermSignal = false;
/**
* Webcam listeners.
*/
private List<WebcamListener> listeners = new ArrayList<WebcamListener>();
private List<Dimension> customSizes = new ArrayList<Dimension>();
private ShutdownHook hook = null;
private WebcamDevice device = null;
private boolean open = false;
/**
* Webcam class.
*
* @param device - device to be used as webcam
*/
protected Webcam(WebcamDevice device) {
if (device == null) {
throw new IllegalArgumentException("Webcam device cannot be null");
}
this.device = device;
}
/**
* Check if size is set up.
*/
private void ensureSize() {
Dimension size = device.getSize();
if (size == null) {
Dimension[] sizes = device.getSizes();
if (sizes == null) {
throw new WebcamException("Sizes array from driver cannot be null!");
}
if (sizes.length == 0) {
throw new WebcamException("Sizes array from driver is empty, cannot choose image size");
}
device.setSize(sizes[0]);
}
}
/**
* Open webcam.
*/
public synchronized void open() {
if (open) {
return;
}
if (LOG.isInfoEnabled()) {
LOG.info("Opening webcam " + getName());
}
ensureSize();
device.open();
open = true;
hook = new ShutdownHook(this);
Runtime.getRuntime().addShutdownHook(hook);
WebcamEvent we = new WebcamEvent(this);
for (WebcamListener l : listeners) {
try {
l.webcamOpen(we);
} catch (Exception e) {
LOG.error(String.format("Notify webcam open, exception when calling %s listener", l.getClass()), e);
}
}
}
/**
* Close webcam.
*/
public synchronized void close() {
if (!open) {
return;
}
Runtime.getRuntime().removeShutdownHook(hook);
close0();
}
/**
* Close webcam (internal impl).
*/
private void close0() {
if (!open) {
return;
}
if (LOG.isInfoEnabled()) {
LOG.info("Closing {}", getName());
}
device.close();
open = false;
WebcamEvent we = new WebcamEvent(this);
for (WebcamListener l : listeners) {
try {
l.webcamClosed(we);
} catch (Exception e) {
LOG.error(String.format("Notify webcam closed, exception when calling %s listener", l.getClass()), e);
}
}
}
/**
* Is webcam open?
*
* @return true if open, false otherwise
*/
public synchronized boolean isOpen() {
return open;
}
/**
* @return Webcam view size (picture size) in pixels.
*/
public Dimension getViewSize() {
return device.getSize();
}
/**
* Return list of supported view sizes. It can differ between vary webcam
* data sources.
*
* @return
*/
public Dimension[] getViewSizes() {
return device.getSizes();
}
public void setCustomViewSizes(Dimension[] sizes) {
if (sizes == null) {
customSizes.clear();
return;
}
customSizes = Arrays.asList(sizes);
}
public Dimension[] getCustomViewSizes() {
return customSizes.toArray(new Dimension[customSizes.size()]);
}
public void setViewSize(Dimension size) {
if (size == null) {
throw new IllegalArgumentException("View size cannot be null!");
}
// check if dimension is valid
Dimension[] predefined = getViewSizes();
Dimension[] custom = getCustomViewSizes();
boolean ok = false;
for (Dimension d : predefined) {
if (d.width == size.width && d.height == size.height) {
ok = true;
break;
}
}
if (!ok) {
for (Dimension d : custom) {
if (d.width == size.width && d.height == size.height) {
ok = true;
break;
}
}
}
if (!ok) {
StringBuilder sb = new StringBuilder("Incorrect dimension [");
sb.append(size.width).append("x").append(size.height).append("] ");
sb.append("possible ones are ");
for (Dimension d : predefined) {
sb.append("[").append(d.width).append("x").append(d.height).append("] ");
}
for (Dimension d : custom) {
sb.append("[").append(d.width).append("x").append(d.height).append("] ");
}
throw new IllegalArgumentException(sb.toString());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Setting new view size {} x {}", size.width, size.height);
}
device.setSize(size);
}
/**
* Capture image from webcam.
*
* @return Captured image
*/
public synchronized BufferedImage getImage() {
if (!open) {
LOG.debug("Try to get image on closed webcam, opening it automatically");
open();
}
return device.getImage();
}
/**
* Get list of webcams to use.
*
* @return List of webcams
*/
public static List<Webcam> getWebcams() {
if (webcams == null) {
webcams = new ArrayList<Webcam>();
if (driver == null) {
driver = WebcamDriverUtils.findDriver(DRIVERS_LIST, DRIVERS_CLASS_LIST);
}
if (driver == null) {
LOG.info("Webcam driver has not been found, default one will be used!");
driver = new WebcamDefaultDriver();
}
List<WebcamDevice> devices = driver.getDevices();
if (deallocOnTermSignal) {
LOG.warn("Automated deallocation on TERM signal is enabled!");
WebcamDeallocator.store(devices.toArray(new WebcamDevice[devices.size()]));
}
for (WebcamDevice device : devices) {
webcams.add(new Webcam(device));
}
if (LOG.isInfoEnabled()) {
for (Webcam webcam : webcams) {
LOG.info("Webcam found " + webcam.getName());
}
}
}
return Collections.unmodifiableList(webcams);
}
protected static void clearWebcams() {
webcams = null;
}
/**
* @return Default webcam (first from the list)
*/
public static Webcam getDefault() {
List<Webcam> webcams = getWebcams();
if (webcams.isEmpty()) {
throw new WebcamException("No webcam available in the system");
}
return webcams.get(0);
}
/**
* Get webcam name (device name). The name of device depends on the value
* returned by the underlying data source, so in some cases it can be
* human-readable value and sometimes it can be some strange number.
*
* @return Name
*/
public String getName() {
return device.getName();
}
@Override
public String toString() {
return String.format("Webcam %s", getName());
}
/**
* Add webcam listener.
*
* @param l the listener to be added
*/
public boolean addWebcamListener(WebcamListener l) {
if (l == null) {
throw new IllegalArgumentException("Webcam listener cannot be null!");
}
synchronized (listeners) {
return listeners.add(l);
}
}
/**
* @return All webcam listeners
*/
public WebcamListener[] getWebcamListeners() {
synchronized (listeners) {
return listeners.toArray(new WebcamListener[listeners.size()]);
}
}
public boolean removeWebcamListener(WebcamListener l) {
synchronized (listeners) {
return listeners.remove(l);
}
}
/**
* @return Data source currently used by webcam
*/
public static WebcamDriver getDriver() {
return driver;
}
/**
* Set new video driver to be used by webcam.
*
* @param driver new video driver to use (e.g. Civil, JFM, FMJ, QTJ, etc)
*/
public static void setDriver(WebcamDriver driver) {
if (driver == null) {
throw new IllegalArgumentException("Webcam driver cannot be null!");
}
resetDriver();
Webcam.driver = driver;
}
/**
* Set new video driver class to be used by webcam. Class given in the
* argument shall extend {@link WebcamDriver} interface and should have
* public default constructor, so instance can be created by reflection.
*
* @param driver new video driver class to use
*/
public static void setDriver(Class<? extends WebcamDriver> driverClass) {
resetDriver();
if (driverClass == null) {
throw new IllegalArgumentException("Webcam driver class cannot be null!");
}
try {
driver = driverClass.newInstance();
} catch (InstantiationException e) {
throw new WebcamException(e);
} catch (IllegalAccessException e) {
throw new WebcamException(e);
}
}
public static void resetDriver() {
DRIVERS_LIST.clear();
DRIVERS_LIST.addAll(Arrays.asList(DRIVERS_DEFAULT));
driver = null;
if (webcams != null && !webcams.isEmpty()) {
webcams.clear();
}
webcams = null;
}
/**
* Register new webcam video driver.
*
* @param clazz webcam video driver class
*/
public static void registerDriver(Class<? extends WebcamDriver> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Webcam driver class to register cannot be null!");
}
DRIVERS_CLASS_LIST.add(clazz);
registerDriver(clazz.getCanonicalName());
}
/**
* Register new webcam video driver.
*
* @param clazzName webcam video driver class name
*/
public static void registerDriver(String clazzName) {
if (clazzName == null) {
throw new IllegalArgumentException("Webcam driver class name to register cannot be null!");
}
DRIVERS_LIST.add(clazzName);
}
/**
* Return underlying webcam device. Depending on the driver used to discover
* devices, this method can return instances of different class. By default
* {@link WebcamDefaultDevice} is returned when no external driver is used.
*
* @return Underlying webcam device instance
*/
public WebcamDevice getDevice() {
return device;
}
/**
* Completely dispose capture device. After this operation webcam cannot be
* used any more and reinstantiation is required.
*/
protected void dispose() {
device.close();
device.dispose();
}
/**
* <b>CAUTION!!!</b><br>
* <br>
* This is experimental feature to be used mostly in in development phase.
* After you set handle term signal to true, and fetch capture devices,
* Webcam Capture API will listen for TERM signal and try to close all
* devices after it has been received. <b>This feature can be unstable on
* some systems!</b>
*
* @param on
*/
public static void handleTermSignal(boolean on) {
deallocOnTermSignal = on;
}
}