File: PsychVideoCaptureSupportGStreamer.c

package info (click to toggle)
psychtoolbox-3 3.0.9%2Bsvn2579.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 63,408 kB
  • sloc: ansic: 73,310; cpp: 11,139; objc: 3,129; sh: 1,669; python: 382; php: 272; makefile: 172; java: 113
file content (3815 lines) | stat: -rwxr-xr-x 155,660 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
/*
	PsychSourceGL/Source/Common/Screen/PsychVideoCaptureSupportGStreamer.c
 
	PLATFORMS:	
	
	GNU/Linux, Apple MacOS/X and MS-Windows.
 
	AUTHORS:
	
	Mario Kleiner           mk              mario.kleiner@tuebingen.mpg.de
 
	HISTORY:
	
	9.01.2011				Created initial version.
	8.04.2011                               Make video/audio recording work ok.
	5.06.2011                               Make video/audio recording godo enough
						for initial release on Linux.

	DESCRIPTION:
	
	This is the videocapture engine based on the free software (LGPL'ed)
	GStreamer multimedia framework. It supports video capture, sound capture and
	recording of video and/or sound.
	 
	NOTES:

	The following works well so far (tested on Linux with Webcams):
 
	* Video device enumeration and selection (tested with iSight, USB webcams, DV Firewire cams, ...)

        * Simultaneous capture from 2 video cams.

        * Videocapture -> Live texture display. All formats L, LA, RGB, RGBA, YUYV.

        * Video-only recording, also optionally combined with live texture display.

	* Video + audio recording (also with optional live display).

        * Timestamping, GetSecs or pipeline running time timebase.

        * Low latency (dropframes) capture, and non-dropframes capture.

        * Selection of resolution and framerate.

        * Definition of ROI's and application to video feed and/or video recording.

        * Video codec selection.

        * Provides interface to change camera settings like exposure time, gain, contrast, etc.

	=> Most functionality for typical everyday tasks works perfect or reasonably well.
        => Some issues for special case apps persist, as written below.

	TODO:

	The following problems/limitations exist, which need to be fixed asap:

        * Some codecs (e.g., huffyuv and h263) don't work yet. Some others show low quality or
          performance. Need to optimize parameters.

 */

#ifdef PTB_USE_GSTREAMER

#include "Screen.h"
#include <float.h>
#include "PsychVideoCaptureSupport.h"

// These are the includes for GStreamer:
#include <glib.h>
#include <gst/gst.h>
#include <gst/app/gstappsink.h>
#include <gst/interfaces/propertyprobe.h>
#include <gst/interfaces/colorbalance.h>

static psych_bool usecamerabin = TRUE;

#define PSYCH_MAX_VIDSRC    256
PsychVideosourceRecordType *devices = NULL;
int ntotal = 0;

// Record which defines all state for a capture device:
typedef struct {
	int valid;                        // Is this a valid device record? zero == Invalid.
	psych_mutex mutex;
	psych_condition condition;
	int frameAvail;                   // Number of frames in videosink.
	int preRollAvail;
	GstElement *camera;               // Ptr to a GStreamer camera object that holds the internal state for such cams.
	GMainLoop *VideoContext;          // Message bus context for delivery of status/error/warning messages by GStreamer.
	GstElement *videosink;            // Our appsink for retrieval of live video feeds --> PTB texture conversion.
	GstElement *videosource;          // The videosource, encapsulating the actual video capture device.
	GstElement *videoenc;             // Video encoder for video recording.
	GstElement *videorate_filter;     // Video framerate converter to guarantee constant framerate and a/v sync for recording.
	GstClockTime lastSavedBaseTime;   // Last time the pipeline was put into PLAYING state. Saved at StopCapture time before stop.
	int nrAudioTracks;
	int nrVideoTracks;
	int dropframes;			  // 1 == Always deliver most recent frame in FIFO, even if dropping of frames is neccessary.
	unsigned char* scratchbuffer;     // Scratch buffer for YUV->RGB conversion.
	int reqpixeldepth;                // Requested depth of single pixel in output texture.
	int pixeldepth;                   // Depth of single pixel from grabber in bits.
	int num_dmabuffers;               // Number of DMA ringbuffers to use in DMA capture.
	int nrframes;                     // Total count of decompressed images.
	double fps;                       // Acquisition framerate of capture device.
	int width;                        // Width x height of captured images from video source (prior to cropping etc.)
	int height;                       // This is effectively the configured resolution (width x height pixels) of the video source.
	int frame_width;                  // Width x height of frames returned from videosink for OpenGL texture conversion or
	int frame_height;                 // image return in raw image buffer.
	double last_pts;                  // Capture timestamp of previous frame.
	double current_pts;               // Capture timestamp of current frame.
	int current_dropped;              // Dropped count for this fetch cycle...
	int nr_droppedframes;             // Counter for dropped frames.
	int grabber_active;               // Grabber running?
	int recording_active;             // Movie file recording requested?
	unsigned int recordingflags;      // recordingflags, as passed to 'OpenCaptureDevice'.
	PsychRectType roirect;            // Region of interest rectangle - denotes subarea of full video capture area.
	double avg_decompresstime;        // Average time spent in Quicktime/Sequence Grabber decompressor.
	double avg_gfxtime;               // Average time spent in GWorld --> OpenGL texture conversion and statistics.
	int nrgfxframes;                  // Count of fetched textures.
	char* targetmoviefilename;        // Filename of a movie file to record.
	char* cameraFriendlyName;         // Camera friendly device name.
} PsychVidcapRecordType;

static PsychVidcapRecordType vidcapRecordBANK[PSYCH_MAX_CAPTUREDEVICES];
static int numCaptureRecords = 0;
static psych_bool gs_firsttime = TRUE;
double gs_startupTime = 0.0;

// Forward declaration of internal helper function:
void PsychGSDeleteAllCaptureDevices(void);
int PsychGSDrainBufferQueue(PsychVidcapRecordType* capdev, int numFramesToDrain, unsigned int flags);


/*    PsychGetGSVidcapRecord() -- Given a handle, return ptr to video capture record.
 *    --> Internal helper function of PsychVideoCaptureSupport.
 */
PsychVidcapRecordType* PsychGetGSVidcapRecord(int deviceIndex)
{
	// Sanity checks:
	if (deviceIndex < 0) {
		PsychErrorExitMsg(PsychError_user, "Invalid (negative) deviceIndex for video capture device passed!");
	}
	
	if (numCaptureRecords >= PSYCH_MAX_CAPTUREDEVICES) {
		PsychErrorExitMsg(PsychError_user, "Invalid deviceIndex for video capture device passed. Index exceeds number of registered devices!");
	}
	
	if (!vidcapRecordBANK[deviceIndex].valid) {
		PsychErrorExitMsg(PsychError_user, "Invalid deviceIndex for video capture device passed. No such device open!");
	}
	
	// Ok, we have a valid device record, return a ptr to it:
	return(&vidcapRecordBANK[deviceIndex]);
}

/* Internal: Check if GStreamer is already initialized. Initialize it,
 * if neccessary.
 */
void PsychGSCheckInit(const char* engineName)
{
	GError			*error = NULL;

	if (gs_firsttime) {
		// First time invocation:
        #if PSYCH_SYSTEM == PSYCH_WINDOWS
        // On Windows, we need to delay-load the GStreamer DLL's. This loading
        // and linking will automatically happen downstream. However, if delay loading
        // would fail, we would end up with a crash! For that reason, we try here to
        // load the DLL, just to probe if the real load/link/bind op later on will
        // likely succeed. If the following LoadLibrary() call fails and returns NULL,
        // then we know we would end up crashing. Therefore we'll output some helpful
        // error-message instead:
        if ((NULL == LoadLibrary("libgstreamer-0.10.dll")) || (NULL == LoadLibrary("libgstapp-0.10.dll"))) {
            // Failed:
            printf("\n\nPTB-ERROR: Tried to startup GStreamer. This didn't work,\n");
            printf("PTB-ERROR: because one of the required GStreamer DLL libraries failed to load. Probably because they\n");
            printf("PTB-ERROR: could not be found, could not be accessed (e.g., due to permission problems),\n");
            printf("PTB-ERROR: or they aren't installed on this machine at all.\n\n");
            printf("PTB-ERROR: Please read the online help by typing 'help GStreamer' for troubleshooting\nand installation instructions.\n\n");
			printf("PTB-ERROR: Due to failed GStreamer initialization, the %s engine is out of order.\n", engineName);
			PsychErrorExitMsg(PsychError_user, "GStreamer initialization failed due to DLL loading problems. Aborted.");
        }
        #endif

		// Initialize GStreamer:
		if(!gst_init_check(NULL, NULL, &error)) {
			if (error) {
				printf("PTB-ERROR: GStreamer initialization failed with error: %s\n", (char*) error->message);
				g_error_free(error);
			}
			else {
				printf("PTB-ERROR: GStreamer initialization failed for unknown reason\n");
			}

			printf("PTB-ERROR: Due to failed GStreamer initialization, the %s engine is out of order.\n", engineName);
			PsychErrorExitMsg(PsychError_system, "GStreamer initialization failed! Aborted.");
		}

        // gs_startupTime is added to all timestamps from GStreamer to compensate for 
        // clock zero offset wrt. to our GetSecs() time:
        if (PSYCH_SYSTEM == PSYCH_WINDOWS) {
            // Windows: Zero-Point is time of GStreamer startup aka sometime
            // during execution of gst_init_check() above. Current system time
            // is our best approximation so far:
            PsychGetAdjustedPrecisionTimerSeconds(&gs_startupTime);
        }
        else {
            // Other OS: Zero-Point of GStreamer clock is identical to Zero-Point
            // of our GetSecs() clock, so apply zero-correction:
            gs_startupTime = 0.0;
        }

        // Select opmode of GStreamers master clock:
		// We use monotonic clock on Windows and OS/X, as these correspond to the
		// clocks we use for GetSecs(), but realtime clock on Linux:
		g_object_set(G_OBJECT(gst_system_clock_obtain()), "clock-type", ((PSYCH_SYSTEM == PSYCH_LINUX) ? GST_CLOCK_TYPE_REALTIME : GST_CLOCK_TYPE_MONOTONIC), NULL);

		// Reset firsttime flag:
		gs_firsttime = FALSE;
	}	
}

/*
 *     PsychGSVideoCaptureInit() -- Initialize video capture subsystem.
 *     This routine is called by Screen's RegisterProject.c PsychModuleInit()
 *     routine at Screen load-time. It clears out the vidcapRecordBANK to
 *     bring the subsystem into a clean initial state.
 */
void PsychGSVideoCaptureInit(void)
{
	// Initialize vidcapRecordBANK with NULL-entries:
	int i;
	for (i=0; i < PSYCH_MAX_CAPTUREDEVICES; i++) {
		vidcapRecordBANK[i].valid = 0;
	}    
	numCaptureRecords = 0;
	
	return;
}

/*
 *  void PsychGSExitVideoCapture() - Shutdown handler.
 *
 *  This routine is called by Screen('CloseAll') and on clear Screen time to
 *  do final cleanup. It deletes all capture objects
 *
 */
void PsychGSExitVideoCapture(void)
{
	// Release all capture devices
	PsychGSDeleteAllCaptureDevices();

	// Shutdown GStreamer framework, release all resources.
	// This is usually not needed/used. For memory leak
	// checking only!
	if (FALSE) {
		gs_firsttime = TRUE;
		gst_deinit();
	}

	return;
}

/*
 *  PsychGSDeleteAllCaptureDevices() -- Delete all capture objects and release all associated ressources.
 */
void PsychGSDeleteAllCaptureDevices(void)
{
	int i;
	for (i=0; i<PSYCH_MAX_CAPTUREDEVICES; i++) {
		if (vidcapRecordBANK[i].valid) PsychGSCloseVideoCaptureDevice(i);
	}
	return;
}


/* Perform one context loop iteration (for bus message handling) if doWait == false,
 * or two seconds worth of iterations if doWait == true. This drives the message-bus
 * callback, so needs to be performed to get any error reporting etc.
 */
int PsychGSProcessVideoContext(GMainLoop *loop, psych_bool doWait)
{
	double tdeadline, tnow;
	PsychGetAdjustedPrecisionTimerSeconds(&tdeadline);
	tnow = tdeadline;
	tdeadline+=2.0;

	if (NULL == loop) return(0);

	while (doWait && (tnow < tdeadline)) {
		// Perform non-blocking work iteration:
		if (!g_main_context_iteration(g_main_loop_get_context(loop), false)) PsychYieldIntervalSeconds(0.010);

		// Update time:
		PsychGetAdjustedPrecisionTimerSeconds(&tnow);
	}

	// Perform one more work iteration of the event context, but don't block:
	return(g_main_context_iteration(g_main_loop_get_context(loop), false));
}

/* Initiate pipeline state changes: Startup, Preroll, Playback, Pause, Standby, Shutdown. */
static psych_bool PsychVideoPipelineSetState(GstElement* camera, GstState state, double timeoutSecs)
{
    GstState			state_pending;
    GstStateChangeReturn	rcstate;

    gst_element_set_state(camera, state);

    // Non-Blocking, async?
    if (timeoutSecs < 0) return(TRUE);
 
    // Wait for up to timeoutSecs for state change to complete or fail:
    rcstate = gst_element_get_state(camera, &state, &state_pending, (GstClockTime) (timeoutSecs * 1e9));
    switch(rcstate) {
	case GST_STATE_CHANGE_SUCCESS:
		//printf("PTB-DEBUG: Statechange completed with GST_STATE_CHANGE_SUCCESS.\n");
	break;

	case GST_STATE_CHANGE_ASYNC:
		printf("PTB-INFO: Statechange in progress with GST_STATE_CHANGE_ASYNC.\n");
	break;

	case GST_STATE_CHANGE_NO_PREROLL:
		//printf("PTB-INFO: Statechange completed with GST_STATE_CHANGE_NO_PREROLL.\n");
	break;

	case GST_STATE_CHANGE_FAILURE:
		printf("PTB-ERROR: Statechange failed with GST_STATE_CHANGE_FAILURE!\n");
		return(FALSE);
	break;

	default:
		printf("PTB-ERROR: Unknown state-change result in preroll.\n");
		return(FALSE);
    }

    return(TRUE);
}

/* Receive messages from the playback pipeline message bus and handle them: */
static gboolean PsychVideoBusCallback(GstBus *bus, GstMessage *msg, gpointer dataptr)
{
  PsychVidcapRecordType* capdev = (PsychVidcapRecordType*) dataptr;

  switch (GST_MESSAGE_TYPE (msg)) {
    case GST_MESSAGE_EOS:
	if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Videobus: Message EOS received.\n"); fflush(NULL);
    break;

    case GST_MESSAGE_WARNING: {
      gchar  *debug;
      GError *error;

      gst_message_parse_warning(msg, &error, &debug);
      if (PsychPrefStateGet_Verbosity() > 3) { 
	      printf("PTB-WARNING: GStreamer videocapture engine reports this warning:\n"
		     "             Warning from element %s: %s\n", GST_OBJECT_NAME(msg->src), error->message);
	      printf("             Additional debug info: %s.\n", (debug) ? debug : "None");
      }

      g_free(debug);
      g_error_free(error);
      break;
    }

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error(msg, &error, &debug);
      if (PsychPrefStateGet_Verbosity() > 0) { 
	      printf("PTB-ERROR: GStreamer videocapture engine reports this error:\n"
		     "           Error from element %s: %s\n", GST_OBJECT_NAME(msg->src), error->message);
	      printf("           Additional debug info: %s.\n\n", (debug) ? debug : "None");

	      // Special tips for the challenged:
	      if (strstr(error->message, "property") || (debug && strstr(debug, "property"))) {
		      // Bailed due to unsupported x264enc parameter "speed-preset". Can be solved by upgrading
		      // GStreamer or the OS or the VideoCodec= override:
		      printf("PTB-TIP: The reason this failed is because your GStreamer codec installation is too outdated.\n");
		      printf("PTB-TIP: Either upgrade your GStreamer (plugin) installation to a more recent version,\n");
		      printf("PTB-TIP: or upgrade your operating system (e.g., Ubuntu 10.10 'Maverick Meercat' and later are fine).\n");
		      printf("PTB-TIP: A recent GStreamer installation is required to use all features and get optimal performance.\n");
		      printf("PTB-TIP: As a workaround, you can manually specify all codec settings, leaving out the unsupported\n");
		      printf("PTB-TIP: option. See 'help VideoRecording' on how to do that.\n\n");
	      }

	      if ((error->domain == GST_RESOURCE_ERROR) && (error->code != GST_RESOURCE_ERROR_NOT_FOUND)) {
		      printf("           This means that there was some problem with opening the video device (permissions etc.).\n\n");
	      }

	      if ((error->domain == GST_RESOURCE_ERROR) && (error->code == GST_RESOURCE_ERROR_NOT_FOUND)) {
		      printf("           This means that no such video device with the given name could be found.\n\n");
	      }
      }

      g_free(debug);
      g_error_free(error);
      break;
    }

    default:
      break;
  }

  return TRUE;
}


/* Called at each end-of-stream event at end of playback: */
static void PsychEOSCallback(GstAppSink *sink, gpointer user_data)
{
	PsychVidcapRecordType* capdev = (PsychVidcapRecordType*) user_data;

	PsychLockMutex(&capdev->mutex);
	printf("PTB-DEBUG: Videosink reached EOS.\n");
	PsychUnlockMutex(&capdev->mutex);

	return;
}

static void PsychProbeBufferProps(GstBuffer *videoBuffer, int *w, int *h, double *fps)
{
	GstCaps                *caps;
	GstStructure	       *str;
	gint		       rate1, rate2;
	rate1 = rate2 = 0;
	str = NULL;
    
	if (videoBuffer) {
		caps = gst_buffer_get_caps(videoBuffer);
		if (caps) str = gst_caps_get_structure(caps, 0);
		if (fps) {
			if (str) gst_structure_get_fraction(str, "framerate", &rate1, &rate2);
			if (rate2 > 0) {
				*fps = ((double) rate1) / ((double) rate2);
			} else {
				*fps = 0.0;
			}
		}
		if (w && str) gst_structure_get_int(str,"width", w);
		if (h && str) gst_structure_get_int(str,"height", h);
		if (caps) gst_caps_unref(caps);
	}

	return;
}

/* Called whenever pipeline goes into pause mode.
 * Signals/handles arrival of preroll buffers. Used to detect/signal when
 * new videobuffers are available in non-playback mode, when device becomes ready.
 */
