-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathCapture.java
More file actions
1235 lines (1037 loc) · 35.4 KB
/
Capture.java
File metadata and controls
1235 lines (1037 loc) · 35.4 KB
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-12 Ben Fry and Casey Reas
The previous version of this code was developed by Hernando Barragan
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.video;
import processing.core.*;
import java.nio.*;
import java.util.ArrayList;
import java.io.File;
import java.lang.reflect.*;
import org.gstreamer.*;
import org.gstreamer.Buffer;
import org.gstreamer.elements.*;
import org.gstreamer.interfaces.PropertyProbe;
import org.gstreamer.interfaces.Property;
/**
* ( begin auto-generated from Capture.xml )
*
* Datatype for storing and manipulating video frames from an attached
* capture device such as a camera. Use <b>Capture.list()</b> to show the
* names of any attached devices. Using the version of the constructor
* without <b>name</b> will attempt to use the last device used by a
* QuickTime program.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Class for storing and manipulating video frames from an attached capture
* device such as a camera.
* @webref video
* @usage application
*/
public class Capture extends PImage implements PConstants {
protected static String sourceElementName;
protected static String devicePropertyName;
protected static String indexPropertyName;
// Default gstreamer capture plugin for each platform, and property names.
static {
if (PApplet.platform == MACOSX) {
sourceElementName = "qtkitvideosrc";
devicePropertyName = "device-name";
indexPropertyName = "device-index";
} else if (PApplet.platform == WINDOWS) {
sourceElementName = "ksvideosrc";
devicePropertyName = "device-name";
indexPropertyName = "device-index";
} else if (PApplet.platform == LINUX) {
sourceElementName = "v4l2src";
// The "device" property in v4l2src expects the device location
// (/dev/video0, etc). v4l2src has "device-name", which requires the
// human-readable name... but how to query in linux?.
devicePropertyName = "device";
indexPropertyName = "device-fd";
} else {}
}
protected static boolean useResMacHack = true;
public float frameRate;
public Pipeline pipeline;
protected boolean capturing = false;
protected String frameRateString;
protected int bufWidth;
protected int bufHeight;
protected String sourceName;
protected Element sourceElement;
protected Method captureEventMethod;
protected Object eventHandler;
protected boolean available;
protected boolean pipelineReady;
protected boolean newFrame;
protected RGBDataAppSink rgbSink = null;
protected int[] copyPixels = null;
protected boolean firstFrame = true;
protected int reqWidth;
protected int reqHeight;
protected boolean useBufferSink = false;
protected boolean outdatedPixels = true;
protected Object bufferSink;
protected Method sinkCopyMethod;
protected Method sinkSetMethod;
protected Method sinkDisposeMethod;
protected Method sinkGetMethod;
protected String copyMask;
protected Buffer natBuffer = null;
protected BufferDataAppSink natSink = null;
public Capture(PApplet parent) {
String[] configs = Capture.list();
if (configs.length == 0) {
throw new RuntimeException("There are no cameras available for capture");
}
String name = getName(configs[0]);
int[] size = getSize(configs[0]);
String fps = getFrameRate(configs[0]);
String idName;
Object idValue;
if (devicePropertyName.equals("")) {
// For plugins without device name property, the name is casted
// as an index
idName = indexPropertyName;
idValue = new Integer(PApplet.parseInt(name));
} else {
idName = devicePropertyName;
idValue = name;
}
initGStreamer(parent, size[0], size[1], sourceElementName,
idName, idValue, fps);
}
public Capture(PApplet parent, String requestConfig) {
String name = getName(requestConfig);
int[] size = getSize(requestConfig);
String fps = getFrameRate(requestConfig);
String idName;
Object idValue;
if (devicePropertyName.equals("")) {
// For plugins without device name property, the name is casted
// as an index
idName = indexPropertyName;
idValue = new Integer(PApplet.parseInt(name));
} else {
idName = devicePropertyName;
idValue = name;
}
initGStreamer(parent, size[0], size[1], sourceElementName,
idName, idValue, fps);
}
/**
* @param parent typically use "this"
* @param requestWidth width of the frame
* @param requestHeight height of the frame
*/
public Capture(PApplet parent, int requestWidth, int requestHeight) {
super(requestWidth, requestHeight, RGB);
initGStreamer(parent, requestWidth, requestHeight, sourceElementName,
null, null, "");
}
/**
* <h3>Advanced</h3>
* Constructor that takes resolution and framerate.
*
* @param frameRate number of frames to read per second
*/
public Capture(PApplet parent, int requestWidth, int requestHeight,
int frameRate) {
super(requestWidth, requestHeight, RGB);
initGStreamer(parent, requestWidth, requestHeight, sourceElementName,
null, null, frameRate + "/1");
}
/**
* <h3>Advanced</h3>
* This constructor allows to specify resolution and camera name.
*
* @param cameraName name of the camera
*/
public Capture(PApplet parent, int requestWidth, int requestHeight,
String cameraName) {
super(requestWidth, requestHeight, RGB);
String idName;
Object idValue;
if (-1 < cameraName.indexOf("name=")) {
// cameraName contains a full config string from gstreamer
cameraName = getName(cameraName);
}
if (devicePropertyName.equals("")) {
// For plugins without device name property, the name is casted
// as an index
idName = indexPropertyName;
idValue = new Integer(PApplet.parseInt(cameraName));
} else {
idName = devicePropertyName;
idValue = cameraName;
}
initGStreamer(parent, requestWidth, requestHeight, sourceElementName,
idName, idValue, "");
}
/**
* <h3>Advanced</h3>
* This constructor allows to specify the camera name and the desired
* framerate, in addition to the resolution.
*/
public Capture(PApplet parent, int requestWidth, int requestHeight,
String cameraName, int frameRate) {
super(requestWidth, requestHeight, RGB);
String idName;
Object idValue;
if (-1 < cameraName.indexOf("name=")) {
// cameraName contains a full config string from gstreamer
cameraName = getName(cameraName);
}
if (devicePropertyName.equals("")) {
// For plugins without device name property, the name is casted
// as an index
idName = indexPropertyName;
idValue = new Integer(PApplet.parseInt(cameraName));
} else {
idName = devicePropertyName;
idValue = cameraName;
}
initGStreamer(parent, requestWidth, requestHeight, sourceElementName,
idName, idValue, frameRate + "/1");
}
/**
* Disposes all the native resources associated to this capture device.
*
* NOTE: This is not official API and may/will be removed at any time.
*/
public void dispose() {
if (pipeline != null) {
try {
if (pipeline.isPlaying()) {
pipeline.stop();
pipeline.getState();
}
} catch (Exception e) {
e.printStackTrace();
}
pixels = null;
copyPixels = null;
if (rgbSink != null) {
rgbSink.removeListener();
rgbSink.dispose();
rgbSink = null;
}
natBuffer = null;
if (natSink != null) {
natSink.removeListener();
natSink.dispose();
natSink = null;
}
pipeline.dispose();
pipeline = null;
parent.g.removeCache(this);
parent.unregisterMethod("dispose", this);
parent.unregisterMethod("post", this);
}
}
/**
* Finalizer of the class.
*/
protected void finalize() throws Throwable {
try {
dispose();
} finally {
super.finalize();
}
}
/**
* ( begin auto-generated from Capture_available.xml )
*
* Returns "true" when a new video frame is available to read.
*
* ( end auto-generated )
*
* @webref capture
* @brief Returns "true" when a new video frame is available to read
*/
public boolean available() {
return available;
}
/**
* ( begin auto-generated from Capture_start.xml )
*
* Starts capturing frames from the selected device.
*
* ( end auto-generated )
*
* @webref capture
* @brief Starts capturing frames from the selected device
*/
public void start() {
boolean init = false;
if (!pipelineReady) {
initPipeline();
init = true;
}
capturing = true;
pipeline.play();
if (init) {
checkResIsValid();
}
}
/**
* ( begin auto-generated from Capture_stop.xml )
*
* Stops capturing frames from an attached device.
*
* ( end auto-generated )
*
* @webref capture
* @brief Stops capturing frames from an attached device
*/
public void stop() {
if (!pipelineReady) {
initPipeline();
}
capturing = false;
pipeline.stop();
pipeline.getState();
}
/**
* ( begin auto-generated from Capture_read.xml )
*
* Reads the current video frame.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* This method() and invokeEvent() are now synchronized, so that invokeEvent()
* can't be called whilst we're busy reading. Problematic frame error
* fixed by Charl P. Botha <charlbotha.com>
*
* @webref capture
* @brief Reads the current video frame
*/
public synchronized void read() {
if (frameRate < 0) {
// Framerate not set yet, so we obtain from stream,
// which is already playing since we are in read().
frameRate = getSourceFrameRate();
}
if (useBufferSink) { // The native buffer from gstreamer is copied to the buffer sink.
outdatedPixels = true;
if (natBuffer == null) {
return;
}
if (firstFrame) {
super.init(bufWidth, bufHeight, ARGB);
firstFrame = false;
}
if (bufferSink == null) {
Object cache = parent.g.getCache(this);
if (cache == null) {
return;
}
setBufferSink(cache);
getSinkMethods();
}
ByteBuffer byteBuffer = natBuffer.getByteBuffer();
try {
sinkCopyMethod.invoke(bufferSink,
new Object[] { natBuffer, byteBuffer, bufWidth, bufHeight });
} catch (Exception e) {
e.printStackTrace();
}
natBuffer = null;
} else { // The pixels just read from gstreamer are copied to the pixels array.
if (copyPixels == null) {
return;
}
if (firstFrame) {
super.init(bufWidth, bufHeight, RGB);
firstFrame = false;
}
int[] temp = pixels;
pixels = copyPixels;
updatePixels();
copyPixels = temp;
}
available = false;
newFrame = true;
}
public synchronized void loadPixels() {
super.loadPixels();
if (useBufferSink) {
if (natBuffer != null) {
// This means that the OpenGL texture hasn't been created so far (the
// video frame not drawn using image()), but the user wants to use the
// pixel array, which we can just get from natBuffer.
IntBuffer buf = natBuffer.getByteBuffer().asIntBuffer();
buf.rewind();
buf.get(pixels);
Video.convertToARGB(pixels, width, height);
} else if (sinkGetMethod != null) {
try {
// sinkGetMethod will copy the latest buffer to the pixels array,
// and the pixels will be copied to the texture when the OpenGL
// renderer needs to draw it.
sinkGetMethod.invoke(bufferSink, new Object[] { pixels });
} catch (Exception e) {
e.printStackTrace();
}
}
outdatedPixels = false;
}
}
public int get(int x, int y) {
if (outdatedPixels) loadPixels();
return super.get(x, y);
}
protected void getImpl(int sourceX, int sourceY,
int sourceWidth, int sourceHeight,
PImage target, int targetX, int targetY) {
if (outdatedPixels) loadPixels();
super.getImpl(sourceX, sourceY, sourceWidth, sourceHeight,
target, targetX, targetY);
}
////////////////////////////////////////////////////////////
// List methods.
/**
* ( begin auto-generated from Capture_list.xml )
*
* Gets a list of all available capture devices such as a camera. Use
* <b>print()</b> to write the information to the text window.
*
* ( end auto-generated )
*
* @webref capture
* @brief Gets a list of all available capture devices such as a camera
*/
static public String[] list() {
if (devicePropertyName.equals("")) {
return list(sourceElementName, indexPropertyName);
} else {
return list(sourceElementName, devicePropertyName);
}
}
static protected String[] list(String sourceName, String propertyName) {
Video.init();
ArrayList<String> devices = listDevices(sourceName, propertyName);
ArrayList<String> configList = new ArrayList<String>();
for (String device: devices) {
ArrayList<String> resolutions = listResolutions(sourceName, propertyName,
device);
if (0 < resolutions.size()) {
for (String res: resolutions) {
configList.add("name=" + device + "," + res);
}
} else {
configList.add("name=" + device);
}
}
String[] configs = new String[configList.size()];
for (int i = 0; i < configs.length; i++) {
configs[i] = configList.get(i);
}
return configs;
}
static protected ArrayList<String> listDevices(String sourceName,
String propertyName) {
ArrayList<String> devices = new ArrayList<String>();
try {
// Using property-probe interface
Element videoSource = ElementFactory.make(sourceName, "Source");
PropertyProbe probe = PropertyProbe.wrap(videoSource);
if (probe != null) {
Property property = probe.getProperty(propertyName);
if (property != null) {
Object[] values = probe.getValues(property);
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String) {
devices.add((String)values[i]);
} else if (values[i] instanceof Integer) {
devices.add(((Integer)values[i]).toString());
}
}
}
}
}
} catch (IllegalArgumentException e) {
if (PApplet.platform == LINUX) {
// Linux hack to detect currently connected cameras
// by looking for device files named /dev/video0, /dev/video1, etc.
devices = new ArrayList<String>();
String dir = "/dev";
File libPath = new File(dir);
String[] files = libPath.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (-1 < files[i].indexOf("video")) {
devices.add("/dev/" + files[i]);
}
}
}
} else {
PGraphics.showWarning("The capture plugin does not support " +
"device query!");
devices = new ArrayList<String>();
}
}
return devices;
}
static protected ArrayList<String> listResolutions(String sourceName,
String propertyName,
Object propertyValue) {
// Creating temporary pipeline so that we can query
// the resolutions supported by the device.
Pipeline testPipeline = new Pipeline("test");
Element source = ElementFactory.make(sourceName, "source");
source.set(propertyName, propertyValue);
BufferDataAppSink sink = new BufferDataAppSink("sink", "",
new BufferDataAppSink.Listener() {
public void bufferFrame(int w, int h, Buffer buffer) { }
});
testPipeline.addMany(source, sink);
Element.linkMany(source, sink);
// Play/pause sequence (with getState() calls to to make sure
// all async operations are done) to trigger the capture momentarily
// for the device and obtain its supported resolutions.
testPipeline.play();
testPipeline.getState();
testPipeline.pause();
testPipeline.getState();
ArrayList<String> resolutions = new ArrayList<String>();
addResFromSource(resolutions, source);
testPipeline.stop();
testPipeline.getState();
if (sink != null) {
sink.removeListener();
sink.dispose();
}
testPipeline.dispose();
return resolutions;
}
static protected void addResFromSource(ArrayList<String> res, Element src) {
if (PApplet.platform == MACOSX && useResMacHack) {
addResFromSourceMacHack(res, src);
} else {
addResFromSourceImpl(res, src);
}
}
static protected void addResFromSourceImpl(ArrayList<String> res,
Element src) {
for (Pad pad : src.getPads()) {
Caps caps = pad.getCaps();
int n = caps.size();
for (int i = 0; i < n; i++) {
Structure str = caps.getStructure(i);
if (!str.hasIntField("width") || !str.hasIntField("height")) continue;
int w = ((Integer)str.getValue("width")).intValue();
int h = ((Integer)str.getValue("height")).intValue();
if (PApplet.platform == WINDOWS) {
// In Windows the getValueList() method doesn't seem to
// return a valid list of fraction values, so working on
// the string representation of the caps structure.
addResFromString(res, str.toString(), w, h);
} else {
addResFromStructure(res, str, w, h);
}
}
}
}
// The problem on OSX, at least when using qtkitvideosrc, is that it is only
// possible to obtain a single supported caps, the native maximum, using
// getNegotiatedCaps. getCaps() just gives the maximum possible ranges that
// are useless to build a list of supported resolutions. Using the fact that
// QTKit allows to capture streams at arbitrary resolutions, then the list is
// faked by repeatedly dividing the maximum by 2 until the width becomes too
// small (or not divisible by 2).
static protected void addResFromSourceMacHack(ArrayList<String> res,
Element src) {
for (Pad pad : src.getPads()) {
Caps caps = pad.getNegotiatedCaps();
int n = caps.size();
if (0 < n) {
Structure str = caps.getStructure(0);
if (!str.hasIntField("width") || !str.hasIntField("height")) return;
int w = ((Integer)str.getValue("width")).intValue();
int h = ((Integer)str.getValue("height")).intValue();
while (80 <= w) {
int num = 30;
int den = 1;
try {
Fraction fr = str.getFraction("framerate");
num = fr.numerator;
den = fr.denominator;
} catch (Exception e) {
}
res.add(makeResolutionString(w, h, num, den));
if (num == 30 && den == 1) {
// Adding additional framerates to allow for slower capture. Again,
// QTKit can output frames at arbitrary rates.
res.add(makeResolutionString(w, h, 15, 1));
res.add(makeResolutionString(w, h, 1, 1));
}
if (w % 2 == 0 && h % 2 == 0) {
w /= 2;
h /= 2;
} else {
break;
}
}
}
}
}
static protected void addResFromString(ArrayList<String> res, String str,
int w, int h) {
int n0 = str.indexOf("framerate=(fraction)");
if (-1 < n0) {
String temp = str.substring(n0 + 20, str.length());
int n1 = temp.indexOf("[");
int n2 = temp.indexOf("]");
if (-1 < n1 && -1 < n2) {
// A list of fractions enclosed between '[' and ']'
temp = temp.substring(n1 + 1, n2);
String[] fractions = temp.split(",");
for (int k = 0; k < fractions.length; k++) {
String fpsStr = fractions[k].trim();
res.add(makeResolutionString(w, h, fpsStr));
}
} else {
// A single fraction
int n3 = temp.indexOf(",");
int n4 = temp.indexOf(";");
if (-1 < n3 || -1 < n4) {
int n5 = -1;
if (n3 == -1) {
n5 = n4;
} else if (n4 == -1) {
n5 = n3;
} else {
n5 = PApplet.min(n3, n4);
}
temp = temp.substring(0, n5);
String fpsStr = temp.trim();
res.add(makeResolutionString(w, h, fpsStr));
}
}
}
}
static protected void addResFromStructure(ArrayList<String> res,
Structure str, int w, int h) {
boolean singleFrac = false;
try {
Fraction fr = str.getFraction("framerate");
res.add(makeResolutionString(w, h, fr.numerator, fr.denominator));
singleFrac = true;
} catch (Exception e) {
}
if (!singleFrac) {
ValueList flist = null;
try {
flist = str.getValueList("framerate");
} catch (Exception e) {
}
if (flist != null) {
// All the framerates are put together, but this is not
// entirely accurate since there might be some of them
// that work only for certain resolutions.
for (int k = 0; k < flist.getSize(); k++) {
Fraction fr = flist.getFraction(k);
res.add(makeResolutionString(w, h, fr.numerator, fr.denominator));
}
}
}
}
static protected String makeResolutionString(int width, int height, int
fpsNumerator,
int fpsDenominator) {
String res = "size=" + width + "x" + height + ",fps=" + fpsNumerator;
if (fpsDenominator != 1) {
res += "/" + fpsDenominator;
}
return res;
}
static protected String makeResolutionString(int width, int height,
String fpsStr) {
String res = "size=" + width + "x" + height;
String[] parts = fpsStr.split("/");
if (parts.length == 2) {
int fpsNumerator = PApplet.parseInt(parts[0]);
int fpsDenominator = PApplet.parseInt(parts[1]);
res += ",fps=" + fpsNumerator;
if (fpsDenominator != 1) {
res += "/" + fpsDenominator;
}
}
return res;
}
protected void checkResIsValid() {
ArrayList<String> resolutions = new ArrayList<String>();
addResFromSource(resolutions, sourceElement);
boolean valid = resolutions.size() == 0;
for (String res: resolutions) {
if (validRes(res)) {
valid = true;
break;
}
}
if (!valid) {
String fpsStr = "";
if (!frameRateString.equals("")) {
fpsStr = ", " + frameRateString + "fps";
}
throw new RuntimeException("The requested resolution of " + reqWidth +
"x" + reqHeight + fpsStr +
" is not supported by the selected capture " +
"device.\n");
}
}
protected void checkValidDevices(String src) {
ArrayList<String> devices;
if (devicePropertyName.equals("")) {
devices = listDevices(src, indexPropertyName);
} else {
devices = listDevices(src, devicePropertyName);
}
if (devices.size() == 0) {
throw new RuntimeException("There are no capture devices connected to " +
"this computer.\n");
}
}
protected boolean validRes(String res) {
int[] size = getSize(res);
String fps = getFrameRate(res);
return (reqWidth == 0 || reqHeight == 0 ||
(size[0] == reqWidth && size[1] == reqHeight)) &&
(frameRateString.equals("") || frameRateString.equals(fps));
}
////////////////////////////////////////////////////////////
// Initialization methods.
// The main initialization here.
protected void initGStreamer(PApplet parent, int rw, int rh, String src,
String idName, Object idValue,
String fps) {
this.parent = parent;
Video.init();
checkValidDevices(src);
// register methods
parent.registerMethod("dispose", this);
parent.registerMethod("post", this);
setEventHandlerObject(parent);
pipeline = new Pipeline("Video Capture");
frameRateString = fps;
if (frameRateString.equals("")) {
frameRate = -1;
} else {
String[] parts = frameRateString.split("/");
if (parts.length == 2) {
int fpsDenominator = PApplet.parseInt(parts[0]);
int fpsNumerator = PApplet.parseInt(parts[1]);
frameRate = (float)fpsDenominator / (float)fpsNumerator;
} else if (parts.length == 1) {
frameRateString += "/1";
frameRate = PApplet.parseFloat(parts[0]);
} else {
frameRateString = "";
frameRate = -1;
}
}
reqWidth = rw;
reqHeight = rh;
sourceName = src;
sourceElement = ElementFactory.make(src, "Source");
if (idName != null && !idName.equals("")) {
sourceElement.set(idName, idValue);
}
bufWidth = bufHeight = 0;
pipelineReady = false;
}
protected void initPipeline() {
String whStr = "";
if (0 < reqWidth && 0 < reqHeight) {
whStr = "width=" + reqWidth + ", height=" + reqHeight;
} else {
PGraphics.showWarning("Resolution information not available, attempting" +
" to open the capture device at 320x240");
whStr = "width=320, height=240";
}
String fpsStr = "";
if (!frameRateString.equals("")) {
// If the framerate string is empty we left the source element
// to use the default value.
fpsStr = ", framerate=" + frameRateString;
}
if (bufferSink != null || (Video.useGLBufferSink && parent.g.isGL())) {
useBufferSink = true;
if (bufferSink != null) {
getSinkMethods();
}
if (copyMask == null || copyMask.equals("")) {
initCopyMask();
}
String caps = whStr + fpsStr + ", " + copyMask;
natSink = new BufferDataAppSink("nat", caps,
new BufferDataAppSink.Listener() {
public void bufferFrame(int w, int h, Buffer buffer) {
invokeEvent(w, h, buffer);
}
});
natSink.setAutoDisposeBuffer(false);
// No need for rgbSink.dispose(), because the addMany() doesn't increment the
// refcount of the videoSink object.
pipeline.addMany(sourceElement, natSink);
Element.linkMany(sourceElement, natSink);
} else {
Element conv = ElementFactory.make("ffmpegcolorspace", "ColorConverter");
Element videofilter = ElementFactory.make("capsfilter", "ColorFilter");
videofilter.setCaps(new Caps("video/x-raw-rgb, width=" + reqWidth +
", height=" + reqHeight +
", bpp=32, depth=24" + fpsStr));
rgbSink = new RGBDataAppSink("rgb",
new RGBDataAppSink.Listener() {
public void rgbFrame(int w, int h, IntBuffer buffer) {
invokeEvent(w, h, buffer);
}
});
// Setting direct buffer passing in the video sink.
rgbSink.setPassDirectBuffer(Video.passDirectBuffer);
// No need for rgbSink.dispose(), because the addMany() doesn't increment
// the refcount of the videoSink object.
pipeline.addMany(sourceElement, conv, videofilter, rgbSink);
Element.linkMany(sourceElement, conv, videofilter, rgbSink);
}
pipelineReady = true;
newFrame = false;
}
/**
* Uses a generic object as handler of the capture. This object should have a
* captureEvent method that receives a Capture argument. This method will
* be called upon a new frame read event.
*
*/
protected void setEventHandlerObject(Object obj) {
eventHandler = obj;
try {
captureEventMethod = obj.getClass().getMethod("captureEvent", Capture.class);
return;
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
// The captureEvent method may be declared as receiving Object, rather
// than Capture.
try {
captureEventMethod = obj.getClass().getMethod("captureEvent", Object.class);
return;
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
}