-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Webcam.java
982 lines (826 loc) · 26.8 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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
package com.github.sarxos.webcam;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sarxos.webcam.WebcamDevice.BufferAccess;
import com.github.sarxos.webcam.ds.buildin.WebcamDefaultDevice;
import com.github.sarxos.webcam.ds.buildin.WebcamDefaultDriver;
import com.github.sarxos.webcam.ds.cgt.WebcamCloseTask;
import com.github.sarxos.webcam.ds.cgt.WebcamDisposeTask;
import com.github.sarxos.webcam.ds.cgt.WebcamOpenTask;
import com.github.sarxos.webcam.ds.cgt.WebcamReadBufferTask;
import com.github.sarxos.webcam.ds.cgt.WebcamReadImageTask;
import com.github.sarxos.webcam.util.ImageUtils;
/**
* Webcam class. It wraps webcam device obtained from webcam driver.
*
* @author Bartosz Firyn (bfiryn)
*/
public class Webcam {
/**
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(Webcam.class);
/**
* List of driver classes names to search for.
*/
private static final List<String> DRIVERS_LIST = new ArrayList<String>();
/**
* List of driver classes to search for.
*/
private static final List<Class<?>> DRIVERS_CLASS_LIST = new ArrayList<Class<?>>();
/**
* Discovery listeners.
*/
private static final List<WebcamDiscoveryListener> DISCOVERY_LISTENERS = Collections.synchronizedList(new ArrayList<WebcamDiscoveryListener>());
/**
* Webcam driver (LtiCivil, JMF, FMJ, JQT, OpenCV, VLCj, etc).
*/
private static WebcamDriver driver = null;
/**
* Webcam discovery service.
*/
private static volatile WebcamDiscoveryService discovery = null;
/**
* Is automated deallocation on TERM signal enabled.
*/
private static boolean deallocOnTermSignal = false;
/**
* Is auto-open feature enabled?
*/
private static boolean autoOpen = false;
/**
* Webcam listeners.
*/
private List<WebcamListener> listeners = Collections.synchronizedList(new ArrayList<WebcamListener>());
/**
* List of custom resolution sizes supported by webcam instance.
*/
private List<Dimension> customSizes = new ArrayList<Dimension>();
/**
* Shutdown hook.
*/
private WebcamShutdownHook hook = null;
/**
* Underlying webcam device.
*/
private WebcamDevice device = null;
/**
* Is webcam open?
*/
private AtomicBoolean open = new AtomicBoolean(false);
/**
* Is webcam already disposed?
*/
private AtomicBoolean disposed = new AtomicBoolean(false);
/**
* Is non-blocking (asynchronous) access enabled?
*/
private volatile boolean asynchronous = false;
/**
* Current FPS.
*/
private volatile double fps = 0;
/**
* Webcam image updater.
*/
private WebcamUpdater updater = new WebcamUpdater(this);
/**
* Webcam class.
*
* @param device - device to be used as webcam
* @throws IllegalArgumentException when device argument is null
*/
protected Webcam(WebcamDevice device) {
if (device == null) {
throw new IllegalArgumentException("Webcam device cannot be null");
}
this.device = device;
}
/**
* Open the webcam in blocking (synchronous) mode.
*
* @see #open(boolean)
*/
public boolean open() {
return open(false);
}
/**
* Open the webcam in either blocking (synchronous) or non-blocking
* (asynchronous) mode.The difference between those two modes lies in the
* image acquisition mechanism.<br>
* <br>
* In blocking mode, when user calls {@link #getImage()} method, device is
* being queried for new image buffer and user have to wait for it to be
* available.<br>
* <br>
* In non-blocking mode, there is a special thread running in the background
* which constantly fetch new images and cache them internally for further
* use. This cached instance is returned every time when user request new
* image. Because of that it can be used when timeing is very important,
* because all users calls for new image do not have to wait on device
* response. By using this mode user should be aware of the fact that in
* some cases, when two consecutive calls to get new image are executed more
* often than webcam device can serve them, the same image instance will be
* returned. User should use {@link #isImageNew()} method to distinguish if
* returned image is not the same as the previous one.
*
* @param async true for non-blocking mode, false for blocking
*/
public boolean open(boolean async) {
if (open.compareAndSet(false, true)) {
assert updater != null;
WebcamOpenTask task = new WebcamOpenTask(driver, device);
try {
task.open();
} catch (InterruptedException e) {
open.set(false);
LOG.error("Processor has been interrupted before webcam was open!", e);
return false;
} catch (WebcamException e) {
open.set(false);
throw e;
}
LOG.debug("Webcam is now open {}", getName());
// setup non-blocking configuration
asynchronous = async;
if (async) {
updater.start();
}
// install shutdown hook
Runtime.getRuntime().addShutdownHook(hook = new WebcamShutdownHook(this));
// notify listeners
WebcamEvent we = new WebcamEvent(WebcamEventType.OPEN, this);
for (WebcamListener l : getWebcamListeners()) {
try {
l.webcamOpen(we);
} catch (Exception e) {
LOG.error(String.format("Notify webcam open, exception when calling listener %s", l.getClass()), e);
}
}
} else {
LOG.debug("Webcam is already open {}", getName());
}
return true;
}
/**
* Close the webcam.
*/
public boolean close() {
if (open.compareAndSet(true, false)) {
assert updater != null;
// close webcam
WebcamCloseTask task = new WebcamCloseTask(driver, device);
try {
task.close();
} catch (InterruptedException e) {
open.set(true);
LOG.error("Processor has been interrupted before webcam was closed!", e);
return false;
} catch (WebcamException e) {
open.set(false);
throw e;
}
// stop updater
if (asynchronous) {
updater.stop();
}
// remove shutdown hook (it's not more necessary)
Runtime.getRuntime().removeShutdownHook(hook);
// notify listeners
WebcamEvent we = new WebcamEvent(WebcamEventType.CLOSED, this);
for (WebcamListener l : getWebcamListeners()) {
try {
l.webcamClosed(we);
} catch (Exception e) {
LOG.error(String.format("Notify webcam closed, exception when calling %s listener", l.getClass()), e);
}
}
} else {
LOG.debug("Webcam is already closed {}", getName());
}
return true;
}
/**
* Is webcam open?
*
* @return true if open, false otherwise
*/
public boolean isOpen() {
return open.get();
}
/**
* Get current webcam resolution in pixels.
*
* @return Webcam resolution (picture size) in pixels.
*/
public Dimension getViewSize() {
return device.getResolution();
}
/**
* Return list of supported view sizes. It can differ between vary webcam
* data sources.
*
* @return Array of supported dimensions
*/
public Dimension[] getViewSizes() {
return device.getResolutions();
}
/**
* Set custom resolution. If you are using this method you have to make sure
* that your webcam device can support this specific resolution.
*
* @param sizes the array of custom resolutions to be supported by webcam
*/
public void setCustomViewSizes(Dimension[] sizes) {
assert customSizes != null;
if (sizes == null) {
customSizes.clear();
return;
}
customSizes = Arrays.asList(sizes);
}
public Dimension[] getCustomViewSizes() {
assert customSizes != null;
return customSizes.toArray(new Dimension[customSizes.size()]);
}
/**
* Set new view size. New size has to exactly the same as one of the default
* sized or exactly the same as one of the custom ones.
*
* @param size the new view size to be set
* @see Webcam#setCustomViewSizes(Dimension[])
* @see Webcam#getViewSizes()
*/
public void setViewSize(Dimension size) {
if (size == null) {
throw new IllegalArgumentException("Resolution cannot be null!");
}
if (open.get()) {
throw new IllegalStateException("Cannot change resolution when webcam is open, please close it first");
}
// check if new resolution is the same as current one
Dimension current = getViewSize();
if (current != null && current.width == size.width && current.height == size.height) {
return;
}
// check if new resolution is valid
Dimension[] predefined = getViewSizes();
Dimension[] custom = getCustomViewSizes();
assert predefined != null;
assert custom != null;
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());
}
LOG.debug("Setting new resolution {}x{}", size.width, size.height);
device.setResolution(size);
}
/**
* Capture image from webcam and return it. Will return image object or null
* if webcam is closed or has been already disposed by JVM.<br>
* <br>
* <b>IMPORTANT NOTE!!!</b><br>
* <br>
* There are two possible behaviors of what webcam should do when you try to
* get image and webcam is actually closed. Normally it will return null,
* but there is a special flag which can be statically set to switch all
* webcams to auto open mode. In this mode, webcam will be automatically
* open, when you try to get image from closed webcam. Please be aware of
* some side effects! In case of multi-threaded applications, there is no
* guarantee that one thread will not try to open webcam even if it was
* manually closed in different thread.
*
* @return Captured image or null if webcam is closed or disposed by JVM
*/
public BufferedImage getImage() {
if (!isReady()) {
return null;
}
long t1 = 0;
long t2 = 0;
assert updater != null;
if (asynchronous) {
return updater.getImage();
} else {
// get image
t1 = System.currentTimeMillis();
BufferedImage image = new WebcamReadImageTask(driver, device).getImage();
t2 = System.currentTimeMillis();
if (image == null) {
return null;
}
// calculate FPS
// +1 to avoid division by zero
fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5;
// notify webcam listeners about new image available
updater.notifyWebcamImageObtained(this, image);
return image;
}
}
public boolean isImageNew() {
assert updater != null;
if (asynchronous) {
return updater.isImageNew();
}
return true;
}
protected double getFPS() {
assert updater != null;
if (asynchronous) {
return updater.getFPS();
} else {
return fps;
}
}
/**
* Get RAW image ByteBuffer. It will always return buffer with 3 x 1 bytes
* per each pixel, where RGB components are on (0, 1, 2) and color space is
* sRGB.<br>
* <br>
*
* <b>IMPORTANT!</b><br>
* Some drivers can return direct ByteBuffer, so there is no guarantee that
* underlying bytes will not be released in next read image operation.
* Therefore, to avoid potential bugs you should convert this ByteBuffer to
* bytes array before you fetch next image.
*
* @return Byte buffer
*/
public ByteBuffer getImageBytes() {
if (!isReady()) {
return null;
}
assert driver != null;
assert device != null;
// some devices can support direct image buffers, and for those call
// processor task, and for those which does not support direct image
// buffers, just convert image to RGB byte array
if (device instanceof BufferAccess) {
return new WebcamReadBufferTask(driver, device).getBuffer();
} else {
BufferedImage image = getImage();
if (image != null) {
return ByteBuffer.wrap(ImageUtils.toRawByteArray(image));
} else {
return null;
}
}
}
/**
* Is webcam ready to be read.
*
* @return True if ready, false otherwise
*/
private boolean isReady() {
assert disposed != null;
assert open != null;
if (disposed.get()) {
LOG.warn("Cannot get image, webcam has been already disposed");
return false;
}
if (!open.get()) {
if (autoOpen) {
open();
} else {
return false;
}
}
return true;
}
/**
* Get list of webcams to use. This method will wait predefined time
* interval for webcam devices to be discovered. By default this time is set
* to 1 minute.
*
* @return List of webcams existing in the system
* @throws WebcamException when something is wrong
* @see Webcam#getWebcams(long, TimeUnit)
*/
public static List<Webcam> getWebcams() throws WebcamException {
// timeout exception below will never be caught since user would have to
// wait around three hundreds billion years for it to occur
try {
return getWebcams(Long.MAX_VALUE);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
/**
* Get list of webcams to use. This method will wait given time interval for
* webcam devices to be discovered. Time argument is given in milliseconds.
*
* @param timeout the time to wait for webcam devices to be discovered
* @return List of webcams existing in the ssytem
* @throws WebcamException when something is wrong
* @throws IllegalArgumentException when timeout is negative
* @see Webcam#getWebcams(long, TimeUnit)
*/
public static List<Webcam> getWebcams(long timeout) throws TimeoutException, WebcamException {
if (timeout < 0) {
throw new IllegalArgumentException(String.format("Timeout cannot be negative (%d)", timeout));
}
return getWebcams(timeout, TimeUnit.MILLISECONDS);
}
/**
* Get list of webcams to use. This method will wait given time interval for
* webcam devices to be discovered.
*
* @param timeout the devices discovery timeout
* @param tunit the time unit
* @return List of webcams
* @throws TimeoutException when timeout has been exceeded
* @throws WebcamException when something is wrong
* @throws IllegalArgumentException when timeout is negative or tunit null
*/
public static synchronized List<Webcam> getWebcams(long timeout, TimeUnit tunit) throws TimeoutException, WebcamException {
if (timeout < 0) {
throw new IllegalArgumentException(String.format("Timeout cannot be negative (%d)", timeout));
}
if (tunit == null) {
throw new IllegalArgumentException("Time unit cannot be null!");
}
WebcamDiscoveryService discovery = getDiscoveryService();
assert discovery != null;
List<Webcam> webcams = discovery.getWebcams(timeout, tunit);
if (!discovery.isRunning()) {
discovery.start();
}
return webcams;
}
/**
* Will discover and return first webcam available in the system.
*
* @return Default webcam (first from the list)
* @throws WebcamException if something is really wrong
* @see Webcam#getWebcams()
*/
public static Webcam getDefault() throws WebcamException {
try {
return getDefault(Long.MAX_VALUE);
} catch (TimeoutException e) {
// this should never happen since user would have to wait 300000000
// years for it to occur
throw new RuntimeException(e);
}
}
/**
* Will discover and return first webcam available in the system.
*
* @param timeout the webcam discovery timeout (1 minute by default)
* @return Default webcam (first from the list)
* @throws TimeoutException when discovery timeout has been exceeded
* @throws WebcamException if something is really wrong
* @throws IllegalArgumentException when timeout is negative
* @see Webcam#getWebcams(long)
*/
public static Webcam getDefault(long timeout) throws TimeoutException, WebcamException {
if (timeout < 0) {
throw new IllegalArgumentException(String.format("Timeout cannot be negative (%d)", timeout));
}
return getDefault(timeout, TimeUnit.MILLISECONDS);
}
/**
* Will discover and return first webcam available in the system.
*
* @param timeout the webcam discovery timeout (1 minute by default)
* @param tunit the time unit
* @return Default webcam (first from the list)
* @throws TimeoutException when discovery timeout has been exceeded
* @throws WebcamException if something is really wrong
* @throws IllegalArgumentException when timeout is negative or tunit null
* @see Webcam#getWebcams(long, TimeUnit)
*/
public static Webcam getDefault(long timeout, TimeUnit tunit) throws TimeoutException, WebcamException {
if (timeout < 0) {
throw new IllegalArgumentException(String.format("Timeout cannot be negative (%d)", timeout));
}
if (tunit == null) {
throw new IllegalArgumentException("Time unit cannot be null!");
}
List<Webcam> webcams = getWebcams(timeout, tunit);
assert webcams != null;
if (!webcams.isEmpty()) {
return webcams.get(0);
}
LOG.warn("No webcam has been detected!");
return null;
}
/**
* 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() {
assert device != null;
return device.getName();
}
@Override
public String toString() {
return String.format("Webcam %s", getName());
}
/**
* Add webcam listener.
*
* @param l the listener to be added
* @throws IllegalArgumentException when argument is null
*/
public boolean addWebcamListener(WebcamListener l) {
if (l == null) {
throw new IllegalArgumentException("Webcam listener cannot be null!");
}
assert listeners != null;
return listeners.add(l);
}
/**
* @return All webcam listeners
*/
public WebcamListener[] getWebcamListeners() {
assert listeners != null;
return listeners.toArray(new WebcamListener[listeners.size()]);
}
/**
* @return Number of webcam listeners
*/
public int getWebcamListenersCount() {
assert listeners != null;
return listeners.size();
}
/**
* Removes webcam listener.
*
* @param l the listener to be removed
* @return True if listener has been removed, false otherwise
*/
public boolean removeWebcamListener(WebcamListener l) {
assert listeners != null;
return listeners.remove(l);
}
/**
* Return webcam driver. Perform search if necessary.<br>
* <br>
* <b>This method is not thread-safe!</b>
*
* @return Webcam driver
*/
public static synchronized WebcamDriver getDriver() {
if (driver == null) {
driver = WebcamDriverUtils.findDriver(DRIVERS_LIST, DRIVERS_CLASS_LIST);
}
if (driver == null) {
driver = new WebcamDefaultDriver();
}
LOG.info("{} capture driver will be used", driver.getClass().getSimpleName());
return driver;
}
/**
* Set new video driver to be used by webcam.<br>
* <br>
* <b>This method is not thread-safe!</b>
*
* @param driver new webcam driver to be used (e.g. LtiCivil, JFM, FMJ, QTJ)
* @throws IllegalArgumentException when argument is null
*/
public static synchronized 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.<br>
* <br>
* <b>This method is not thread-safe!</b>
*
* @param driverClass new video driver class to use
* @throws IllegalArgumentException when argument is null
*/
public static synchronized void setDriver(Class<? extends WebcamDriver> driverClass) {
if (driverClass == null) {
throw new IllegalArgumentException("Webcam driver class cannot be null!");
}
resetDriver();
try {
driver = driverClass.newInstance();
} catch (InstantiationException e) {
throw new WebcamException(e);
} catch (IllegalAccessException e) {
throw new WebcamException(e);
}
}
/**
* Reset webcam driver.<br>
* <br>
* <b>This method is not thread-safe!</b>
*/
public static synchronized void resetDriver() {
DRIVERS_LIST.clear();
if (discovery != null) {
discovery.shutdown();
discovery = null;
}
driver = null;
}
/**
* Register new webcam video driver.
*
* @param clazz webcam video driver class
* @throws IllegalArgumentException when argument is null
*/
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
* @throws IllegalArgumentException when argument is null
*/
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() {
assert device != null;
return device;
}
/**
* Completely dispose capture device. After this operation webcam cannot be
* used any more and full reinstantiation is required.
*/
protected void dispose() {
assert disposed != null;
assert open != null;
assert driver != null;
assert device != null;
assert listeners != null;
if (!disposed.compareAndSet(false, true)) {
return;
}
open.set(false);
LOG.info("Disposing webcam {}", getName());
WebcamDisposeTask task = new WebcamDisposeTask(driver, device);
try {
task.dispose();
} catch (InterruptedException e) {
LOG.error("Processor has been interrupted before webcam was disposed!", e);
return;
}
WebcamEvent we = new WebcamEvent(WebcamEventType.DISPOSED, this);
for (WebcamListener l : listeners) {
try {
l.webcamClosed(we);
l.webcamDisposed(we);
} catch (Exception e) {
LOG.error(String.format("Notify webcam disposed, exception when calling %s listener", l.getClass()), e);
}
}
// hook can be null because there is a possibility that webcam has never
// been open and therefore hook was not created
if (hook != null) {
try {
Runtime.getRuntime().removeShutdownHook(hook);
} catch (IllegalStateException e) {
LOG.trace("Shutdown in progress, cannot remove hook");
}
}
LOG.debug("Webcam disposed {}", getName());
}
/**
* <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 signal handling will be enabled if true, disabled otherwise
*/
public static void setHandleTermSignal(boolean on) {
if (on) {
LOG.warn("Automated deallocation on TERM signal is now enabled! Make sure to not use it in production!");
}
deallocOnTermSignal = on;
}
/**
* Is TERM signal handler enabled.
*
* @return True if enabled, false otherwise
*/
public static boolean isHandleTermSignal() {
return deallocOnTermSignal;
}
/**
* Switch all webcams to auto open mode. In this mode, each webcam will be
* automatically open whenever user will try to get image from instance
* which has not yet been open. Please be aware of some side effects! In
* case of multi-threaded applications, there is no guarantee that one
* thread will not try to open webcam even if it was manually closed in
* different thread.
*
* @param on true to enable, false to disable
*/
public static void setAutoOpenMode(boolean on) {
autoOpen = on;
}
/**
* Is auto open mode enabled. Auto open mode will will automatically open
* webcam whenever user will try to get image from instance which has not
* yet been open. Please be aware of some side effects! In case of
* multi-threaded applications, there is no guarantee that one thread will
* not try to open webcam even if it was manually closed in different
* thread.
*
* @return True if mode is enabled, false otherwise
*/
public static boolean isAutoOpenMode() {
return autoOpen;
}
/**
* Add new webcam discovery listener.
*
* @param l the listener to be added
* @return True, if listeners list size has been changed, false otherwise
* @throws IllegalArgumentException when argument is null
*/
public static boolean addDiscoveryListener(WebcamDiscoveryListener l) {
if (l == null) {
throw new IllegalArgumentException("Webcam discovery listener cannot be null!");
}
return DISCOVERY_LISTENERS.add(l);
}
public static WebcamDiscoveryListener[] getDiscoveryListeners() {
return DISCOVERY_LISTENERS.toArray(new WebcamDiscoveryListener[DISCOVERY_LISTENERS.size()]);
}
/**
* Remove discovery listener
*
* @param l the listener to be removed
* @return True if listeners list contained the specified element
*/
public static boolean removeDiscoveryListener(WebcamDiscoveryListener l) {
return DISCOVERY_LISTENERS.remove(l);
}
/**
* Return discovery service.
*
* @return Discovery service
*/
public static synchronized WebcamDiscoveryService getDiscoveryService() {
if (discovery == null) {
discovery = new WebcamDiscoveryService(getDriver());
}
return discovery;
}
}