static GstFlowReturn PsychNewPrerollCallback(GstAppSink *sink, gpointer user_data)
{
	GstBuffer              *videoBuffer;

	PsychVidcapRecordType* capdev = (PsychVidcapRecordType*) user_data;

	PsychLockMutex(&capdev->mutex);
	videoBuffer = gst_app_sink_pull_preroll(GST_APP_SINK(capdev->videosink));
	if (videoBuffer) {
		PsychProbeBufferProps(videoBuffer, NULL, NULL, &capdev->fps);
	}

	if (PsychPrefStateGet_Verbosity() > 5) {
		printf("PTB-DEBUG: New PrerollBuffer received. fps = %f\n", capdev->fps);
		fflush(NULL);
	}

	capdev->preRollAvail++;

	PsychUnlockMutex(&capdev->mutex);

	return(GST_FLOW_OK);
}

/* Called whenever pipeline is in active playback and a new video frame arrives.
 * Used to detect/signal when new videobuffers are available in playback mode.
 */
static GstFlowReturn PsychNewBufferCallback(GstAppSink *sink, gpointer user_data)
{
	PsychVidcapRecordType* capdev = (PsychVidcapRecordType*) user_data;

	PsychLockMutex(&capdev->mutex);
	capdev->frameAvail++;
	if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: New Buffer received. %i\n", capdev->frameAvail);
	PsychSignalCondition(&capdev->condition);
	PsychUnlockMutex(&capdev->mutex);

	return(GST_FLOW_OK);
}

/* Not used by us, but needs to be defined as no-op anyway: */
static GstFlowReturn PsychNewBufferListCallback(GstAppSink *sink, gpointer user_data)
{
	PsychVidcapRecordType* capdev = (PsychVidcapRecordType*) user_data;

	PsychLockMutex(&capdev->mutex);
	//printf("PTB-DEBUG: New Bufferlist received.\n");
	PsychUnlockMutex(&capdev->mutex);

	return(GST_FLOW_OK);
}

/* Not used by us, but needs to be defined as no-op anyway: */
static void PsychDestroyNotifyCallback(gpointer user_data)
{
	return;
}

static GstAppSinkCallbacks videosinkCallbacks = {
    PsychEOSCallback,
    PsychNewPrerollCallback,
    PsychNewBufferCallback,
    PsychNewBufferListCallback
};

/*
 *  PsychGSCloseVideoCaptureDevice() -- Close a capture device and release all associated ressources.
 */
void PsychGSCloseVideoCaptureDevice(int capturehandle)
{
	// Retrieve device record for handle:
	PsychVidcapRecordType* capdev = PsychGetGSVidcapRecord(capturehandle);

	// Make sure GStreamer is ready:
	PsychGSCheckInit("videocapture");

	if (capdev->camera) {
		// Stop capture immediately if it is still running:
		PsychGSVideoCaptureRate(capturehandle, 0, 0, NULL);
	
		// Close & Shutdown camera, release ressources:
		// Stop video capture immediately:
		PsychVideoPipelineSetState(capdev->camera, GST_STATE_NULL, 20.0);

		// Delete camera for this handle:
		gst_object_unref(GST_OBJECT(capdev->camera));
		capdev->camera=NULL;
	}

	// Delete video context:
	if (capdev->VideoContext) g_main_loop_unref(capdev->VideoContext);
	capdev->VideoContext = NULL;
	
	PsychDestroyMutex(&capdev->mutex);
	PsychDestroyCondition(&capdev->condition);
	
	// Was our videosink (aka appsink) detached during device operation,
	// because videorecording was active but live feedback disabled, i.e.,
	// a fakesink was attached to camerabin? If so then camerabin didn't
	// own our videosink at destruction time and didn't auto-delete it.
	// We need to manually delete our orphaned videosink:
	if ((capdev->recording_active) && (capdev->recordingflags & 4) && (capdev->videosink)) {
		gst_object_unref(GST_OBJECT(capdev->videosink));
	}
	capdev->videosink = NULL;

	if (capdev->targetmoviefilename) free(capdev->targetmoviefilename);
	capdev->targetmoviefilename = NULL;

	if (capdev->cameraFriendlyName) free(capdev->cameraFriendlyName);
	capdev->cameraFriendlyName = NULL;

	// Invalidate device record to free up this slot in the array:
	capdev->valid = 0;
    
	// Decrease counter of open capture devices:
	if (numCaptureRecords>0) numCaptureRecords--;
	
	// Done.
	return;
}

/* Helper routine for PsychGSEnumerateVideoSources()
 *
 * Probes video source plugin 'srcname' [with class index 'classIndex' and
 * name 'className', using the property 'devHandlePropName' and probe strategy
 * as given by 'flags'. Adds all detected video input devices for that plugin
 * to the global 'devices' array and increases ntotal count accordingly.
 */
void PsychGSEnumerateVideoSourceType(const char* srcname, int classIndex, const char* className, const char* devHandlePropName, unsigned int flags)
{
	int					i, n;
	char				port_str[64];
	char				class_str[64];
	int					inputIndex;
	GstElement			*videosource = NULL;
	GstPropertyProbe	*probe = NULL;
	GValueArray			*viddevs = NULL;
	GValue				*dev = NULL;
	char				*device_name = NULL;
	gchar               *pstring = NULL;
	psych_uint64		deviceURI = 0;
	
	// Info to the user:
	if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to probe %s as video source...\n", srcname);
	
	// Create video source plugin, define class name:
	videosource = gst_element_factory_make(srcname, "ptb_videosource");
	sprintf(class_str, "%s", className);

	// Nothing to do if no such video plugin available:
	if (!videosource) return;

	// No property probe interface for dc1394src, but "enumeration by trying" requested?
	// This is what we need to do for IIDC IEEE-1394 video sources via the dc1394src,
	// as it doesn't support property probe interface:
	if (!strcmp(srcname, "dc1394src")) {
		// Try a reasonable range of cameras, e.g., up to 10 cameras:
		n = 0;
		for (i = 0; i < 100; i++) {
			// Set suspected camera id (select i'th camera on bus):
			g_object_set(G_OBJECT(videosource), devHandlePropName, i, NULL);
			// Try to set it to "paused" state, which should fail if no such
			// camera is connected:
			if (gst_element_set_state(videosource, GST_STATE_PAUSED) == GST_STATE_CHANGE_FAILURE) {
				// No such camera connected. Game over, no need to probe further non-existent cams:
				if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: No camera %i connected to IIDC-1394 bus. Probe finished.\n", i);
				break;
			}

			// i'th camera exists. Probe and assign:
			inputIndex = i;
			devices[ntotal].deviceIndex = classIndex * 10000 + inputIndex;
			devices[ntotal].classIndex = classIndex;
			devices[ntotal].inputIndex = inputIndex;
			sprintf(devices[ntotal].deviceClassName, "%s", className);
			sprintf(devices[ntotal].deviceHandle, "%i", inputIndex);
			sprintf(devices[ntotal].deviceSelectorProperty, "%s", devHandlePropName);
			sprintf(devices[ntotal].deviceVideoPlugin, "%s", srcname);
			sprintf(devices[ntotal].deviceName, "%i", inputIndex);
			sprintf(devices[ntotal].devicePath, "%i", inputIndex);
			sprintf(devices[ntotal].device, "%i", inputIndex);
			devices[ntotal].deviceURI = inputIndex;

			ntotal++;
			n++;

			// Reset this cam:
			gst_element_set_state(videosource, GST_STATE_READY);

			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: %i'th IIDC-1394 camera enumerated.\n", inputIndex);
		}

		// Release videosource:
		gst_element_set_state(videosource, GST_STATE_NULL);
		gst_object_unref(GST_OBJECT(videosource));
	
		// Any success?
		if (n == 0) {
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: No video devices to enumerate for plugin '%s'.\n", class_str);
		}

		return;
	}

	// Generate property probe for videosource:
	// Make sure videosource implements property probe interface to avoid useless warning clutter,
	// unless on Linux, where this query actually causes an assertion on some GStreamer versions...
	if ((PSYCH_SYSTEM == PSYCH_LINUX) || gst_element_implements_interface(videosource, GST_TYPE_PROPERTY_PROBE)) {
		probe = GST_PROPERTY_PROBE(videosource);
	}
	else {
		probe = NULL;
	}
	
	if (probe) {
		if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Probing '%s' property...\n", devHandlePropName);
		viddevs = gst_property_probe_probe_and_get_values_name(probe, devHandlePropName);

		if (viddevs) {
			// Assign count of available devices:
			n = viddevs->n_values;
			
			// Iterate all available devices:
			for(i = 0; i < n; i++) {
				// Get device handle:
				dev = g_value_array_get_nth(viddevs, i);
				if (G_VALUE_HOLDS_STRING(dev)) {
					sprintf(port_str, "%s", (const char*) g_value_get_string(dev));

					// Select it for further probing:
					g_object_set(G_OBJECT(videosource), devHandlePropName, port_str, NULL);
				}

				if (G_VALUE_HOLDS_UINT64(dev)) {
					deviceURI = g_value_get_uint64(dev);

					// Select it for further probing:
					g_object_set(G_OBJECT(videosource), devHandlePropName, deviceURI, NULL);
					sprintf(port_str, "%llu", deviceURI);
				}

				inputIndex = i;
				devices[ntotal].deviceIndex = classIndex * 10000 + inputIndex;
				devices[ntotal].classIndex = classIndex;
				devices[ntotal].inputIndex = inputIndex;
				sprintf(devices[ntotal].deviceClassName, "%s", className);
				sprintf(devices[ntotal].deviceHandle, "%s", port_str);
				sprintf(devices[ntotal].deviceSelectorProperty, "%s", devHandlePropName);
				sprintf(devices[ntotal].deviceVideoPlugin, "%s", srcname);

				// Query and assign device specific parameters:
				pstring = NULL;
				if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device")) {
					g_object_get(G_OBJECT(videosource), "device", &pstring, NULL);
				}
				
				if (pstring) {
					sprintf(devices[ntotal].device, "%s", pstring);
					g_free(pstring);
				}
				else {
					sprintf(devices[ntotal].device, "%s", port_str);
				}
				
				pstring = NULL;
				if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device-path")) {
					g_object_get(G_OBJECT(videosource), "device-path", &pstring, NULL);
				}
				
				if (pstring) {
					sprintf(devices[ntotal].devicePath, "%s", pstring);
					g_free(pstring);
				}
				else {
					sprintf(devices[ntotal].devicePath, "%s", port_str);
				}
				
				pstring = NULL;
				if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device-name")) {
					g_object_get(G_OBJECT(videosource), "device-name", &pstring, NULL);
				}
				
				if (pstring) {
					sprintf(devices[ntotal].deviceName, "%s", pstring);
					g_free(pstring);
				}
				else {
					sprintf(devices[ntotal].deviceName, "%s", port_str);
				}

				pstring = NULL;
				if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "guid")) {
					g_object_get(G_OBJECT(videosource), "guid", &deviceURI, NULL);
					devices[ntotal].deviceURI = deviceURI;
				} else {
					devices[ntotal].deviceURI = 0;
				}

				pstring = NULL;
				
				// Probe next device...
				ntotal++;
				
				if (ntotal >= PSYCH_MAX_VIDSRC) {
					printf("PTB-WARNING: Maximum number of allowable video sourced during enumeration %i exceeded! Aborting enumeration.\n", PSYCH_MAX_VIDSRC);
					break;
				}
			}

			g_value_array_free(viddevs);
		}
		else {
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Video plugin '%s' doesn't provide any video devices to enumerate.\n", class_str);
		}
	}
	else {
		if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Video plugin '%s' doesn't support probing. No video devices to enumerate for this plugin.\n", class_str);
	}

	// Release videosource:
	gst_element_set_state(videosource, GST_STATE_NULL);
	gst_object_unref(GST_OBJECT(videosource));
	
	return;
}

/* PsychGSEnumerateVideoSources(int outPos, int deviceIndex);  -- Internal.
 *
 * Enumerates all connected and supported video sources into an internal
 * array "devices".
 *
 * If deviceIndex >= 0 : Returns pointer to PsychVideosourceRecordType struct
 *                       with info about the detected device with index 'deviceIndex'
 *                       or NULL if no such device exists. The pointer is valid until
 *                       the Screen module returns control to the runtime - then it
 *                       will get deallocated and must not be accessed anymore!
 *
 * If deviceIndex < 0 : Returns NULL to caller, returns a struct array to runtime
 *                      environment return argument position 'outPos' with all info
 *                      about the detected sources.
 */
PsychVideosourceRecordType* PsychGSEnumerateVideoSources(int outPos, int deviceIndex)
{
	PsychGenericScriptType 	*devs;
	const char *FieldNames[]={"DeviceIndex", "ClassIndex", "InputIndex", "ClassName", "InputHandle", "Device", "DevicePath", "DeviceName", "GUID", "DevicePlugin", "DeviceSelectorProperty" };

	int					i, n;
	char				port_str[64];
	char				class_str[64];
	int					inputIndex;
	GstElement			*videosource = NULL;
	GstPropertyProbe	*probe = NULL;
	GValueArray			*viddevs = NULL;
	GValue				*dev = NULL;
	char				*device_name = NULL;
	gchar               *pstring = NULL;
	PsychVideosourceRecordType *mydevice = NULL;
	
	// Make sure GStreamer is ready:
	PsychGSCheckInit("videocapture");

	// Allocate temporary space for enumerated devices:
	devices = (PsychVideosourceRecordType*) PsychCallocTemp(PSYCH_MAX_VIDSRC, sizeof(PsychVideosourceRecordType));
	ntotal  = 0;

	// Linux specific setup path:
	if (PSYCH_SYSTEM == PSYCH_LINUX) {
		// Try Video4Linux-II camera source:
		PsychGSEnumerateVideoSourceType("v4l2camsrc", 1, "Video4Linux2-CameraSource", "device", 0);

		// Try standard Video4Linux-II source:
		PsychGSEnumerateVideoSourceType("v4l2src", 2, "Video4Linux2", "device", 0);
	}

	if (PSYCH_SYSTEM == PSYCH_WINDOWS) {
		// Try Windows kernel streaming source:
		PsychGSEnumerateVideoSourceType("ksvideosrc", 1, "Windows WDM kernel streaming", "device-name", 0);

		// Use DirectShow to probe:
		PsychGSEnumerateVideoSourceType("dshowvideosrc", 2, "DirectShow", "device-name", 0);
	}
	
	if (PSYCH_SYSTEM == PSYCH_OSX) {
		// Try OSX Quicktime sequence grabber video source:
		PsychGSEnumerateVideoSourceType("osxvideosrc", 1, "OSXQuicktimeSequenceGrabber", "device", 0);
	}
	
	// Try DV-Cameras:
	PsychGSEnumerateVideoSourceType("dv1394src", 5, "DV1394", "guid", 0);
	
	// Try HDV-Cameras:
	PsychGSEnumerateVideoSourceType("hdv1394src", 6, "HDV1394", "guid", 0);
	
	// Try IIDC-1394 Cameras:
	// Does not work, no property probe interface:
	PsychGSEnumerateVideoSourceType("dc1394src", 7, "1394-IIDC", "camera-number", 1);

	if (ntotal <= 0) {
		if (PsychPrefStateGet_Verbosity() > 4) {
            printf("PTB-INFO: Could not detect any supported video devices on this system.\n");
            printf("PTB-INFO: Trying to fake an auto-detected default device...\n");
        }
        
        // Create a fake entry for the autovideosrc:
        devices[0].deviceIndex = 0;
        sprintf(devices[0].deviceVideoPlugin, "autovideosrc");
        sprintf(devices[0].deviceSelectorProperty, "");
        sprintf(devices[0].deviceHandle, "");
        ntotal= 1;
        return(&devices[0]);
	}

    // Add fake entry for deviceIndex zero, as a copy of the first real entry:
    memcpy(&devices[ntotal], &devices[0], sizeof(PsychVideosourceRecordType));
    devices[ntotal].deviceIndex = 0;
    ntotal++;
    
	// Have enumerated devices:
	if (deviceIndex >= 0) {
		// Yes: Return device name for that index:
		for (i=0; i < ntotal; i++) {
			if (devices[i].deviceIndex == deviceIndex) {
				mydevice = &devices[i];
				break;
			}
		}
	}
	else {
		// No: Code wants us to return struct array with all enumerated
		// devices to userspace:
		
		// Create output struct array with n output slots:
		PsychAllocOutStructArray(outPos, TRUE, ntotal, 11, FieldNames, &devs);
		
		// Iterate all available devices:
		for(i = 0; i < ntotal; i++) {
			PsychSetStructArrayDoubleElement("DeviceIndex", i, devices[i].deviceIndex, devs);
			PsychSetStructArrayDoubleElement("ClassIndex", i, devices[i].classIndex, devs);
			PsychSetStructArrayDoubleElement("InputIndex", i, devices[i].inputIndex, devs);
			PsychSetStructArrayStringElement("ClassName", i, devices[i].deviceClassName , devs);
			PsychSetStructArrayStringElement("InputHandle", i, devices[i].deviceHandle, devs);
			PsychSetStructArrayStringElement("Device", i, devices[i].device, devs);
			PsychSetStructArrayStringElement("DevicePath", i, devices[i].devicePath, devs);
			PsychSetStructArrayStringElement("DeviceName", i, devices[i].deviceName, devs);
			PsychSetStructArrayStringElement("GUID", i,  (devices[i].deviceURI > 0) ? devices[i].deviceHandle : "0", devs);
			PsychSetStructArrayStringElement("DevicePlugin", i, devices[i].deviceVideoPlugin, devs);
			PsychSetStructArrayStringElement("DeviceSelectorProperty", i, devices[i].deviceSelectorProperty, devs);
		}
	}

	// Done. Return device struct if assigned:
	return(mydevice);
}

psych_bool PsychGSGetResolutionAndFPSForSpec(PsychVidcapRecordType *capdev, int* width, int* height, double* fps, int reqdepth)
{
	GstCaps                 *caps = NULL;
	GstStructure		*str;
	gint			qwidth, qheight;
	gint                    qbpp;
	gint			rate1 = 0, rate2 = 1;
	gint			twidth = -1, theight = -1;
	gint                    maxpixelarea = -1;
	double                  tfps = 0.0;
	int			i;

	if (!usecamerabin) {
		// No camerabin, no way to query this stuff. Just fail
		printf("PTB-BUG: PsychGSGetResolutionAndFPSForSpec() called while !usecamerabin !?! Returning failure.\n");
		return(FALSE);
	}

	// Camerabin, we can actually enumerate and match.

	// Query caps of videosource and extract supported video capture modes:
	g_object_get(G_OBJECT(capdev->camera), "video-source-caps", &caps, NULL);

	if (caps) {
		if (PsychPrefStateGet_Verbosity() > 4)
			printf("PTB-DEBUG: Videosource caps are: %" GST_PTR_FORMAT "\n\n", caps);

		// Iterate through all supported video capture modes:
		for (i = 0; i < gst_caps_get_size(caps); i++) {
			str = gst_caps_get_structure(caps, i);

			gst_structure_get_int(str, "width", &qwidth);
			gst_structure_get_int(str, "height", &qheight);
			gst_structure_get_int(str, "bpp", &qbpp);
			gst_structure_get_fraction(str, "framerate", &rate1, &rate2);
			// if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Videosource cap %i: w = %i h = %i fps = %f\n", i, qwidth, qheight, (float) rate1 / (float) rate2);
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Videosource cap %i: w = %i h = %i.\n", i, qwidth, qheight);

			// Check for matching pixel color resolution, reject too low modes:
			// TODO: Not yet implemented, don't know if it makes sense at all, as the
			// colorspace converters can always take care of this.

			// Is this detection of default resolution, or validation of a
			// given resolution?
			if ((*width == -1) && (*height == -1)) {
				// Auto-Detection of optimal default resolution.
				// Need to find the one with highest resolution (== pixel area):
				if (qwidth * qheight > maxpixelarea) {
					// A new favorite with max pixel area:
					maxpixelarea = qwidth * qheight;
					twidth = qwidth;
					theight = qheight;
					tfps = (double) rate1 / (double) rate2;
				}
			}
			else {
				// Validation: Reject/Skip modes which don't support requested resolution.
				if ((*width != (int) qwidth) || (*height != (int) qheight)) continue;

				// Videomode which supports this resolution. Framerate validation?
				if (*fps != -1) {
					// TODO FIXME.
				}

				// Acceptable mode for requested resolution and framerate. Set it:
				maxpixelarea = qwidth * qheight;
			        twidth = qwidth;
				theight = qheight;
				tfps = (double) rate1 / (double) rate2;
			}
		}

		gst_caps_unref(caps);

		// Any matching mode found?
		if (twidth == -1) {
			// No! The requested resolution + fps + pixelformat combo
			// is not supported:
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Could not validate video source resolution %i x %i. Returning failure.\n", *width, *height);
			return(FALSE);
		}

		// Yes. Return settings:
		*fps = tfps;
		*width = twidth;
		*height = theight;

		if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: Will use auto-detected or validated video source resolution %i x %i.\n", *width, *height);

		return(TRUE);
	} else {
		if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychGSGetResolutionAndFPSForSpec(): Capability query to video source failed! Returning failure.\n");
		return(FALSE);
	}
}

// Parse codecSpec string, check for certain element specs. If found, parse them
// and create corresponding GstElement*, otherwise return NULL.
GstElement* CreateGStreamerElementFromString(const char* codecSpec, const char* typeSpec, char* codecParams)
{
	char *codecPipelineSpec, *codecPipelineEnd;
	GstElement* element = NULL;

	if (strstr(codecSpec, typeSpec)) {
		// Find start of codec spec string:
		codecPipelineSpec = strstr(codecSpec, typeSpec);

		// Cut off the prefix:
		codecPipelineSpec += strlen(typeSpec);

		// Copy the remaining string, so we can mess with it:
		codecPipelineSpec = strdup(codecPipelineSpec);

		// Search for end-of-codecspec marker:
		codecPipelineEnd = strstr(codecPipelineSpec, ":::");

		// If any, null-terminate at start of marker:
		if (codecPipelineEnd) *codecPipelineEnd = 0;

		// codecPipelineSpec is now a null-terminated string which only
		// contains the GStreamer syntax description of the video codec and
		// its parameters.

		// Parse it and create a corresponding bin for use as encoder element:
		// Set GError* to NULL: Real men don't do error handling.
		element = gst_parse_bin_from_description((const gchar *) codecPipelineSpec, TRUE, NULL);
		if (element == NULL) {
			// Oopsie: Failed!
			if (PsychPrefStateGet_Verbosity() > 1) {
				printf("PTB-WARNING: Failed to create an encoder element of type '%s' from the following passed parameter string:\n", typeSpec);
				printf("PTB-WARNING: %s\n", codecPipelineSpec);
				printf("PTB-WARNING: Will revert to default settings for this element. This will likely fail soon...\n");
				printf("PTB-WARNING: Full parameter string was:\n");
				printf("PTB-WARNING: %s\n", codecSpec);
			}
		}
		else {
			// Success!
			if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Element '%s' created from spec '%s'.\n", typeSpec, codecPipelineSpec);
		}
		sprintf(codecParams, "%s", codecPipelineSpec);
		free(codecPipelineSpec);
	}

	return(element);
}

psych_bool PsychSetupRecordingPipeFromString(PsychVidcapRecordType* capdev, char* codecSpec, char* outCodecName, psych_bool launchline)
{
	GstElement *camera = NULL;
	GstElement *some_element = NULL;
	GstElement *audio_enc = NULL;
	GstElement *audio_src = NULL;
	GstElement *muxer_elt = NULL;

	char *poption = NULL;
	char *codecName = NULL;
	char *codecSep  = NULL;
	char muxer[1000];
	char audiocodec[1000];
	char videocodec[1000];
	char codecoption[1000];
	char audiosrc[1000];

	int nrAudioChannels;
	int audioFreq;

	int interlaced = -1;
	int keyFrameInterval = -1;
	float videoQuality = -1;
	float audioQuality = -1;
	int audioBitrate = -1;
	int videoBitrate = -1;
	int bigFiles = -1;
	int fastStart = -1;
	int indexItemsSec = -1;
	int profile = -1;

	memset(muxer, 0, sizeof(muxer));
	memset(audiosrc, 0, sizeof(audiosrc));
	memset(audiocodec, 0, sizeof(audiocodec));
	memset(videocodec, 0, sizeof(videocodec));

	// Get camera object - the camerabin2:
	camera = capdev->camera;

	// Parse and assign high-level properties if any:
	codecSep = strstr(codecSpec, "Profile=");
	if (codecSep) {
		sscanf(codecSep, "Profile=%i", &profile);
	}

	codecSep = strstr(codecSpec, "Interlaced=");
	if (codecSep) {
		sscanf(codecSep, "Interlaced=%i", &interlaced);
	}

	codecSep = strstr(codecSpec, "Keyframe=");
	if (codecSep) {
		sscanf(codecSep, "Keyframe=%i", &keyFrameInterval);
	}

	// Audio bit rate in kBit/Sec
	codecSep = strstr(codecSpec, "Audiobitrate=");
	if (codecSep) {
		sscanf(codecSep, "Audiobitrate=%i", &audioBitrate);
	}

	// Video bit rate in kBit/Sec
	codecSep = strstr(codecSpec, "Videobitrate=");
	if (codecSep) {
		sscanf(codecSep, "Videobitrate=%i", &videoBitrate);
	}

	codecSep = strstr(codecSpec, "Bigfiles=");
	if (codecSep) {
		sscanf(codecSep, "Bigfiles=%i", &bigFiles);
	}

	codecSep = strstr(codecSpec, "Faststart=");
	if (codecSep) {
		sscanf(codecSep, "Faststart=%i", &fastStart);
	}

	codecSep = strstr(codecSpec, "Timeresolution=");
	if (codecSep) {
		sscanf(codecSep, "Timeresolution=%i", &indexItemsSec);
	}

	codecSep = strstr(codecSpec, "Videoquality=");
	if (codecSep) {
		sscanf(codecSep, "Videoquality=%f", &videoQuality);
	}

	codecSep = strstr(codecSpec, "Audioquality=");
	if (codecSep) {
		sscanf(codecSep, "Audioquality=%f", &audioQuality);
	}

	// Create matching video encoder for codecSpec:
	// Codecs are sorted by suitability for high quality realtime video recording, so if usercode
	// doesn't specify a codec, and thereby requests use of the recommended default codec 'DEFAULTenc',
	// we will try to choose the best codec, then on failure fallback to the 2nd best, 3rd best, etc.

	// Video encoder from parameter string?
	if ((some_element = CreateGStreamerElementFromString(codecSpec, "VideoCodec=", videocodec)) != NULL) {
		// Yes. Assign it as our encoder:
		capdev->videoenc = some_element;

		// Need to extract the actual name of the codec from the codecSpec string:
		codecName = strstr(codecSpec, "VideoCodec=");
		codecName+= strlen("VideoCodec=");
		codecName = strdup(codecName);
		codecSep = codecName;
		while ((*codecSep > 0) && (*codecSep != ' ')) codecSep++;
		*codecSep = 0;

		sprintf(outCodecName, "%s", codecName);
		free(codecName);
		codecName = NULL;
	}

	// Start with H264 encoder as default:
	if (strstr(codecSpec, "x264enc") || strstr(codecSpec, "1635148593") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "qtmux");                 // Need to use Quicktime-Multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=x264enc ");

			// Interlace flag specified?
			if (interlaced >= 0) {
				// Enable or disable handling of interlaced input video stream:
				sprintf(codecoption, "interlaced=%i ", (interlaced) ? 1 : 0);
				strcat(videocodec, codecoption);
			}

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "key-int-max=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			} else {
				// Default to a keyframe at least every 30 frames:
				strcat(videocodec, "key-int-max=30 ");
			}

			// Encoding profile specified?
			if (profile >= 0) {
				// Assign profile:
				sprintf(codecoption, "profile=%i ", profile);
				strcat(videocodec, codecoption);
			} else {
				// Default to "High" profile: 640 x 480 @ 30 fps possible:
				strcat(videocodec, "profile=3 ");
			}

			// Quality vs. Speed tradeoff specified?
			if (videoQuality >= 0) {
				// Yes: Map quality vs. speed scalar to 0-10 number for speed preset:
				if (videoQuality > 1) videoQuality = 1;

				// Speed-Quality profile set to 1 "Ultra fast".
				// (1 = "Ultra fast", 2 = "Super fast", 3 = "Very fast",  4 = "Faster", 5 = "Fast",
				//  6 = "Medium" - the default,7 = "Slow", 8 = "Slower", 9 = "Very slow")
				sprintf(codecoption, "speed-preset=%i ", (int) (videoQuality * 10.0 + 0.5));
				strcat(videocodec, codecoption);
			}
			else {
				// No: Use the fastest speed at lowest quality:
				strcat(videocodec, "speed-preset=1 ");
			}
            
			// Bitrate specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'x264enc' H.264 video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "x264enc");
		}
	}

	// Then xvidenc - MPEG4 in a AVI container: High quality, handles 640 x 480 @ 30 fps on
	// a 4 year old MacBookPro Core2Duo 2.2 Ghz with about 70% - 100% cpu load, depending on settings.
	if (strstr(codecSpec, "xvidenc") || strstr(codecSpec, "1836070006") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "avimux");                // Need to use avi-multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=xvidenc ");

			// Interlace flag specified?
			if (interlaced >= 0) {
				// Enable or disable handling of interlaced input video stream:
				sprintf(codecoption, "interlaced=%i ", (interlaced) ? 1 : 0);
				strcat(videocodec, codecoption);
			}

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "max-key-interval=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate * 1024);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'xvidenc' xvid/mpeg-4 video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "xvidenc");
		}
	}

	// ffenc_mpeg4 also creates MPEG4, but at lower quality - much more blocky etc.
	if (strstr(codecSpec, "ffenc_mpeg4") || ((strstr(codecSpec, "DEFAULTenc") || strstr(codecSpec, "1836070006")) && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "avimux");                // Need to use avi-multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=ffenc_mpeg4 ");

			// Interlace flag specified?
			if (interlaced >= 0) {
				// Enable or disable handling of interlaced input video stream:
				sprintf(codecoption, "interlaced=%i ", (interlaced) ? 1 : 0);
				strcat(videocodec, codecoption);
			}

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "max-key-interval=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate * 1024);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'ffenc_mpeg4' mpeg-4 video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "ffenc_mpeg4");
		}
	}

	// Theora + Ogg vorbis audio in .ogv container:
	if (strstr(codecSpec, "theoraenc") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=vorbisenc "); // Need to use Ogg Vorbis audio encoder.
		sprintf(muxer, "oggmux");                // Need to use Ogg-multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=theoraenc drop-frames=0 speed-level=2 ");

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "keyframe-auto=0 keyframe-force=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoQuality >= 0) {
				// Yes: Map quality vs. speed scalar to 0-63 number:
				if (videoQuality > 1) videoQuality = 1;

				sprintf(codecoption, "quality=%i ", (int) (videoQuality * 63.0 + 0.5));
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'theoraenc' video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "theoraenc");
		}
	}

	// VP-8 in WebM container:
	if (strstr(codecSpec, "vp8enc") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=vorbisenc "); // Need to use Ogg Vorbis audio encoder.
		sprintf(muxer, "webmmux");                    // Default to WebM multiplexer.

		// Need to use matroska/webm-multiplexer:
		if (strstr(codecSpec, "_matroska")) sprintf(muxer, "matroskamux");
		if (strstr(codecSpec, "_webm")) sprintf(muxer, "webmmux");

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=vp8enc ");

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "max-keyframe-distance=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoQuality >= 0) {
				// Yes: Map quality vs. speed scalar to 0-10 number:
				if (videoQuality > 1) videoQuality = 1;

				sprintf(codecoption, "quality=%i ", (int) (videoQuality * 10.0 + 0.5));
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate * 1024);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'vp8enc' VP-8 video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "vp8enc");
		}
	}

	// Raw YUV: Works, but only for fixed hard-coded size 640 x 480 by now.
	if (strstr(codecSpec, "yuvraw") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "avimux");                // Need to use AVI-Multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=capsfilter caps=\"video/x-raw-yuv, format=(fourcc)I420, width=(int)640, height=(int)480\" ");

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'capsfilter' YUV pass-through video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "yuvraw");
		}
	}

	// H263 -- Does not work well yet.
	if (strstr(codecSpec, "ffenc_h263p") || strstr(codecSpec, "1748121139") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "qtmux");                 // Need to use Quicktime-Multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=ffenc_h263p ");

			// Interlace flag specified?
			if (interlaced >= 0) {
				// Enable or disable handling of interlaced input video stream:
				sprintf(codecoption, "interlaced=%i ", (interlaced) ? 1 : 0);
				strcat(videocodec, codecoption);
			}

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "max-key-interval=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate * 1024);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'ffenc_h263p' H.263 video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "ffenc_h263p");
		}
	}

	// Raw Huffman encoded YUV -- Does not work yet.
	if (strstr(codecSpec, "huffyuv") || (strstr(codecSpec, "DEFAULTenc") && !capdev->videoenc)) {
		// Define recommended (compatible) audioencoder/muxer and their default options:
		sprintf(audiocodec, "AudioCodec=faac "); // Need to use faac MPEG-4 audio encoder.
		sprintf(muxer, "avimux");           // Need to use AVI-Multiplexer.

		// Videoencoder not yet created? If so, we have to do it now:
		if (!capdev->videoenc) {
			// Not yet created. Create full codec & option string from high level properties,
			// if any, then create based on string:
			sprintf(videocodec, "VideoCodec=ffenc_huffyuv ");

			// Keyframe interval specified?
			if (keyFrameInterval >= 0) {
				// Assign maximum distance between key frames:
				sprintf(codecoption, "gop-size=%i ", keyFrameInterval);
				strcat(videocodec, codecoption);
			}

			// Quality vs. Speed tradeoff specified?
			if (videoBitrate >= 0) {
				sprintf(codecoption, "bitrate=%i ", (int) videoBitrate * 1024);
				strcat(videocodec, codecoption);
			}

			// Create videocodec from options string:
			capdev->videoenc = CreateGStreamerElementFromString(videocodec, "VideoCodec=", videocodec);
		}

		if (!capdev->videoenc) {
			printf("PTB-WARNING: Failed to create 'ffenc_huffyuv' compressed YUV lossless video encoder! Does not seem to be installed on your system?\n");
		}
		else {
			sprintf(outCodecName, "ffenc_huffyuv");
		}
	}

	// Audio encoder from parameter string?
	if ((audio_enc = CreateGStreamerElementFromString(codecSpec, "AudioCodec=", audiocodec)) != NULL) {
		// Yes: Assign it.
	} else {
		// No: Build from preset as defined by video codec and some high level settings:

		// Audio quality flag specified?
		if (audioQuality >= 0) {
			if (audioQuality > 1) audioQuality = 1;

			if (strstr(audiocodec, "faac")) {
				// Map quality range 0.0 - 1.0 to bitrate range 0 - 320000 bits/sec:
				sprintf(codecoption, "bitrate=%i ", (int) (audioQuality * 320000));
				strcat(audiocodec, codecoption);
			}

			if (strstr(audiocodec, "vorbisenc")) {
				// Assign quality range 0.0 - 1.0 directly:
				sprintf(codecoption, "quality=%f ", audioQuality);
				strcat(audiocodec, codecoption);
			}
		}

		// Audio bitrate specified?
		if (audioBitrate >= 0) {
			if (strstr(audiocodec, "faac")) {
				sprintf(codecoption, "bitrate=%i ", audioBitrate * 1024);
				strcat(audiocodec, codecoption);
			}

			if (strstr(audiocodec, "vorbisenc")) {
				sprintf(codecoption, "managed=1 bitrate=%i ", audioBitrate * 1024);
				strcat(audiocodec, codecoption);
			}
		}

		// Create audio encoder:
		if ((audio_enc = CreateGStreamerElementFromString(audiocodec, "AudioCodec=", audiocodec)) != NULL) {
			// Yes: Assign it.
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Created audio encoder according to: %s\n", audiocodec);
		} else {
			if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Failed to create requested audio encoder [%s]! Falling back to default encoder.\n", audiocodec);
		}
	}

	// Audio source from parameter string? Most of the time usercode would not want
	// to change type/assignment/source parameters of a source. Also, the available
	// settings are common enough across sources that it doesn't make sense for us to
	// introduce our own high-level parameters. Therefore we only provide the low-level
	// interface here.
	// Interesting sources would be: alsasrc, osssrc, oss4src, pulsesrc, jackaudiosrc,
	// autoaudiosrc, gconfaudiosrc.
	//
	// Interesting settings would be:
	// device = The audio device name.
	// server = Audio server name for Jack and PulseAudio.
	// slave-method = Type of syncing to master clock.
	if ((audio_src = CreateGStreamerElementFromString(codecSpec, "AudioSource=", audiosrc)) != NULL) {
	}

	// Multiplexer from parameter string?
	if (strstr(codecSpec, "Muxer=")) {
		// Must create it without help of CreateGStreamerElementFromString() as the muxer has
		// 2 sink pads, but our method can only handle 1 sink pad. Therefore just create a
		// muxer by name, setting it to its default settings:
		poption = strstr(codecSpec, "Muxer=");
		poption+= strlen("Muxer=");

		// Store muxer name in 'muxer':
		sprintf(muxer, "%s", poption);

		// Terminate muxer string if a ::: marker is encountered:
		poption = strstr(muxer, ":::");
		if (poption) *poption = 0;

		// Build element from muxer spec:
		muxer_elt = gst_element_factory_make(muxer, "ptbvideomuxer0");
	} else {
		// As assigned by video codec init path:
		muxer_elt = gst_element_factory_make(muxer, "ptbvideomuxer0");
	}

	// Special muxer-specific setup of mux parameters:
	if (strstr(muxer, "avimux")) {
		// Big file writing support (> 2GB) is on by default. This allows to change it:
		if (bigFiles >= 0) {
			g_object_set(muxer_elt, "bigfile", (bigFiles > 0) ? 1 : 0, NULL);
			sprintf(codecoption, " bigfile=%i", (bigFiles > 0) ? 1 : 0);
			strcat(muxer, codecoption);
		}
	}
	
	if (strstr(muxer, "qtmux")) {
		// Big file writing support (> 2GB) is on by default. This allows to change it:
		if (bigFiles >= 0) {
			g_object_set(muxer_elt, "large-file", (bigFiles > 0) ? 1 : 0, NULL);
			sprintf(codecoption, " large-file=%i", (bigFiles > 0) ? 1 : 0);
			strcat(muxer, codecoption);
		} else {
			// Enforce default of "on":
			g_object_set(muxer_elt, "large-file", 1, NULL);
			sprintf(codecoption, " large-file=%i", 1);
			strcat(muxer, codecoption);
		}

		if (fastStart >= 0) {
			// Enable/Disable fast start support for low-latency start of movie playback:
			g_object_set(muxer_elt, "faststart", (fastStart > 0) ? 1 : 0, NULL);
			sprintf(codecoption, " faststart=%i", (fastStart > 0) ? 1 : 0);
			strcat(muxer, codecoption);
		}
		else {
			// Enable fast start support for low-latency start of movie playback:
            // FIXME: Unless we're on Windows where this would cause a crash in qtmux!
            // TODO: Investigate & Fix root cause. For now we just disable faststart
            // on Windows.
            fastStart = (PSYCH_SYSTEM == PSYCH_WINDOWS) ? 0 : 1;
			g_object_set(muxer_elt, "faststart", fastStart, NULL);
			sprintf(codecoption, " faststart=%i", fastStart);
			strcat(muxer, codecoption);
		}

		if (indexItemsSec >= 0) {
			// Write seek index entry for each 1/indexItemsSec of movie time:
			g_object_set(muxer_elt, "movie-timescale", indexItemsSec, NULL);
			sprintf(codecoption, " movie-timescale=%i", indexItemsSec);
			strcat(muxer, codecoption);
		} else {
			// Write seek index entry for each millisecond of movie time:
			g_object_set(muxer_elt, "movie-timescale", 1000, NULL);
			sprintf(codecoption, " movie-timescale=%i", 1000);
			strcat(muxer, codecoption);
		}
	}

	if (strstr(muxer, "matroskamux") || strstr(muxer, "webmmux")) {
		if (indexItemsSec >= 0) {
			// Write seek index entry for each 1/indexItemsSec of movie time:
			g_object_set(muxer_elt, "min-index-interval", (int)  (1e9 / indexItemsSec), NULL);
			sprintf(codecoption, " min-index-interval=%i", (int) (1e9 / indexItemsSec));
			strcat(muxer, codecoption);
		} else {
			// Write seek index entry for each millisecond (1e6 nanoseconds) of movie time:
			g_object_set(muxer_elt, "min-index-interval", (int)  1e6, NULL);
			sprintf(codecoption, " min-index-interval=%i", (int) 1e6);
			strcat(muxer, codecoption);
		}
	}

	// Still no video codec? Then this is game over: FIXME Small memory leak here on error exit.
	if (capdev->videoenc == NULL) PsychErrorExitMsg(PsychError_user, "Could not find or setup requested video codec or any fallback codec for video recording. Aborted.");
	if (!audio_enc) PsychErrorExitMsg(PsychError_user, "Could not find or setup requested audio codec for recording. Aborted.");
	if (!muxer_elt) PsychErrorExitMsg(PsychError_user, "Could not find or setup requested audio-video multiplexer for recording. Aborted.");

	if (PsychPrefStateGet_Verbosity() > 3) {
		printf("PTB-INFO: Audiosource: %s\n", audiosrc);
		printf("PTB-INFO: Audiocodec : %s\n", audiocodec);
		printf("PTB-INFO: Videocodec : %s\n", videocodec);
		printf("PTB-INFO: Multiplexer: %s\n", muxer);
	}

	if (!launchline) {
		// Attach our created objects to camerabin:
		g_object_set(camera, "video-encoder", capdev->videoenc, NULL);
		g_object_set(camera, "audio-encoder", audio_enc, NULL);
		g_object_set(camera, "video-muxer", muxer_elt, NULL);
		if (audio_src) g_object_set(camera, "audio-source", audio_src, NULL);
	} else {
		// Release our objects, we have our launch line:
		gst_object_unref(G_OBJECT(capdev->videoenc)); capdev->videoenc = NULL;
		if (audio_enc) gst_object_unref(G_OBJECT(audio_enc));
		if (audio_src) gst_object_unref(G_OBJECT(audio_src));
		if (muxer_elt) gst_object_unref(G_OBJECT(muxer_elt));

		// Build gst-launch style GStreamer pipeline spec string:

		// Special keyword for audio tracks in written movies?
		if ((poption=strstr(codecSpec, "AddAudioTrack"))) {
			// Audio and Video:
			poption+=strlen("AddAudioTrack");
			if (sscanf(poption, "=%i@%i", &nrAudioChannels, &audioFreq) != 2) {
				// Assign default 1 mono-channel count and 48 kHz frequency:
				nrAudioChannels = 1;
				audioFreq = 48000;
			}

			if (nrAudioChannels < 1 || nrAudioChannels > 256 || audioFreq < 1 || audioFreq > 200000) {
				printf("PTB-ERROR: Invalid parameters in 'AddAudioTrack='! Either %i audio channels outside valid range 1-256, or %i audioFreq outside allowable range 1 - 200000 Hz.\n",
				       nrAudioChannels, audioFreq);
				PsychErrorExitMsg(PsychError_user, "Invalid audio recording parameters provided");
			}

			// If no "AudioSource=" was provided then configure for appsrc feeding
			// from Screen('AddAudioBufferToMovie') into movie:
			if (strlen(audiosrc) == 0) sprintf(audiosrc, "appsrc name=ptbaudioappsrc do-timestamp=0 stream-type=0 max-bytes=0 block=1 is-live=0 emit-signals=0 caps=\"audio/x-raw-float, endianness=(int)1234, width=(int)32, channels=(int)%i, rate=(int)%i\" ! audioconvert ! queue", nrAudioChannels, audioFreq);

			// We add bits to feed from 'audiosrc' into 'audiocodec' into the common muxer of video and audio stream:
			sprintf(outCodecName, " %s ! ptbvideomuxer0. %s ! %s ! ptbvideomuxer0. %s name=ptbvideomuxer0 ", videocodec, audiosrc, audiocodec, muxer);            
		} else {
			// Video only:
            
			// We feed the output of 'videocodec' directly into the muxer:
			sprintf(outCodecName, " %s ! %s ", videocodec, muxer);
		}
        
		// Example launch line for audio+video recording:
		// gst-launch-0.10 -e v4l2src device=/dev/video0 ! videorate ! ffmpegcolorspace ! "video/x-raw-yuv, format=(fourcc)I420, width=(int)640, height=(int)480", framerate=15/1 ! queue ! x264enc speed-preset=1 ! muxout. autoaudiosrc ! faac ! muxout. avimux name=muxout ! filesink location=~/Desktop/record.avi
		// Example without audio, pure video:
		// gst-launch-0.10 -e v4l2src device=/dev/video0 ! videorate ! ffmpegcolorspace ! "video/x-raw-yuv, format=(fourcc)I420, width=(int)640, height=(int)480", framerate=15/1 ! queue ! x264enc speed-preset=1 ! muxout. avimux name=muxout ! filesink location=~/Desktop/record.avi
		// Better:
		// gst-launch-0.10 -e v4l2src device=/dev/video0 ! videorate ! ffmpegcolorspace ! "video/x-raw-yuv, format=(fourcc)I420, width=(int)640, height=(int)480", framerate=15/1 ! queue ! x264enc speed-preset=1 ! avimux ! filesink location=~/Desktop/record.avi
		//
		// Raw data:
		// st-launch-0.10 -e v4l2src device=/dev/video0 ! videorate ! ffmpegcolorspace ! "video/x-raw-yuv, format=(fourcc)I420, width=(int)640, height=(int)480", framerate=15/1 ! queue ! identity ! avimux ! filesink location=~/Desktop/record.avi
	}

	return(TRUE);
}

/* PsychGetCodecLaunchLineFromString() - Helper function for GStreamer based movie writing.
 *
 * Take a 'codecSpec' string with user provided codec settings string, get
 * a proper gst-launch style segment for the codecs and muxers back.
 * launchString must be preallocated and of sufficient size (approx. 1Kb).
 * Returns TRUE on success, FALSE on failure.
 */
psych_bool PsychGetCodecLaunchLineFromString(char* codecSpec, char* launchString)
{
	// Need a fake capdev to pass to PsychSetupRecordingPipeFromString():
	PsychVidcapRecordType dummydev;
	memset(&dummydev, 0, sizeof(dummydev));

	// Pass off the job and just return its results. This is shared with encoder/muxer
	// creation, setup, configuration and testing for the video recording engine:
	return(PsychSetupRecordingPipeFromString(&dummydev, codecSpec, launchString, TRUE));
}

/* CHECKED TODO
*      PsychGSOpenVideoCaptureDevice() -- Create a video capture object.
*
*      This function tries to open and initialize a connection to a camera
*      and returns the associated captureHandle for it.
*
*      slotid = Number of slot in vidcapRecordBANK[] array to use for this camera.
*      win = Pointer to window record of associated onscreen window.
*      deviceIndex = Index of the grabber device.
*      capturehandle = handle to the new capture object.
*      capturerectangle = If non-NULL a ptr to a PsychRectangle which contains the ROI for capture. Special roi [0 0 w h] selects resolution w x h on device.
*      reqdepth = Number of layers for captured output textures. (0=Don't care, 1=LUMINANCE8, 2=LUMINANCE8_ALPHA8, 3=RGB8, 4=RGBA8, 5=YCBCR)
*      num_dmabuffers = Number of buffers to queue internally before dropping buffers. Zero = Don't drop buffers, fill up whole memory if neccessary.
*      allow_lowperf_fallback = If set to 1 then PTB can use less capable fallback path on setups which don't support the 'camerabin' plugin.
*      targetmoviefilename = Filename of movie file to record (if any) if deviceIndex >=0,
*                            special spec string for a video capture device if deviceIndex < 0.
*      recordingflags = Special flags to control internal operation (harddisc recording yes/no, live video during recording?, audio recording? workarounds?)
*/
psych_bool PsychGSOpenVideoCaptureDevice(int slotid, PsychWindowRecordType *win, int deviceIndex, int* capturehandle, double* capturerectangle,
								   int reqdepth, int num_dmabuffers, int allow_lowperf_fallback, char* targetmoviefilename, unsigned int recordingflags)
{
	GstCaps                 *colorcaps, *filter_caps;
	GstElement		*camera = NULL;
	GMainLoop		*VideoContext = NULL;
	GstBus			*bus = NULL;
	GstElement              *videosink = NULL;
	GstElement              *videosource = NULL;
	GstElement              *videosource_filter = NULL;
	GstElement              *videocrop_filter = NULL;
	GstPad			*pad, *peerpad;
	GstCaps                 *caps;
	GstStructure		*str;
	gint			width, height;
	gint			rate1, rate2;
	gint			twidth, theight;
	int			i;
	char                    *codecSpec;
	char                    codecName[10000];

	PsychVidcapRecordType	*capdev = NULL;
	char			config[1000];
	char			tmpstr[1000];
	char			device_name[1000];
	char			plugin_name[1000];
	char			prop_name[1000];
	gchar                   *pstring = NULL; 
	PsychVideosourceRecordType *theDevice = NULL;
	psych_bool              overrideFrameSize = FALSE;
	
	config[0] = 0;
	tmpstr[0] = 0;
	device_name[0] = 0;
	plugin_name[0] = 0;
	prop_name[0] = 0;

	// Init capturehandle to none:
	*capturehandle = -1;
	
	// Make sure GStreamer is ready:
	PsychGSCheckInit("videocapture");
	
	// Map deviceIndex of requested video source to device name:
	if (deviceIndex >= 0) {
		// Get device name for given deviceIndex from video device
		// enumeration (or NULL if no such device):
		theDevice = PsychGSEnumerateVideoSources(-1, deviceIndex);
		if (NULL == theDevice) {
			printf("PTB-ERROR: There isn't any video capture device available for provided deviceIndex %i.\n", deviceIndex);
			PsychErrorExitMsg(PsychError_user, "Invalid deviceIndex provided. No such video source. Aborted.");
		}
		
		// Assign name:
		sprintf(device_name, "%s", theDevice->deviceHandle);
		sprintf(plugin_name, "%s", theDevice->deviceVideoPlugin);
		sprintf(prop_name, "%s", theDevice->deviceSelectorProperty);
		if (theDevice->deviceURI > 0) {
			sprintf(device_name, "%llu", theDevice->deviceURI);
		}

		if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Trying to open video capture device with deviceIndex %i [%s].\n", deviceIndex, device_name);
	}

    // Slot 'slotid' will contain the record for our new capture object:

    // Zero-out new record in video bank:
    memset(&vidcapRecordBANK[slotid], 0, sizeof(PsychVidcapRecordType));
    
    // Initialize new record:
    vidcapRecordBANK[slotid].valid = 1;
    
    // Retrieve device record for slotid:
    capdev = PsychGetGSVidcapRecord(slotid);
	
    capdev->camera = NULL;
    capdev->grabber_active = 0;
    capdev->scratchbuffer = NULL;        
    
    // Selection of pixel depths:
    if (reqdepth == 4 || reqdepth == 0) {
	    // Default is RGB 32 bit, aka RGBA8:
	    reqdepth = 4;
    }
    else {
	    // Only other supported format is RGB24 bit:
	    switch (reqdepth) {
	    case 2:
		    // A no-go: Instead we use 1 channel luminance8:
		    if (PsychPrefStateGet_Verbosity()>1)
			printf("PTB-WARNING: Video capture engine doesn't support requested Luminance+Alpha format. Will revert to pure luminance instead...\n");
		    reqdepth = 1;
	    break;
		    
	    case 1: // Accept as is: L8   aka Luminance 8 bit.
	    case 3: // Accept as is: RGB8 aka RGB 24 bit.
	    break;
	    case 5: // Accept as YVYU.
		    if (!(win->gfxcaps & kPsychGfxCapUYVYTexture)) {
		        // Usercode requested type 5 - UYVY textures, but GPU does not support them.
			// Fallback to type 4 - RGBA8 textures:
			reqdepth = 4;
			if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Requested YUV texture format for video capture unsupported by GPU. Falling back to RGBA8 format.\n");
		    }
	    break;
	    default:
		    // Unknown format:
		    PsychErrorExitMsg(PsychError_user, "You requested an invalid image depths (not one of 0, 1, 2, 3, 4 or 5). Aborted.");
	    }
    }

    // Requested output texture pixel depth in layers:
    capdev->reqpixeldepth = reqdepth;
    capdev->pixeldepth = reqdepth * 8;

    // Assign number of dma buffers to use:
    capdev->num_dmabuffers = num_dmabuffers;

    PsychInitMutex(&vidcapRecordBANK[slotid].mutex);
    PsychInitCondition(&vidcapRecordBANK[slotid].condition, NULL);
    
    // Try to open and initialize camera according to given settings:
    // Create video capture pipeline with camerabin plugin:
    usecamerabin = TRUE;
    camera = gst_element_factory_make ("camerabin", "ptbvideocapturepipeline");
    sprintf(config, "%s", device_name);

    // Camerabin disabled or creation failed?
    if (NULL == camera) {
		// Failed or disabled: Use fallback playbin2 implementation.
		usecamerabin = FALSE;
		
		if (!allow_lowperf_fallback)
			PsychErrorExitMsg(PsychError_user, "Failed to create high-performance video capture pipeline and script doesn't allow fallback! Aborted.");
		
		camera = gst_element_factory_make ("playbin2", "ptbvideocapturepipeline");
		
		// Assign a specific input video source URI name if possible:
		if (theDevice && (theDevice->classIndex  < 5)) sprintf(config, "v4l2://%s", device_name);
		// DV1394 and HDV1394 only encode the port property in their URI, not the GUID. Therefore
		// we can not select a camera by GUID if we have to use playbin2 instead of camerabin.
		// Do the best we can do: Select the generic "default camera" URI for now:
		if (theDevice && (theDevice->classIndex == 5)) sprintf(config, "dv://");
		if (theDevice && (theDevice->classIndex == 6)) sprintf(config, "hdv://");
		
		if (PsychPrefStateGet_Verbosity() > 1) {
			printf("PTB-WARNING: Could not use GStreamer 'camerabin' plugin for videocapture. Will use 'playbin2' as fallback. Most\n");
			printf("PTB-WARNING: features, e.g., video recording, ROI and video resolution selection, are not supported in fallback mode.\n");
		}
    }
	
    // Pipeline creation failed?
    if (NULL == camera) PsychErrorExitMsg(PsychError_user, "Failed to create video capture pipeline! Fallback capture engine is also unsupported. Aborted.");

    // Assign new record in videobank:
    vidcapRecordBANK[slotid].camera = camera;
    vidcapRecordBANK[slotid].frameAvail = 0;

    // Enforce use of the system clock for this pipeline instead of leaving it to the pipeline
    // to choose a proper clock automatically:
    // TODO FIXME: To use or not to use? Preliminare results on Linux indicate it
    // doesn't make a difference, so skip it for now: gst_pipeline_use_clock(camera, gst_system_clock_obtain());

    // Need to select a video source for this capture pipeline:
    if (!usecamerabin) {
		// Fallback path with playbin2: All video source parameters are encoded in "URI"
		// property as a string:
		
		// Assign name and configuration parameters of video capture device to open:
		g_object_set(G_OBJECT(camera), "uri", config, NULL);
    }
    else {
		// High performance path with camerabin. Build an appropriate video source and set up its input:
		videosource = NULL;
		
		if (deviceIndex >= 0) {
			// Create proper videosource plugin if possible:
			if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach '%s' as video source...\n", plugin_name);
			videosource = gst_element_factory_make(plugin_name, "ptb_videosource");

			if (!videosource) {
				if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Failed! We are out of options and will probably fail soon.\n");
				PsychErrorExitMsg(PsychError_system, "GStreamer failed to find a suitable video source! Game over.");
			}

			// Attach correct video input device to it:
			if (!strcmp(plugin_name, "dc1394src") && (prop_name[0] != 0)) {
				// DC1394 source:
				if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device with guid '%llu' as video input [Property %s].\n", theDevice->deviceURI, prop_name);
				g_object_set(G_OBJECT(videosource), prop_name, (int) theDevice->deviceURI, NULL);
			} else {
				if ((config[0] != 0) && (prop_name[0] != 0) && (theDevice->deviceURI == 0)) {
					if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input [Property %s].\n", config, prop_name);
					g_object_set(G_OBJECT(videosource), prop_name, config, NULL);
				}

				if ((theDevice->deviceURI > 0) && (prop_name[0] != 0)) {
					if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device with guid '%llu' as video input [Property %s].\n", theDevice->deviceURI, prop_name);
					g_object_set(G_OBJECT(videosource), prop_name, theDevice->deviceURI, NULL);
				}
			}
		}
		
		// MS-Windows specific setup path:
		if (PSYCH_SYSTEM == PSYCH_WINDOWS) {
			if (deviceIndex < 0) {
				// Non-Firewire video source selected:
				
				//if ((deviceIndex >= 10000) || (deviceIndex == -1) || (deviceIndex == -2)) {
				if ((deviceIndex == -1) || (deviceIndex == -2)) {
					// First try Kernel-Streaming based video source for low-latency capture:
					// if (deviceIndex >= 10000) deviceIndex = deviceIndex - 10000;
					if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach ksvideosrc as video source...\n");
					videosource = gst_element_factory_make("ksvideosrc", "ptb_videosource");
				}

				if (videosource) {
					// Kernel streaming video source:
					
					// Specific deviceIndex requested, instead of auto-select?
					if (deviceIndex < 0) {
						// Fetch optional targetmoviename parameter as name spec string:
						if (targetmoviefilename == NULL) PsychErrorExitMsg(PsychError_user, "You set 'deviceIndex' to a negative value, but didn't provide the required device name string in the 'moviename' argument! Aborted.");

						// Assign:
						strcat(config, targetmoviefilename);
						
						switch(deviceIndex) {
							case -1:
								// Human friendly device name provided:
								if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input.\n", config);
								g_object_set(G_OBJECT(videosource), "device-name", config, NULL);
								break;
								
							case -2:
								// DirectShow device path provided:
								if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device at path '%s' as video input.\n", config);
								g_object_set(G_OBJECT(videosource), "device-path", config, NULL);
								break;
								
							default:
								PsychErrorExitMsg(PsychError_user, "Invalid 'deviceIndex' provided! Not a value of -1 or -2. Aborted.");
						}
					}
				}

				// No kernel streaming video source available?
				if (!videosource) {
					// No. Try a Directshow video source instead:
					if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach dshowvideosrc as video source...\n");
					videosource = gst_element_factory_make("dshowvideosrc", "ptb_videosource");

					if (videosource) {
						// Specific deviceIndex requested, instead of auto-select?
						if (deviceIndex < 0) {
							if (deviceIndex != -5) {
								// Fetch optional targetmoviename parameter as name spec string:
								if (targetmoviefilename == NULL) PsychErrorExitMsg(PsychError_user, "You set 'deviceIndex' to a negative value, but didn't provide the required device name string in the 'moviename' argument! Aborted.");
								
								// Assign:
								strcat(config, targetmoviefilename);
							}
							
							switch(deviceIndex) {
								case -1:
								case -3:
									// Human friendly device name provided:
									if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input.\n", config);
									g_object_set(G_OBJECT(videosource), "device-name", config, NULL);
									break;
									
								case -2:
								case -4:
									// DirectShow device path provided:
									if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device at path '%s' as video input.\n", config);
									g_object_set(G_OBJECT(videosource), "device", config, NULL);
									break;									
								case -5:
									if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach default DirectShow video device as video input.\n");
									break;
								default:
									PsychErrorExitMsg(PsychError_user, "Invalid 'deviceIndex' provided! Aborted.");
							}
						}
						else {
							// Human friendly device name provided:
							if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input.\n", config);
							g_object_set(G_OBJECT(videosource), "device-name", config, NULL);							
						}
					}
				}
				// Have a standard windows video source ready.
			}
			
			// Still no video source available?
			if (!videosource) {
				if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Failed! We are out of options and will probably fail soon.\n");
				PsychErrorExitMsg(PsychError_system, "GStreamer failed to find a suitable video source! Game over.");
			}
		} // End of MS-Windows Video source creation.
		
		// MacOS/X specific setup path:
		if (PSYCH_SYSTEM == PSYCH_OSX) {
			if (deviceIndex < 0) {
				if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach osxvideosrc as video source...\n");
				videosource = gst_element_factory_make("osxvideosrc", "ptb_videosource");
				
				if (!videosource) {
					if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Failed! We are out of options and will probably fail soon.\n");
					PsychErrorExitMsg(PsychError_system, "GStreamer failed to find a suitable video source! Game over.");
				}
				
				// Fetch optional targetmoviename parameter as name spec string:
				if (deviceIndex != -5) {
					// Fetch optional targetmoviename parameter as name spec string:
					if (targetmoviefilename == NULL) PsychErrorExitMsg(PsychError_user, "You set 'deviceIndex' to a negative value, but didn't provide the required device name string in the 'moviename' argument! Aborted.");
					
					// Assign:
					strcat(config, targetmoviefilename);
				}
				
				switch(deviceIndex) {
					case -1:
					case -3:
						// Human friendly device name provided:
						if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input.\n", config);
						g_object_set(G_OBJECT(videosource), "device-name", config, NULL);
						break;
						
					case -2:
					case -4:
						// System device path provided:
						if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach video device '%s' as video input.\n", config);
						g_object_set(G_OBJECT(videosource), "device", config, NULL);
						break;

					case -5:
					if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Trying to attach default Quicktime OS/X video device as video input.\n");
						break;
						
					default:
						PsychErrorExitMsg(PsychError_user, "Invalid 'deviceIndex' provided! Not a value of -1 or -2. Aborted.");
				}
			}
		} // End of OS/X Video source creation.

		// The usual crap for MS-Windows:
		if (strstr(plugin_name, "dshowvideosrc")) g_object_set(G_OBJECT(videosource), "typefind", 1, NULL);
		
		// Enable timestamping by videosource:
		g_object_set(G_OBJECT(videosource), "do-timestamp", 1, NULL);

		// Assign video source to pipeline:
		g_object_set(camera, "video-source", videosource, NULL);
	}

    // Assign message context, message bus and message callback for
    // the pipeline to report events and state changes, errors etc.:    
    VideoContext = g_main_loop_new (NULL, FALSE);
    vidcapRecordBANK[slotid].VideoContext = VideoContext;
    bus = gst_pipeline_get_bus(GST_PIPELINE(camera));
    gst_bus_add_watch(bus, PsychVideoBusCallback, &(vidcapRecordBANK[slotid]));
    gst_object_unref(bus);

    // Name of target movie file for video and audio recording specified?
    if ((deviceIndex >= 0) && targetmoviefilename) {
	    // Assign it to camerabin to perform video recording:
	    if (!usecamerabin)
		    PsychErrorExitMsg(PsychError_user, "You requested video recording, but current fallback video engine doesn't support this. Aborted.");

	    // Codec settings or type specified?
	    if ((codecSpec = strstr(targetmoviefilename, ":CodecSettings="))) {
		    // Replace ':' with a zero in targetmoviefilename, so it gets null-terminated
		    // and only points to the actual movie filename:
		    *codecSpec = 0;

		    // Move after null-terminator:
		    codecSpec++;

		    // Replace the ':CodecSettings=' with the special keyword 'DEFAULTenc', so
		    // so the default video codec is chosen, but the given settings override its
		    // default parameters.
		    strncpy(codecSpec, "DEFAULTenc    ", strlen("DEFAULTenc    "));

		    if (strlen(codecSpec) == 0) PsychErrorExitMsg(PsychError_user, "Invalid (empty) :CodecSettings= parameter specified. Aborted.");
	    } else if ((codecSpec = strstr(targetmoviefilename, ":CodecType="))) {
		    // Replace ':' with a zero in targetmoviefilename, so it gets null-terminated
		    // and only points to the actual movie filename:
		    *codecSpec = 0;
		    // Advance codecSpec to point to the actual codec spec string:
		    codecSpec+= 11;

		    if (strlen(codecSpec) == 0) PsychErrorExitMsg(PsychError_user, "Invalid (empty) :CodecType= parameter specified. Aborted.");
	    } else {
		    // No codec specified: Use our default encoder, the one that's been shown to
		    // produce good results:
		    codecSpec = strdup("DEFAULTenc");
	    }

	    // Create matching video encoder for codecSpec:
	    if (PsychSetupRecordingPipeFromString(capdev, codecSpec, codecName, FALSE)) {
		    if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Video%s recording into file [%s] enabled for device %i. Codec is [%s].\n",
								  ((recordingflags & 2) ? " and audio" : ""), targetmoviefilename, deviceIndex, codecName);
		    if (strcmp(codecSpec, "DEFAULTenc") == 0) free(codecSpec);
		    codecSpec = NULL;
	    } else {
		    if (strcmp(codecSpec, "DEFAULTenc") == 0) free(codecSpec);
		    PsychErrorExitMsg(PsychError_system, "Setup of video recording failed. Reason hopefully given above.");
	    }

	    capdev->targetmoviefilename = strdup(targetmoviefilename); 
	    capdev->recording_active = TRUE;
    } else {
	    capdev->recording_active = FALSE;
    }

    // Create a appsink named "ptbsink0" for attachment as the destination video-sink for
    // all video content. This allows us to get hold of the videoframe buffers for
    // converting them into PTB OpenGL textures:
    videosink = gst_element_factory_make ("appsink", "ptbsink0");
    if (!videosink) {
	printf("PTB-ERROR: Failed to create video-sink appsink ptbsink!\n");
	PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, TRUE);
	PsychErrorExitMsg(PsychError_system, "Opening the videocapture device failed. Reason hopefully given above.");
    };

    vidcapRecordBANK[slotid].videosink = videosink;

    // Our OpenGL texture creation routine needs GL_BGRA8 data in GL_UNSIGNED_8_8_8_8_REV
    // format, but the pipeline usually delivers YUV data in planar format. Therefore
    // need to perform colorspace/colorformat conversion. These colorcaps, as assigned to
    // the videosink will try to nudge the video source to deliver data in our requested
    // format. If this ain't possible, they will enforce creation of a colorspace converter
    // inbetween the video source and our videosink:
    switch (reqdepth) {
    case 4:
	    colorcaps = gst_caps_new_simple (   "video/x-raw-rgb",
						"bpp", G_TYPE_INT, capdev->pixeldepth,
						"depth", G_TYPE_INT, capdev->pixeldepth,
						"alpha_mask", G_TYPE_INT, 0x000000FF,
						"red_mask", G_TYPE_INT,   0x0000FF00,
						"green_mask", G_TYPE_INT, 0x00FF0000,
						"blue_mask", G_TYPE_INT,  0xFF000000,
						NULL);
	    break;
    case 3:
	    colorcaps = gst_caps_new_simple (   "video/x-raw-rgb",
						"bpp", G_TYPE_INT, capdev->pixeldepth,
						"depth", G_TYPE_INT, capdev->pixeldepth,
						"red_mask", G_TYPE_INT,   0x00FF0000,
						"green_mask", G_TYPE_INT, 0x0000FF00,
						"blue_mask", G_TYPE_INT,  0x000000FF,
						NULL);
	    break;
    case 2:
    case 1:
	    colorcaps = gst_caps_new_simple (   "video/x-raw-gray",
						"bpp", G_TYPE_INT, capdev->pixeldepth,
						NULL);
	    break;
    case 5:
	    colorcaps = gst_caps_new_simple (   "video/x-raw-yuv",
						"format", GST_TYPE_FOURCC, GST_MAKE_FOURCC('U', 'Y', 'V', 'Y'),
						NULL);
	    reqdepth = 2;
	    capdev->reqpixeldepth = 2;
	    capdev->pixeldepth = 16;

	    break;
    default:
	PsychErrorExitMsg(PsychError_internal, "Unknown reqdepth parameter received!");            
    }

    // Assign 'colorcaps' as caps to our videosink. This marks the videosink so
    // that it can only receive video image data in the format defined by colorcaps,
    // i.e., a format that is easy to consume for OpenGL's texture creation on std.
    // gpu's. It is the job of the video pipeline's autoplugger to plug in proper
    // color & format conversion plugins to satisfy videosink's needs.
    gst_app_sink_set_caps(GST_APP_SINK(videosink), colorcaps);

    // ROI rectangle specified and use of it supported by camerabin?
    if (usecamerabin && capturerectangle) {
	if ((capturerectangle[kPsychLeft] == 0) && (capturerectangle[kPsychTop] == 0)) {
		// roi = [0 0 w h] --> Specs a target capture resolution.
		// Extract wanted width and height and use it as target capture resolution:
		twidth  = (int) PsychGetWidthFromRect(capturerectangle);
		theight = (int) PsychGetHeightFromRect(capturerectangle);
	} else {
		// roi = [l t r b] --> Specs a ROI to crop out of full res capture.

		// Don't change videocapture resolution -- Leave it at auto-detected settings:
		twidth  = -1;
		theight = -1;

		// Create videocrop filter to crop away everything outside the defined ROI:
		videocrop_filter = gst_element_factory_make ("videocrop", "ptbvideocropfilter");
		if (!videocrop_filter) {
			// Disable capturerectangle, so we revert to full device default resolution:
			capturerectangle = NULL;
			if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Selection of specified video ROI not supported by setup. Using full resolution.\n");
		}
	}
    }
    else {
	if (capturerectangle) {
		// ROI spec'd but camerabin not supported. This is a no-go.
		capturerectangle = NULL;
		if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Selection of video ROI's or capture resolution not supported by your setup. Using full resolution.\n");
	}

	// No user specified resolution. Rely on auto-detection:
	twidth  = -1;
	theight = -1;
    }

    // Assign our special appsink 'videosink' as video-sink of the pipeline:
    if (!usecamerabin) {
	if (capdev->recording_active) PsychErrorExitMsg(PsychError_user, "Video recording requested, but this isn't supported on this setup, sorry.");
	g_object_set(G_OBJECT(camera), "video-sink", videosink, NULL);

	// Invalidate capdev->width,height/fps etc. so it gets auto-detected
	// by preroll op:
	capdev->width = capdev->height = 0;
	capdev->fps = 0;
    } else {
	    // Attach our appsink as videosink:
	    g_object_set(G_OBJECT(camera), "viewfinder-sink", videosink, NULL);

	    // Setup pipeline for video recording or pure capture:
	    if (!capdev->recording_active) {
		    // Pure video capture, no recording: Optimize pipeline for this case:
		    g_object_set(G_OBJECT(camera),
				 "flags", 1+2+4,
				 "filter-caps", colorcaps,
				 NULL);
	    } else {
		    // Video recording (with optional capture). Setup pipeline:
		    filter_caps = gst_caps_from_string ("video/x-raw-yuv,format=(fourcc)I420");
		    
		    g_object_set(G_OBJECT(camera),
				 // Only enable sound encoding if "audio recording" flag 2 is set in
				 // recordingflags. Otherwise add flags 0x20 to disable audio encoding:
				 "flags", 0x08 + 0x04 + 0x02 + 0x01 + ((recordingflags & 2) ? 0x10 : 0x20),
				 // filter caps not needed for V4L2 webcam sources. TODO FIXME: Needed for non-Video4Linux2 sources?
				 // "filter-caps", filter_caps,
				 NULL);

		    gst_caps_unref(filter_caps);
	    }

	    // Create and use a videorate converter always when video recording is active (because without it
	    // we can get choppy or truncated video recordings and/or audio-video sync problems), and
	    // optionally in pure video feedback mode if explicitely requested by usercode via
	    // recordingflags & 128, as this is usually not what one wants for live video processing or
	    // feedback.
	    if (capdev->recording_active || (recordingflags & 128)) {
		    // Attach a videorate converter as source filter. It should take care of adjusting
		    // for fluctuating framerates from the videosource device by dropping or duplicating
		    // videoframes and adjusting timestamps as needed to generate a video stream with the
		    // selected target output framerate:
		    capdev->videorate_filter = gst_element_factory_make ("videorate", "ptbvideoratefilter");
		    if (capdev->videorate_filter == NULL) {
			    if (PsychPrefStateGet_Verbosity() > 1) {
				    printf("PTB-WARNING: Could not create video rate conversion filter. Therefore can't compensate\n");
				    printf("PTB-WARNING: for possible fluctuations in videocapture framerate. This can cause\n");
				    printf("PTB-WARNING: audio-video sync problems or wrong timing/speed in videostream!\n");
			    }
		    }
		    else {
			    // By default we apply the videorate converter upstream at the videosource,
			    // so it affects both video recording and live video feedback. Usercode can
			    // restrict conversion to the recorded video stream only by setting
			    // recordingflags & 256:
			    if (recordingflags & 256) {
				    // Attach to video-post-processing -- immediately before video encoder:
				    g_object_set(G_OBJECT(camera), "video-post-processing", capdev->videorate_filter, NULL);
				    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Restricting video framerate conversion to recorded video.\n"); 
			    }
			    else {
				    // Attach as video-source-filter -- upstream right at the source:
				    videosource_filter = capdev->videorate_filter;
				    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Video framerate conversion applies to recorded video and live video.\n"); 
			    }
		    }
	    }

	    // Specific capture resolution requested?
	    if ((twidth != -1) && (theight != -1)) {
            // Yes. Validate and request it.
            
            // The usual Windows crap. Enumeration of supported resolutions doesn't work, so
            // we skip validation and trust blindly that the usercode is right if this is the
            // DirectShow video source:
            if (!strstr(plugin_name, "dshowvideosrc")) {
                // Query camera if it supports the requested resolution:
                capdev->fps = -1;
                if (!PsychGSGetResolutionAndFPSForSpec(capdev, &twidth, &theight, &capdev->fps, reqdepth)) {
                    // Unsupported resolution. Game over!
                    printf("PTB-ERROR: Video capture device %i doesn't support requested video capture resolution of %i x %i pixels! Aborted.\n", slotid, twidth, theight);
                    PsychErrorExitMsg(PsychError_user, "Failed to open video device at requested video resolution.");
                }
            }
            
            // Resolution supported. Request it:
            g_object_set(G_OBJECT(camera),
                         "video-capture-width", twidth,
                         "video-capture-height", theight,
                         NULL);
            
            // Assign requested and validated resolution as capture resolution of video source:
            capdev->width = twidth;
            capdev->height = theight;
            capdev->fps = 0;
	    }
	    else {
            // No, usercode wants auto-detected default resolution. Query
            // highest possible resolution (maximum pixel area) and choose that:
            capdev->width = -1;
            capdev->height = -1;
            capdev->fps = -1;

            // Auto-Detection doesn't work with Windows DirectShow video plugin :-( Skip it.
            if (!strstr(plugin_name, "dshowvideosrc")) {
                // Ask camera to provide auto-detected parameters:
                if (!PsychGSGetResolutionAndFPSForSpec(capdev, &capdev->width, &capdev->height, &capdev->fps, reqdepth)) {
                    // Unsupported resolution. Game over!
                    printf("PTB-ERROR: Auto-Detection of optimal video resolution on video capture device %i failed! Aborted.\n", slotid);
                    PsychErrorExitMsg(PsychError_user, "Failed to open video device with auto-detected video resolution.");
                }
                
                // Resolution supported. Request it:
                g_object_set(G_OBJECT(camera),
                             "video-capture-width", capdev->width,
                             "video-capture-height", capdev->height,
                             NULL);
            }
            else {
                // Directshow source. Set "don't know" values and hope the fallback code below
                // does a better job at guessing the true source resolution:
                capdev->width  = 0;
                capdev->height = 0;

                // ROI defined? We can't handle this, because we don't know the true video capture resolution
                // which would be needed at this point in the setup path due to the broken enumeration of dshowvideosrc.
                if (capturerectangle) {
                    capturerectangle = NULL;
                    overrideFrameSize = TRUE;

                    // Delete useless videocrop element if any:
                    if (videocrop_filter) gst_object_unref(G_OBJECT(videocrop_filter));
                    videocrop_filter = NULL;

                    if (PsychPrefStateGet_Verbosity() > 1) {
                        printf("PTB-WARNING: Usercode specified a 'roirectangle' with a ROI for video cropping, but this system setup\n");
                        printf("PTB-WARNING: doesn't support this. Ignoring 'roirectangle' and reverting to full video capture resolution.\n");
                    }

                }
            }
            
            // Reset capdev->fps to neutral zero: capdev->width and capdev->height are already auto-assigned.
            capdev->fps = 0;
	    }
        
	    // videocrop_filter for ROI processing available?
	    if (videocrop_filter) {
		    // Setup final cropping region:
		    g_object_set(G_OBJECT(videocrop_filter),
				 "left",   (int) capturerectangle[kPsychLeft],
				 "top",    (int) capturerectangle[kPsychTop],
				 "right",  capdev->width - (int) capturerectangle[kPsychRight],
				 "bottom", capdev->height - (int) capturerectangle[kPsychBottom],
				 NULL);

		    // HACK HACK HACK: This video ROI cropping implementation is not what we want,
		    // but it is the best we can do to workaround what i think are GStreamer bugs.
		    // Will work correctly for live capture cropping only. As soon as videorecording
		    // gets cropped as well, it affects the live feed in ugly ways...

		    // Is video recording active and ROI cropping for recording explicitely enabled
		    // via recordingflags setting 512?
		    if (capdev->recording_active && (recordingflags & 512)) {
			    // Yes. Attach filter to video-post-processing. This way it affects
			    // recorded video, but unfortunately also *always* the viewfinder video feed
			    // - which i think is a bug - and it affects the viewfinder feed in a weird way -
			    // which i think is a 2nd bug: The viewfinder/appsink gets the cropped
			    // ROI, but upscaled to full video resolution! We need to hack the
			    // capdev->frame_width and capdev->frame_height fields to take this
			    // into account, so we at least get a distorted image in the video
			    // textures. Usercode can Screen('DrawTexture') such distorted textures
                // with a properly scaled 'dstrect' to undistort, although this is a
			    // messy endeveaour -- but not impossible.

			    // So we attach to video-post-processing and set a special flag to
			    // signal the capdev->frame_width and capdev->frame_height needs to
			    // get hacked into shape :-(
			    g_object_set(G_OBJECT(camera), "video-post-processing", videocrop_filter, NULL);
			    overrideFrameSize = TRUE;

			    if (PsychPrefStateGet_Verbosity() > 1) {
				    printf("PTB-WARNING: Application of ROI's to recorded video is buggy, due to\n");
				    printf("PTB-WARNING: GStreamer bugs. The ROI gets correctly applied to the \n");
				    printf("PTB-WARNING: recorded video. It also gets applied to the live video feed,\n");
				    printf("PTB-WARNING: regardless if you want it or not. The live ROI texture images are\n");
				    printf("PTB-WARNING: distorted. They have the full video resolution size, but only\n");
				    printf("PTB-WARNING: show the ROI, zoomed and scaled to fit the full video resolution!\n");
				    printf("PTB-WARNING: You can either manually undistort the images during texture drawing,\n");
				    printf("PTB-WARNING: by proper choice of the 'dstRect' parameter in Screen('DrawTexture',...),\n");
				    printf("PTB-WARNING: or you can avoid application of ROI's to recorded video. In that case\n");
				    printf("PTB-WARNING: the video will be recorded at full video resolution, but application of\n");
				    printf("PTB-WARNING: ROI's to the live video textures will work correctly.\n\n");
			    }
		    }
		    else {
			    // No. Either no videorecording active -- pure live feedback, or it is
			    // active, but cropping of recorded video is not enabled.
			    // This means only the viewfinder, aka appsink aka our live video textures
			    // shall be cropped to ROI, if at all. This works as expected and is
			    // thankfully the common case for most applications of ROI's.

			    // Check if live feed is enabled and ROI cropping for it is not disabled:
			    if (!(recordingflags & 4) && !(recordingflags & 1024)) {
				    // Yes. Viewfinder feed shall be cropped: Attach to viewfinder-filter:
				    g_object_set(G_OBJECT(camera), "viewfinder-filter", videocrop_filter, NULL);

				    // No stupid hack needed in this case:
				    overrideFrameSize = FALSE;
			    }
			    else {
				    // Disable application of ROI to video buffers:
				    overrideFrameSize = TRUE;
			    }
		    }

#if 0
/* This should be the correct implementation, but it doesn't work due to what i think are bugs
   in the GStreamer videocrop or camerabin plugin. Therefore this codepath is disabled:
*/
		    // Attach video cropping to viewfinder-filter --> Apply to our live video feed,
		    // unless the "only apply to videorecording" recordingflag 512 is set or the
		    // live feed is disabled via flag 4
		    if (!(recordingflags & 1024) && !(recordingflags & 4)) {
			    g_object_set(G_OBJECT(camera), "viewfinder-filter", videocrop_filter, NULL);
		    }
		    else {
			    // Disable application of ROI to video buffers:
			    overrideFrameSize = TRUE;
		    }

		    // Is videorecording active and cropping for it requested?
		    if ((recordingflags & 512) && capdev->recording_active) {
			    // Need to attach to video-post-processing as well. We need to setup a 2nd
			    // cropping filter with identical settings for this, unless the 1st one isn't
			    // used as the viewfinder-filter.
			    if ((recordingflags & 1024) || (recordingflags & 4)) {
				    // Live feed disabled or no cropping for live feed wanted. The videocrop_filter
				    // is unused and we can use it here for cropping the videorecording by
				    // attaching to video-post-processing:
				    g_object_set(G_OBJECT(camera), "video-post-processing", videocrop_filter, NULL);
			    }
			    else {
				    // videocrop_filter already used for cropping the live feed aka viewfinder.
				    // Generate a new videocrop element, set it up identically, attach it to
				    // video-post-processing:
				    videocrop_filter = gst_element_factory_make ("videocrop", "ptbvideoreccropfilter");
				    if (!videocrop_filter) {
					    if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Failed to apply video ROI to videorecording! Using full resolution.\n");
				    }
				    else {
					    g_object_set(G_OBJECT(videocrop_filter),
							 "left",   (int) capturerectangle[kPsychLeft],
							 "top",    (int) capturerectangle[kPsychTop],
							 "right",  capdev->width - (int) capturerectangle[kPsychRight],
							 "bottom", capdev->height - (int) capturerectangle[kPsychBottom],
							 NULL);
					    g_object_set(G_OBJECT(camera), "video-post-processing", videocrop_filter, NULL);
				    }
			    }
		    }
#endif
	    }


	    // Attach videosource filter, if any:
	    if (videosource_filter) {
		    g_object_set(G_OBJECT(camera), "video-source-filter", videosource_filter, NULL);
	    }
    }

    gst_caps_unref(colorcaps);

    // Disable asynchronous transition to GST_PAUSED state for video sink when simultaneous
    // video recording is active: TODO FIXME: This seems to have no effect whatsoever....
    if (capdev->recording_active) g_object_set(G_OBJECT(videosink), "async", FALSE, NULL);

    // Disable internal queuing of the last buffer, as we don't ever use the "last-buffer" property:
    g_object_set(G_OBJECT(videosink), "enable-last-buffer", FALSE, NULL);

    // Get the pad from the final sink for probing width x height of video frames and nominal framerate of video source:	
    pad = gst_element_get_pad(videosink, "sink");

    // Install callbacks used by the videosink (appsink) to announce various events:
    gst_app_sink_set_callbacks(GST_APP_SINK(videosink), &videosinkCallbacks, &(vidcapRecordBANK[slotid]), PsychDestroyNotifyCallback);

    // Specific maximum number of buffers to use?
    if (capdev->num_dmabuffers) {
	    // Yes: Drop frames if callback can't pull buffers fast enough:
	    gst_app_sink_set_drop(GST_APP_SINK(videosink), TRUE);
	    
	    // Allownum_dmabuffers to be queued before dropping buffers:
	    gst_app_sink_set_max_buffers(GST_APP_SINK(videosink), capdev->num_dmabuffers);
    }
    else {
	    // No: Leave queue length at default and disable buffer dropping:
	    gst_app_sink_set_drop(GST_APP_SINK(videosink), FALSE);
    }

    PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, FALSE);

    if ((capdev->recording_active) && (recordingflags & 4)) {
	    // No live feedback (flags 4) implies no preroll (flags 8):
	    // This because a preroll would bring the pipeline from null state to
	    // at least ready state and thereby prevent us from detaching our
	    // appsink and replacing it with a fakesink. This would cause our
	    // appsink to collect video buffers which wouldn't get pulled/drained,
	    // effectively filling up all memory with "leaked" buffers until
	    // out of memory abort happens after a minute or so.
	    //
	    // Not prerolling -> pipeline in null state at fakesink attach time
	    // -> problem solved.
	    recordingflags |= 8;

	    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Pipeline preroll skipped because only harddisc recording (recordingflags & 4).\n");
    }

    // Only preroll if prerolling not disabled by recordingflag 8,
    // or if we use the fallback path, which utterly needs this:
    if (!(recordingflags & 8) || !usecamerabin) {
	    // Ready the pipeline:
	    if (!PsychVideoPipelineSetState(camera, GST_STATE_READY, 30.0)) {
		    PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, TRUE);
		    PsychErrorExitMsg(PsychError_user, "In OpenVideoCapture: Opening the video capture device failed during pipeline zero -> ready. Reason given above.");
	    }

	    // Preroll the pipeline:
	    if (!PsychVideoPipelineSetState(camera, GST_STATE_PLAYING, 30.0)) {
		    PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, TRUE);
		    PsychErrorExitMsg(PsychError_user, "In OpenVideoCapture: Opening the video capture device failed during pipeline preroll ready->playing. Reason given above.");
	    }
    }

    if (!usecamerabin) {
	    g_object_get (G_OBJECT(camera),
			  "source", &videosource,
			  NULL);
    } else {
	    g_object_get (G_OBJECT(camera),
			  "video-source", &videosource,
			  NULL);
    }

    // Query number of available video and audio channels on capture device:
    if (!usecamerabin) {
	    g_object_get(G_OBJECT(camera),
		         "n-video", &vidcapRecordBANK[slotid].nrVideoTracks,
		         "n-audio", &vidcapRecordBANK[slotid].nrAudioTracks,
			 NULL);
    } else {
	// There's always at least a video channel:
	vidcapRecordBANK[slotid].nrVideoTracks = 1;
    }

    // We need a valid onscreen window handle for real video playback:
    if ((NULL == win) && (vidcapRecordBANK[slotid].nrVideoTracks > 0) && !(recordingflags & 4)) {
	    PsychErrorExitMsg(PsychError_user, "No windowPtr to an onscreen window provided. Must do so for sources with video channels!");
    }
 
    PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, FALSE);

    // Assign harmless initial settings for fps and frame size:
    rate1 = 0;
    rate2 = 1;
    width = height = 0;

    // Videotrack available and return of video data enabled?
    if (vidcapRecordBANK[slotid].nrVideoTracks > 0) {
	// Yes: Query video frame size and framerate of device:
	peerpad = gst_pad_get_peer(pad);
	caps = NULL;
	if (GST_IS_PAD(peerpad)) caps = gst_pad_get_negotiated_caps(peerpad);
	if (caps) {
		str=gst_caps_get_structure(caps,0);

		/* Get some data about the frame */
		gst_structure_get_int(str,"width",&width);
		gst_structure_get_int(str,"height",&height);
		gst_structure_get_fraction(str, "framerate", &rate1, &rate2);
		gst_caps_unref(caps);
		if (PsychPrefStateGet_Verbosity() > 4) printf("Negotiated videosink res: %i x %i\n", width, height);
	} else {
		if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: No frame info available after preroll.\n");
	}
    }

    // Release the pad:
    gst_object_unref(pad);

    // Our camera should be ready: Assign final handle.
    *capturehandle = slotid;

    // Increase counter of open capture devices:
    numCaptureRecords++;

    // Assign our first guess on video device resolution, only already
    // setup by detection code above:
    if ((capdev->width == 0) && (capdev->height)) {
        capdev->width = width;
        capdev->height = height;
    }
    
    // Reset framecounter:
    capdev->nrframes = 0;
    capdev->grabber_active = 0;

    rate1 = 0;
    rate2 = 1;
    width = height = 0;

    // Query true properties of attached video source:
    videosource = NULL;
	
    if (!usecamerabin) {
	    g_object_get (G_OBJECT(camera),
			  "source", &videosource,
			  NULL);
	    capdev->videoenc = NULL;
    } else {
	    g_object_get (G_OBJECT(camera),
			  "video-source", &videosource,
			  NULL);
	    g_object_get (G_OBJECT(camera),
			  "video-encoder", &capdev->videoenc,
			  NULL);
    }

    if (videosource) {
	pstring = NULL; 
	if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device")) {
		g_object_get(G_OBJECT(videosource), "device", &pstring, NULL);
		if (pstring) {
			if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Camera device name is '%s'.\n", pstring);
			g_free(pstring); pstring = NULL;
		}
	}

	if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device-path")) {
		g_object_get(G_OBJECT(videosource), "device-path", &pstring, NULL);
		if (pstring) {
			if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Camera device-path is '%s'.\n", pstring);
			g_free(pstring); pstring = NULL;
		}
	}

	if (g_object_class_find_property(G_OBJECT_GET_CLASS(videosource), "device-name")) {
		g_object_get(G_OBJECT(videosource), "device-name", &pstring, NULL);
		if (pstring) {
			if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Camera friendly device-name is '%s'.\n", pstring);
			capdev->cameraFriendlyName = strdup(pstring);
			g_free(pstring); pstring = NULL;
		}
		else {
			capdev->cameraFriendlyName = strdup("Unknown");
		}
	}

	// Get the pad from the src pad of the source for probing width x height
	// of video frames and nominal framerate of video source:	
	pad = gst_element_get_pad(videosource, "src");

	// Videotrack available?
	if (vidcapRecordBANK[slotid].nrVideoTracks > 0) {
		// Yes: Query video frame size and framerate of device:
		peerpad = gst_pad_get_peer(pad);
		caps = NULL;
		if (GST_IS_PAD(peerpad)) caps = gst_pad_get_negotiated_caps(peerpad);
		if (caps) {
			str=gst_caps_get_structure(caps,0);

			/* Get some data about the frame */
			gst_structure_get_int(str,"width",&width);
			gst_structure_get_int(str,"height",&height);
			gst_structure_get_fraction(str, "framerate", &rate1, &rate2);
			if (PsychPrefStateGet_Verbosity() > 4) printf("Negotiated videosource w = %i h = %i fps = %f\n", width, height, rate1/rate2);
			gst_caps_unref(caps);
		} else {
			 if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-DEBUG: No frame info for video source available after preroll.\n");	
		}
	}

	// Release the pad:
	gst_object_unref(pad);		
    }

    // If correct width x height not yet assigned, retry assignment from
    // results of videosource query:
    if (capdev->width == 0) capdev->width = width;
    if (capdev->height == 0) capdev->height = height;

    // If we totally failed to query width and height, set what usercode
    // requested - if it requested anything:
    if (capdev->width == 0) capdev->width = (twidth > 0) ? twidth : 0;
    if (capdev->height == 0) capdev->height = (theight > 0) ? theight : 0;

    // Create final user-visible effective ROI:
    if (capturerectangle && ((twidth == -1) && (theight == -1))) {
	    // Usercode specified a ROI, videosource is left at its full default
	    // resolution, ROI is applied via videocrop_filter. Specified ROI is
	    // effective ROI, so just copy it:
	    PsychCopyRect(capdev->roirect, capturerectangle);
    } else {
	    // Usercode specified no ROI, but a target device resolution or no
	    // resolution at all. Videosource is configured for a certain resolution,
	    // as stored in capdev->width x height. Our effective ROI is simply
	    // the full videosource resolution:
	    PsychMakeRect(capdev->roirect, 0, 0, capdev->width, capdev->height);
    }

    // The size of returned video frames for texture creation or image buffer return
    // etc., is equal to the width x height of the ROI:
    capdev->frame_width  = (int) PsychGetWidthFromRect(capdev->roirect);
    capdev->frame_height = (int) PsychGetHeightFromRect(capdev->roirect);

    // Do we need to force the frame_width x frame_height to full capture
    // resolution?
    if (overrideFrameSize) {
	    // Yes.
	    capdev->frame_width  = capdev->width;
	    capdev->frame_height = capdev->height;
    }

    // If we prerolled before, we need to undo its effects:
    if (!(recordingflags & 8) || !usecamerabin) {
	    // Pause the pipeline again:
	    if (!PsychVideoPipelineSetState(camera, (usecamerabin) ? GST_STATE_READY : GST_STATE_PAUSED, 30.0)) {
		    PsychGSProcessVideoContext(vidcapRecordBANK[slotid].VideoContext, TRUE);
		    PsychErrorExitMsg(PsychError_user, "In OpenVideoCapture: Opening the video capture device failed during preroll playing -> pause. Reason given above.");
	    }
    }

    if ((capdev->recording_active) && (recordingflags & 4)) {
	    // Only disc recording, no data return: Attach a fakesink to effectively
	    // disable most of viewfinder processing:
	    videosink = gst_element_factory_make ("fakesink", "ptbfakesink0");
	    g_object_set(G_OBJECT(camera), "viewfinder-sink", videosink, NULL);
    }

    /* Obsolete on Linux, hopefully also on Windows:
    // Make sure our capture timestamps are in system time (GetSecs() reference time)
    // unless recordingflags 64 are set, in which case timestamps are in pipeline
    // running time, or whatever GStreamer finds convenient.
    if (!(recordingflags & 64)) {
	    // Set defined start time for pipeline - Used for cts timestamps:
	    gst_element_set_base_time(camera, GST_CLOCK_TIME_NONE);
	    gst_element_set_start_time(camera, GST_CLOCK_TIME_NONE);
    }
    */

    // Assign final recordingflags:
    vidcapRecordBANK[slotid].recordingflags = recordingflags;

    if (PsychPrefStateGet_Verbosity() > 2) {
	    printf("PTB-INFO: Camera %i opened [Source resolution width x height = %i x %i, video image size %i x %i]\n",
		   slotid, capdev->width, capdev->height, capdev->frame_width, capdev->frame_height);
    }

    return(TRUE);
}

/* Internal helper:
 * Drain up to 'numFramesToDrain' videobuffers from the videosink of 'capdev'.
 * 'flags' modify drain behaviour. Unused so far.
 * Return number of drained buffers.
 */
int PsychGSDrainBufferQueue(PsychVidcapRecordType* capdev, int numFramesToDrain, unsigned int flags)
{
	GstBuffer *videoBuffer = NULL;
	int drainedCount = 0;

	// Drain while anything available, but at most numFramesToDrain frames.
	while (GST_IS_APP_SINK(capdev->videosink) && !gst_app_sink_is_eos(GST_APP_SINK(capdev->videosink))
		&& (capdev->frameAvail > 0) && (numFramesToDrain > drainedCount)) {
		capdev->frameAvail--;
		videoBuffer = gst_app_sink_pull_buffer(GST_APP_SINK(capdev->videosink));
		gst_buffer_unref(videoBuffer);
		videoBuffer = NULL;
		drainedCount++;
	}

	return(drainedCount);
}

/* CHECKED
*  PsychGSVideoCaptureRate() - Start- and stop video capture.
*
*  capturehandle = Grabber to start-/stop.
*  playbackrate = zero == Stop capture, non-zero == Capture
*  dropframes = 0 - Always deliver oldest frame in DMA ringbuffer. 1 - Always deliver newest frame.
*               --> 1 == drop frames in ringbuffer if behind -- low-latency capture.
*
*               If dropframes is 1 at 'stop' time, then discard all pending buffers in queue,
*               otherwise retain them so they can be fetched after stop.
*
*  startattime = Deadline (in system time) for which to wait before real start of capture.
*  Returns Number of dropped frames during capture.
*/
int PsychGSVideoCaptureRate(int capturehandle, double capturerate, int dropframes, double* startattime)
{
	GstElement		*camera = NULL;
	GstBuffer               *videoBuffer = NULL;
	GValue                  fRate = { 0, };
	guint64                 nrInFrames, nrOutFrames, nrDroppedFrames, nrDuplicatedFrames;
	int dropped = 0;
	int drainedCount;
	float framerate = 0;

	// Retrieve device record for handle:
	PsychVidcapRecordType* capdev = PsychGetGSVidcapRecord(capturehandle);
	camera = capdev->camera;

	// Make sure GStreamer is ready:
	PsychGSCheckInit("videocapture");

	PsychGSProcessVideoContext(capdev->VideoContext, FALSE);

	// Start- or stop capture?
	if (capturerate > 0) {
		// Start capture:
		if (capdev->grabber_active) PsychErrorExitMsg(PsychError_user, "You tried to start video capture, but capture is already started!");
		
		// Reset statistics:
		capdev->last_pts = -1.0;
		capdev->nr_droppedframes = 0;
		capdev->lastSavedBaseTime = 0;

		// Framedropping in the sense we define it is not supported by libGStreamer, so we implement it ourselves.
		// Store the 'dropframes' flag in our capdev struct, so the PsychGSGetTextureFromCapture()
		// knows how to handle this:
		capdev->dropframes = (dropframes > 0) ? 1 : 0;

		if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StartVideoCapture: Draining any queued stale video buffers before start of capture.\n");
		drainedCount = PsychGSDrainBufferQueue(capdev, INT_MAX, 0);
		if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StartVideoCapture: Drain of %i buffers completed.\n", drainedCount);

		// Only do state transitions for camerabin:
		if (usecamerabin) {
			// Start the video capture for this camera.
			if (!PsychVideoPipelineSetState(camera, GST_STATE_READY, 10.0)) {
				// Failed!
				PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
				PsychErrorExitMsg(PsychError_user, "Failure in pipeline transition null -> ready - Start of video capture failed!");
			}

			if (!PsychVideoPipelineSetState(camera, GST_STATE_PAUSED, 10.0)) {
				// Failed!
				PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
				PsychErrorExitMsg(PsychError_user, "Failure in pipeline transition ready -> paused - Start of video capture failed!");
			}
		}

		// Setup of capture framerate & resolution:
		if (usecamerabin) {
			// Set requested capture/recording video resolution and framerate:
			// Map special capturerate value DBL_MAX to a fps nominator of zero. This
			// asks the engine to capture at the maximum supported framerate for given
			// format and resolution:
			g_signal_emit_by_name (G_OBJECT(camera),
					       "set-video-resolution-fps", capdev->width, capdev->height,
					       ((capturerate < DBL_MAX) ? (int)(capturerate + 0.5) : 0), 1);
		}
		else {
			// Set playback rate in non camerabin configuration:
			// We only set it if the special value DBL_MAX isn't provided. DBL_MAX means
			// to run at maximum supported fps. As we can't pass this request to playbin2,
			// we do the 2nd best and don't ask for a specific fps at all, hoping that playbin2
			// will then configure to a save high speed default value -- or at least to something
			// supported and safe:
			if (capturerate < DBL_MAX) {
				gst_element_seek(camera, capturerate, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_NONE, 0, GST_SEEK_TYPE_NONE, 0);
			}
		}

		// Init parameters:
		capdev->last_pts = -1.0;
		capdev->nr_droppedframes = 0;
		capdev->frameAvail = 0;
		capdev->preRollAvail = 0;

		// Wait until start deadline reached:
		if (*startattime != 0) PsychWaitUntilSeconds(*startattime);
		
		// Start actual video capture and/or recording:
		if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Starting capture...\n");

		if (!PsychVideoPipelineSetState(camera, GST_STATE_PLAYING, 10.0)) {
			// Failed!
			PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
			PsychErrorExitMsg(PsychError_user, "Failure in pipeline transition paused -> playing - Start of video capture failed!");
		}
		
		// Start video recording if requested:
		if (usecamerabin && capdev->recording_active) {
			if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Starting recording...\n");
			g_object_set(G_OBJECT(camera), "mode", 1, NULL);
			if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Recording 1 started...\n");
			g_object_set(G_OBJECT(camera), "filename", capdev->targetmoviefilename, NULL);
			if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Recording 2 started...\n");
			g_signal_emit_by_name (camera, "capture-start", 0, 0);
			if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Recording started...\n");
		}

		// Wait for real start of capture, i.e., arrival of 1st captured
		// video buffer:
		PsychLockMutex(&capdev->mutex);

		// This wait is just here to clear potentially pending conditions on
		// MS-Windows. Therefore only wait for 1.1 msecs at most:
		PsychTimedWaitCondition(&capdev->condition, &capdev->mutex, 0.0011);

		// Wait for first frame to become available, but only if return of videodata is
		// actually enabled:
		if (!(capdev->recordingflags & 4)) {
			while (capdev->frameAvail == 0) {
				if (PsychPrefStateGet_Verbosity() > 5) {
					printf("PTB-DEBUG: Waiting for real start: fA = %i pA = %i fps=%f\n", capdev->frameAvail, capdev->preRollAvail, capdev->fps);
					fflush(NULL);
				}
				PsychTimedWaitCondition(&capdev->condition, &capdev->mutex, 10.0);
			}
		}

		// Assign a plausible framerate if none assigned properly:
		if (capdev->fps <= 0) capdev->fps = capturerate;

		// Ok, capture is now started:
		capdev->grabber_active = 1;

		PsychUnlockMutex(&capdev->mutex);

		// Record real start time:
		PsychGetAdjustedPrecisionTimerSeconds(startattime);

		// Some processing time for message dispatch:
		PsychGSProcessVideoContext(capdev->VideoContext, FALSE);

		if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: Capture engine fully running...\n");
		
		/* // Allocate conversion buffer if needed for YUV->RGB conversions.
		if (capdev->pixeldepth == -1) {
			// Not used at the moment!!
			// Software conversion of YUV -> RGB needed. Allocate a proper scratch-buffer:
			capdev->scratchbuffer = malloc(capdev->frame_width * capdev->frame_height * 3);
		}
		*/

		if(PsychPrefStateGet_Verbosity() > 3) {
			printf("PTB-INFO: Capture started on device %i - Input video resolution %i x %i - Framerate: %f fps.\n",
			       capturehandle, capdev->width, capdev->height, capdev->fps);
		}
	}
	else {
		// Stop capture:
		if (capdev->grabber_active) {
			// Store a backup copy of pipeline basetime for use in offline frame fetch:
			capdev->lastSavedBaseTime = gst_element_get_base_time(camera);

			// Video framerate converter attached?
			if (capdev->videorate_filter) {
				// Query its stats in dropped and duplicated frames:
				g_object_get(G_OBJECT(capdev->videorate_filter),
					     "in", &nrInFrames,
					     "out", &nrOutFrames,
					     "drop", &nrDroppedFrames,
					     "duplicate", &nrDuplicatedFrames,
					     NULL);
			}

			// Stop video recording if requested:
			if (usecamerabin && capdev->recording_active) {
				PsychGSProcessVideoContext(capdev->VideoContext, FALSE);

				if(PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Stopping video recording...\n");
				g_signal_emit_by_name (camera, "capture-stop", 0);

				if(PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Stopping pipeline [playing -> paused]\n");
				if (!PsychVideoPipelineSetState(camera, GST_STATE_PAUSED, 10.0)) {
					if(PsychPrefStateGet_Verbosity() > 0) {
						PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
						printf("PTB-ERROR: StopVideoCapture: Unable to pause recording pipeline! Prepare for trouble!\n");
					}
				}

				if(PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Videorecording stopped.\n");
			}

			// Stop pipeline, bring it back into READY state:
			if(PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Fully stopping and shutting down capture pipeline.\n");
			if (!PsychVideoPipelineSetState(camera, (usecamerabin) ? GST_STATE_READY : GST_STATE_PAUSED, 10.0)) {
				if(PsychPrefStateGet_Verbosity() > 0) {
					PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
					printf("PTB-ERROR: StopVideoCapture: Unable to stop capture pipeline [Transition 1 to ready state failed]! Prepare for trouble!\n");
				}
			}
			else {
				// Capture stopped. More cleanup work:
				PsychGSProcessVideoContext(capdev->VideoContext, FALSE);
				if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Stopped.\n");

				// Drain any queued buffers, if requested:
				if (dropframes) {
					drainedCount = PsychGSDrainBufferQueue(capdev, INT_MAX, 0);
					if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: StopVideoCapture: Drain of %i buffers completed. GStreamer idle, cleaning up...\n", drainedCount);
				}
			}

			// Ok, capture is now stopped.
			capdev->grabber_active = 0;
			
			if (capdev->scratchbuffer) {
				// Release scratch-buffer:
				free(capdev->scratchbuffer);
				capdev->scratchbuffer = NULL;
			}

			if (PsychPrefStateGet_Verbosity() > 3) {
				// Output count of dropped frames:
				if ((dropped=capdev->nr_droppedframes) > 0) {
					printf("PTB-INFO: Video live capture dropped at least %i frames on device %i to keep capture running in sync with realtime.\n", dropped, capturehandle); 
				}

				if (capdev->videorate_filter) {
					printf("PTB-INFO: Framerate compensation received %i frames, delivered %i frames, had to drop %i frames and duplicate %i frames\n",
					       (int) nrInFrames, (int) nrOutFrames, (int) nrDroppedFrames, (int) nrDuplicatedFrames);
					printf("PTB-INFO: to compensate for framerate fluctuations or mismatch between expected vs. real framerate on device %i.\n", capturehandle);
				}

				if (capdev->nrframes>0) capdev->avg_decompresstime/= (double) capdev->nrframes;
				printf("PTB-INFO: Average time spent in video decompressor (waiting/polling for new frames) was %f milliseconds.\n", (float) capdev->avg_decompresstime * 1000.0f);
				if (capdev->nrgfxframes>0) capdev->avg_gfxtime/= (double) capdev->nrgfxframes;
				printf("PTB-INFO: Average time spent in GetCapturedImage (intensity calculation Video->OpenGL texture conversion) was %f milliseconds.\n",  (float) capdev->avg_gfxtime * 1000.0f);
			}
		}
	}
	
	fflush(NULL);

	// Reset framecounters and statistics:
	capdev->nrframes = 0;
	capdev->avg_decompresstime = 0;
	capdev->nrgfxframes = 0;
	capdev->avg_gfxtime = 0;
	
	// Return either the real capture framerate (at start of capture) or count of dropped frames - at end of capture.
	return((capturerate!=0) ? (int) (capdev->fps + 0.5) : dropped);
}


/* CHECKED TODO
*  PsychGSGetTextureFromCapture() -- Create an OpenGL texturemap from a specific videoframe from given capture object.
*
*  win = Window pointer of onscreen window for which a OpenGL texture should be created.
*  capturehandle = Handle to the capture object.
*  checkForImage = >0 == Just check if new image available, 0 == really retrieve the image, blocking if necessary.
*                   2 == Check for new image, block inside this function (if possible) if no image available.
*
*  timeindex = This parameter is currently ignored and reserved for future use.
*  out_texture = Pointer to the Psychtoolbox texture-record where the new texture should be stored.
*  presentation_timestamp = A ptr to a double variable, where the presentation timestamp of the returned frame should be stored.
*  summed_intensity = An optional ptr to a double variable. If non-NULL, then sum of intensities over all channels is calculated and returned.
*  outrawbuffer = An optional ptr to a memory buffer of sufficient size. If non-NULL, the buffer will be filled with the captured raw image data, e.g., for use inside Matlab or whatever...
*  Returns Number of pending or dropped frames after fetch on success (>=0), -1 if no new image available yet, -2 if no new image available and there won't be any in future.
*/
int PsychGSGetTextureFromCapture(PsychWindowRecordType *win, int capturehandle, int checkForImage, double timeindex,
								 PsychWindowRecordType *out_texture, double *presentation_timestamp, double* summed_intensity, rawcapimgdata* outrawbuffer)
{
    PsychVidcapRecordType *capdev;
    GstElement *camera;
    GstBuffer *videoBuffer = NULL;
    gint64 bufferIndex;
    double deltaT = 0;
    GstEvent *event;
    GstClockTime baseTime;

    int waitforframe;
    GLuint texid;
    int w, h;
    double targetdelta, realdelta, frames;
    unsigned int intensity = 0;
    unsigned int count, i, bpp;
    unsigned char* pixptr;
    psych_bool newframe = FALSE;
    double tstart, tend;
    unsigned int pixval, alphacount;
    int error;
    int nrdropped = 0;
    unsigned char* input_image = NULL;


    // Make sure GStreamer is ready:
    PsychGSCheckInit("videocapture");

    // Take start timestamp for timing stats:
    PsychGetAdjustedPrecisionTimerSeconds(&tstart);
	
    // Retrieve device record for handle:
    capdev = PsychGetGSVidcapRecord(capturehandle);

    // Allow context task to do its internal bookkeeping and cleanup work:
    PsychGSProcessVideoContext(capdev->VideoContext, FALSE);

    // If this is a pure audio capture with no video channels, we always return failed,
    // as those certainly don't have movie frames associated.
    if ((capdev->recordingflags & 4) || (capdev->nrVideoTracks == 0)) return((checkForImage) ? -1 : FALSE);

    if (!PsychIsOnscreenWindow(win)) {
        PsychErrorExitMsg(PsychError_user, "You need to pass a handle to an onscreen window, not to something else!");
    }

    // Compute width and height for later creation of textures etc. Need to do this here,
    // so we can return the values for raw data retrieval:
    w = capdev->frame_width;
    h = capdev->frame_height;

    // Size of a single pixel in bytes:
    bpp = capdev->reqpixeldepth;
	
    // If a outrawbuffer struct is provided, we fill it with info needed to allocate a
    // sufficient memory buffer for returned raw image data later on:
    if (outrawbuffer) {
	    outrawbuffer->w = w;
	    outrawbuffer->h = h;
	    outrawbuffer->depth = bpp;
    }
	
    waitforframe = (checkForImage > 1) ? 1:0; // Blocking wait for new image requested?
	
    // A checkForImage 4 means "no op" with the GStreamer capture engine: This is meant to drive
    // a single threaded movie recording engine, ie., grant processing time to it.
    // Our GStreamer engine doesn't need this as it is highly multi-threaded and does all
    // relevant work in the background.
    if (checkForImage == 4) return(0);
	
    // Should we just check for new image?
    if (checkForImage) {
	    // Reset current dropped count to zero:
	    capdev->current_dropped = 0;
	    
	    PsychLockMutex(&capdev->mutex);
	    if (!capdev->frameAvail) {
		    // No new frame available yet:

		    if (capdev->grabber_active == 0) {
			    // Grabber stopped. We'll never get a new image:
			    PsychUnlockMutex(&capdev->mutex);
			    return(-2);
		    }

		    // Blocking wait requested?
		    if (!waitforframe) {
			    // No blocking wait, just return "no new frame yet":
			    PsychUnlockMutex(&capdev->mutex);
			    //printf("PTB-DEBUG: NO NEW FRAME\n");
			    return(-1);
		    }

		    // No new frame available. Perform a blocking wait:
		    PsychTimedWaitCondition(&capdev->condition, &capdev->mutex, 10.0);

		    // Recheck:
		    if (!capdev->frameAvail) {
			    // Game over! Wait timed out after 10 secs.
			    PsychUnlockMutex(&capdev->mutex);
			    if (PsychPrefStateGet_Verbosity()>4) printf("PTB-ERROR: In blocking wait: No new video frame received after timeout of 10 seconds! Aborting fetch.\n");
			    return(-1);
		    }

		    // Have at least one new frame after wait :-)
	    }
	    
	    // New frame available:

	    // Store count of currently queued frames (in addition to the one just fetched).
	    // This is an indication of how well the users script is keeping up with the video stream,
	    // technically the number of frames that would need to be dropped to keep in sync with the
	    // stream.
	    capdev->current_dropped = capdev->frameAvail - 1;

	    //printf("PTB-DEBUG: NEW FRAME %d\n", capdev->frameAvail);
	    
	    // Ok, at least one new frame ready. If more than one frame has queued up and
	    // we are in 'dropframes' mode, ie. we should always deliver the most recent available
	    // frame, then we quickly fetch & discard all queued frames except the last one.
	    while((capdev->dropframes) && ((int) capdev->frameAvail > 1)) {
		    // On frame to dequeue:
		    capdev->frameAvail--;
		    PsychUnlockMutex(&capdev->mutex);

		    // Pull next buffer which is to be dropped:
		    videoBuffer = gst_app_sink_pull_buffer(GST_APP_SINK(capdev->videosink));

		    // Release the capture buffer. Return it to the DMA ringbuffer pool:
		    gst_buffer_unref(videoBuffer);
		    videoBuffer = NULL;

		    // Retry if there are more pending frames to drop:
		    PsychLockMutex(&capdev->mutex);
	    }

	    // Release lock:
	    PsychUnlockMutex(&capdev->mutex);

	    // Update stats for decompression:
	    PsychGetAdjustedPrecisionTimerSeconds(&tend);
	    
	    // Increase counter of decompressed frames:
	    capdev->nrframes++;
	    
	    // Update avg. decompress time:
	    capdev->avg_decompresstime+= (tend - tstart);
	    
	    // Return availability status: At least one new frame available :-)
	    return(0);
    }
    
    // This point is only reached if checkForImage == FALSE, which only happens
    // if a new frame is available in our buffer:    
    PsychLockMutex(&capdev->mutex);

    //printf("PTB-DEBUG: Blocking fetch start %d\n", capdev->frameAvail);
    if (!capdev->frameAvail) {
		// No new frame available but grabber active. Perform a blocking wait:
		if (capdev->grabber_active) PsychTimedWaitCondition(&capdev->condition, &capdev->mutex, 10.0);
		
		// Recheck:
		if (!capdev->frameAvail) {
			// Game over! Wait timed out after 10 secs.
			PsychUnlockMutex(&capdev->mutex);
			if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: No new video frame received after timeout of 10 seconds! Something's wrong. Aborting fetch.\n");
			return(-1);
		}
		
		// At this point we should have at least one frame available.
    }
	
    // We're here with at least one frame available and the mutex lock held.
    if (PsychPrefStateGet_Verbosity()>6) printf("PTB-DEBUG: Pulling from videosink, %d buffers avail...\n", capdev->frameAvail);

    // One less frame available after our fetch:
    capdev->frameAvail--;
    
    // Clamp frameAvail to queue lengths, unless queue length is set to zero, which means "unlimited":
    if ((int) gst_app_sink_get_max_buffers(GST_APP_SINK(capdev->videosink)) < capdev->frameAvail) {
	    if (gst_app_sink_get_max_buffers(GST_APP_SINK(capdev->videosink)) > 0) {
		    capdev->frameAvail = gst_app_sink_get_max_buffers(GST_APP_SINK(capdev->videosink));
	    }
    }
    if (PsychPrefStateGet_Verbosity()>6) printf("PTB-DEBUG: Post-Pulling from videosink, %d buffers avail...\n", capdev->frameAvail);
    
    // This will pull the oldest video buffer from the videosink. It would block if none were available,
    // but that won't happen as we wouldn't reach this statement if none were available. It would return
    // NULL if the stream would be EOS or the pipeline off, but that shouldn't ever happen:
    videoBuffer = gst_app_sink_pull_buffer(GST_APP_SINK(capdev->videosink));

    // We can unlock early, thanks to videosink's internal buffering:
    PsychUnlockMutex(&capdev->mutex);
    
    if (videoBuffer) {
	    // Assign pointer to videoBuffer's data directly: Avoids one full data copy compared to oldstyle method.
	    // input_image points to the image buffer in our cam:
	    input_image = (unsigned char*) (GLuint*) GST_BUFFER_DATA(videoBuffer);
	    
	    // Assign pts presentation timestamp in pipeline stream time and convert to seconds:
	    if (capdev->recordingflags & 64) {
		    // Retrieve raw buffer timestamp - pipeline running time.
		    capdev->current_pts = (double) GST_BUFFER_TIMESTAMP(videoBuffer) / (double) 1e9;
	    } else {
		    // Add base time to convert running time buffer timestamp into absolute time:
		    baseTime = gst_element_get_base_time(capdev->camera);
		    if (baseTime == 0) baseTime = capdev->lastSavedBaseTime;

		    capdev->current_pts = (double) (GST_BUFFER_TIMESTAMP(videoBuffer) + baseTime) / (double) 1e9;

            // Apply corrective offset for GStreamer clock base zero point:
            capdev->current_pts+= gs_startupTime;     
        }
        
	    deltaT = 0.0;
	    if (GST_CLOCK_TIME_IS_VALID(GST_BUFFER_DURATION(videoBuffer)))
		    deltaT = (double) GST_BUFFER_DURATION(videoBuffer) / (double) 1e9;

	    if (PsychPrefStateGet_Verbosity() > 6) {
		    PsychProbeBufferProps(videoBuffer, NULL, NULL, &capdev->fps);
		    printf("Bufferprobe: newfps = %f altfps = %f\n", capdev->fps, (float) ((deltaT > 0) ? 1.0 / deltaT : 0.0));
	    }

	    bufferIndex = GST_BUFFER_OFFSET(videoBuffer);
    } else {
	    if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: No new video frame received in gst_app_sink_pull_buffer! Something's wrong. Aborting fetch.\n");
	    return(-1);
    }
    if (PsychPrefStateGet_Verbosity()>6) printf("PTB-DEBUG: ...done.\n");

    // Presentation timestamp requested?
    if (presentation_timestamp) {
	    // Return it:
	    *presentation_timestamp = capdev->current_pts;
    }
	
    // Synchronous texture fetch: Copy content of capture buffer into a texture:
    // =========================================================================
	
    // Do we want to do something with the image data and have a
    // scratch buffer for color conversion alloc'ed?
    if ((capdev->scratchbuffer) && ((out_texture) || (summed_intensity) || (outrawbuffer))) {
		// Yes. Perform color-conversion YUV->RGB from cameras DMA buffer
		// into the scratch buffer and set scratch buffer as source for
		// all further operations:
		memcpy(capdev->scratchbuffer, input_image, w * h * bpp);
		
		// Ok, at this point we should have a RGB8 texture image ready in scratch_buffer.
		// Set scratch buffer as our new image source for all further processing:
		input_image = (unsigned char*) capdev->scratchbuffer;
    }
	
    // Only setup if really a texture is requested (non-benchmarking mode):
    if (out_texture) {
	    // Activate OpenGL context of target window:
	    PsychSetGLContext(win);
	    
#if PSYCH_SYSTEM == PSYCH_OSX
	    // Explicitely disable Apple's Client storage extensions. For now they are not really useful to us.
	    glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE);
#endif

	    PsychMakeRect(out_texture->rect, 0, 0, w, h);    
	    
	    // Set NULL - special texture object as part of the PTB texture record:
	    out_texture->targetSpecific.QuickTimeGLTexture = NULL;
	    
	    // Set texture orientation as if it were an inverted Offscreen window: Upside-down.
	    out_texture->textureOrientation = 3;
	    
	    // Setup a pointer to our buffer as texture data pointer: Setting memsize to zero
	    // prevents unwanted free() operation in PsychDeleteTexture...
	    out_texture->textureMemorySizeBytes = 0;
	    
	    // Set texture depth: Could be 8, 16, 24 or 32 bpp.
	    out_texture->depth = capdev->reqpixeldepth * 8;
	    
	    // 4-channel textures are aligned on 4 Byte boundaries because texels are RGBA8:
	    out_texture->textureByteAligned = (capdev->reqpixeldepth == 4) ? 4 : 1;

	    // This will retrieve an OpenGL compatible pointer to the pixel data and assign it to our texmemptr:
	    out_texture->textureMemory = (GLuint*) input_image;
	    
	    // Special case depths == 2, aka YCBCR texture?
	    if ((capdev->reqpixeldepth == 2) && (win->gfxcaps & kPsychGfxCapUYVYTexture)) {
		// GPU supports UYVY textures and we get data in that YCbCr format. Tell
		// texture creation routine to use this optimized format:
		if (!glewIsSupported("GL_APPLE_ycbcr_422")) {
		    // No support for more powerful Apple extension. Use Linux MESA extension:
		    out_texture->textureinternalformat = GL_YCBCR_MESA;
		    out_texture->textureexternalformat = GL_YCBCR_MESA;
		} else {
		    // Apple extension supported:
		    out_texture->textureinternalformat = GL_RGB;
		    out_texture->textureexternalformat = GL_YCBCR_422_APPLE;
		}
		// Same enumerant for Apple and Mesa:
		out_texture->textureexternaltype   = GL_UNSIGNED_SHORT_8_8_MESA;
	    }

	    // Let PsychCreateTexture() do the rest of the job of creating, setting up and
	    // filling an OpenGL texture with content:
	    PsychCreateTexture(out_texture);
	    
	    // Ready to use the texture...
    }
    
    // Sum of pixel intensities requested?
    if(summed_intensity) {
	    pixptr = (unsigned char*) input_image;
	    count  = w * h * bpp;
	    for (i=0; i<count; i++) intensity+=(unsigned int) pixptr[i];
	    *summed_intensity = ((double) intensity) / w / h / bpp;
    }
    
    // Raw data requested?
    if (outrawbuffer) {
	    // Copy it out:
	    outrawbuffer->w = w;
	    outrawbuffer->h = h;
	    outrawbuffer->depth = bpp;
	    count = (w * h * outrawbuffer->depth);
	    memcpy(outrawbuffer->data, (const void *) input_image, count);
    }
	
    // Release the capture buffer. Return it to the DMA ringbuffer pool:
    gst_buffer_unref(videoBuffer);
    videoBuffer = NULL;

    // Update total count of dropped (or pending) frames:
    capdev->nr_droppedframes += capdev->current_dropped;
    nrdropped = capdev->current_dropped;
    capdev->current_dropped = 0;
	
    // Timestamping:
    PsychGetAdjustedPrecisionTimerSeconds(&tend);
	
    // Increase counter of retrieved textures:
    capdev->nrgfxframes++;
	
    // Update average time spent in texture conversion:
    capdev->avg_gfxtime+= (tend - tstart);
    
    // We're successfully done! Return number of dropped (or pending in DMA ringbuffer) frames:
    return(nrdropped);
}

// CHECKED
/* Set capture device specific parameters:
* Currently, the named parameters are a subset of the parameters supported by the
* IIDC specification, mapped to more convenient names.
*
* Input: pname = Name string to specify the parameter.
*        value = Either DBL_MAX to not set but only query the parameter, or some other
*                value, that we try to set in the Firewire camera.
*
* Returns: Old value of the setting
*/
double PsychGSVideoCaptureSetParameter(int capturehandle, const char* pname, double value)
{
	unsigned int minval, maxval, intval, oldintval;
	int triggercount;

	float oldfvalue = FLT_MAX;
	double oldvalue = DBL_MAX; // Initialize return value to the "unknown/unsupported" default.
	psych_bool assigned = false;
	psych_bool present  = false;
	GstColorBalance* cb = NULL;
	GList* cl = NULL;
	GList* iter = NULL;
	GstColorBalanceChannel* cc = NULL;

	// Retrieve device record for handle:
	PsychVidcapRecordType* capdev = PsychGetGSVidcapRecord(capturehandle);

	// Make sure GStreamer is ready:
	PsychGSCheckInit("videocapture");

	if (usecamerabin && gst_element_implements_interface(capdev->camera, GST_TYPE_COLOR_BALANCE)) {
		cb = GST_COLOR_BALANCE(capdev->camera);
	} else {
		if (usecamerabin && (PsychPrefStateGet_Verbosity() > 1)) printf("PTB-WARNING: Camerabin does not suppport GstColorBalance interface as expected.\n");
	}
	
	oldintval = 0xFFFFFFFF;
	
	// Round value to integer:
	intval = (int) (value + 0.5);
	
	// Set a new target movie name for video recordings:
	if (strstr(pname, "SetNewMoviename=")) {
		// Find start of movie namestring and assign to pname:
		pname = strstr(pname, "=");
		pname++;

		// Child protection:
		if (!capdev->recording_active) {
			if (PsychPrefStateGet_Verbosity() > 1) {
				printf("PTB-WARNING: Tried to change name of target movie file on device %i, but recording not enabled on that device! Ignored.\n", capturehandle);
			}
			return(-2);
		}

		// Can't reassign new codec without reopening the device:
		if (strstr(pname, ":CodecType")) {
			*(strstr(pname, ":CodecType")) = 0;
			if (PsychPrefStateGet_Verbosity() > 1) {
				printf("PTB-WARNING: Tried to change recording codec on device %i, but this isn't possible without reopening the device. Ignored.\n", capturehandle);
			}
		}

		// Release old movie name:
		if (capdev->targetmoviefilename) free(capdev->targetmoviefilename);
		capdev->targetmoviefilename = NULL;

		// Assign new movie name:
		capdev->targetmoviefilename = strdup(pname);

		if (PsychPrefStateGet_Verbosity() > 2) {
			printf("PTB-INFO: Changed name of movie file for recording on device %i to '%s'.\n", capturehandle, pname);
		}

		return(0);
	}

	// Check parameter name pname and call the appropriate subroutine:
	if (strcmp(pname, "TriggerCount")==0 || strcmp(pname, "WaitTriggerCount")==0) {
		// Query of cameras internal trigger counter or waiting for a specific
		// value in the counter requested. Trigger counters are special features,
		// (so called "Smart Features" or "Advanced Features" in the IIDC spec)
		// which are only available on selected cameras.
		// We currently only know how to do this on Basler cameras.
		return(-2);
	}
	
	if (strcmp(pname, "PrintParameters")==0) {
		// Special command: List and print all features...
		printf("PTB-INFO: The video source provides the following controllable parameters:\n");
		printf("PTB-INFO: ----------------------------------------------------------------\n\n");
		printf("PTB-INFO: Optional parameters - may or may not be supported:\n");
		printf("PTB-INFO: Shutter, Aperture, EVCompensation, Flickermode, Whitebalancemode,\n");
		printf("PTB-INFO: Flashmode, Scenemode, Focusmode\n\n");
		printf("PTB-INFO: These are definitely supported by the connected camera:\n");


		if (cb) {
			// Enumerate all color balance channels:
			cl = (GList*) gst_color_balance_list_channels(cb);
			for (iter = g_list_first(cl); iter != NULL ; iter = g_list_next(iter)) {
				cc = (GstColorBalanceChannel*) iter->data;
				printf("PTB-INFO: '%s'\t\t min=%i\t : max=%i\t : current=%i\n", (char*) cc->label,
				(int) cc->min_value, (int) cc->max_value, (int) gst_color_balance_get_value(cb, cc));
			}
		}
		printf("PTB-INFO: ----------------------------------------------------------------\n\n");
		return(0);
	}

	// Return current framerate:
	if (strcmp(pname, "GetFramerate")==0) {
		PsychCopyOutDoubleArg(1, FALSE, capdev->fps);
		return(0);
	}
	
	// Return current ROI of camera, as requested (and potentially modified during
	// PsychOpenCaptureDevice(). This is a read-only parameter, as the ROI can
	// only be set during Screen('OpenVideoCapture').
	if (strcmp(pname, "GetROI")==0) {
		PsychCopyOutRectArg(1, FALSE, capdev->roirect);
		return(0);
	}
	
	// Return vendor name string:
	if (strcmp(pname, "GetVendorname")==0) {
		PsychCopyOutCharArg(1, FALSE, "Unknown Vendor");
		return(0);
	}
	
	// Return model name string:
	if (strcmp(pname, "GetModelname")==0) {
		PsychCopyOutCharArg(1, FALSE, capdev->cameraFriendlyName);
		return(0);
	}

	// All code below this check is for camerabin only:
	if (!usecamerabin) {
		// No camerabin, no way to query this stuff. Just fail
		return(DBL_MAX);
	}

	if (strstr(pname, "Shutter")!=0) {
		// Query old "exposure" setting, which is duration of shutter open:
		g_object_get(capdev->camera, "exposure", &oldintval, NULL);
		oldvalue = (double) oldintval / 1e9;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) value = 0;

		// Optionally set new setting:
		if (value != DBL_MAX) g_object_set(capdev->camera, "exposure", (int) (value * 1e9), NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Aperture")) {
		// Query old "aperture" setting, which is the amount of lens opening:
		g_object_get(capdev->camera, "aperture", &oldintval, NULL);
		oldvalue = (double) oldintval;

		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 255) intval = 255;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 0; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "aperture", intval, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "EVCompensation")!=0) {
		// Query old "ev-compensation" setting, which is duration of shutter open:
		g_object_get(capdev->camera, "ev-compensation", &oldfvalue, NULL);
		oldvalue = (double) oldfvalue;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) value = 0;

		// Optionally set new setting:
		if (value != DBL_MAX) g_object_set(capdev->camera, "ev-compensation", (float) value, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Flickermode")) {
		// Query old "flicker-mode" setting:
		g_object_get(capdev->camera, "flicker-mode", &oldintval, NULL);
		oldvalue = (double) oldintval;

		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 3) intval = 3;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 3; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "flicker-mode", intval, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Whitebalancemode")) {
		// Query old "white-balance-mode" setting:
		g_object_get(capdev->camera, "white-balance-mode", &oldintval, NULL);
		oldvalue = (double) oldintval;

		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 5) intval = 5;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 0; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "white-balance-mode", intval, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Focusmode")) {
		// Query old "focus-mode" setting:
		g_object_get(capdev->camera, "focus-mode", &oldintval, NULL);
		oldvalue = (double) oldintval;

		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 7) intval = 7;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 0; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "focus-mode", intval, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Flashmode")) {
		// Query old "flash-mode" setting:
		g_object_get(capdev->camera, "flash-mode", &oldintval, NULL);
		oldvalue = (double) oldintval;


		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 4) intval = 4;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 0; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "flash-mode", intval, NULL);
		return(oldvalue);
	}

	if (strstr(pname, "Scenemode")) {
		// Query old "scene-mode" setting:
		g_object_get(capdev->camera, "scene-mode", &oldintval, NULL);
		oldvalue = (double) oldintval;

		// Optionally set new setting:
		if (intval < 0) intval = 0;
		if (intval > 6) intval = 6;

		// Reset to auto-mode, if requested:
		if (strstr(pname, "Auto")) { intval = 6; value = 0; }

		if (value != DBL_MAX) g_object_set(capdev->camera, "scene-mode", intval, NULL);
		return(oldvalue);
	}

	// Not yet matched? Try if it matches one of the color channel properties
	// from the color balance interface.
	if (cb) {
		// Search all color balance channels:
		cl = (GList*) gst_color_balance_list_channels(cb);
		for (iter = g_list_first(cl); iter != NULL ; iter = g_list_next(iter)) {
			cc = (GstColorBalanceChannel*) iter->data;

			// Match?
			if (strcmp((const char*) cc->label, (const char*) pname) == 0) {
				assigned = TRUE;

				// Query and return old setting:
				oldvalue = (double) gst_color_balance_get_value(cb, cc);

				// Optionally assign new setting:
				if (intval < (int) cc->min_value) intval = (int) cc->min_value;
				if (intval > (int) cc->max_value) intval = (int) cc->max_value;
				if (value != DBL_MAX) gst_color_balance_set_value(cb, cc, intval);
			}
		}

		if (!assigned) {
			if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Screen('SetVideoCaptureParameter', ...) called with unknown parameter %s. Ignored...\n", pname);
		}

		return(oldvalue);
	}

	return(DBL_MAX);
}

#endif