forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcap_gstreamer.cpp
More file actions
1729 lines (1506 loc) · 51.7 KB
/
cap_gstreamer.cpp
File metadata and controls
1729 lines (1506 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2008, 2011, Nils Hasler, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
/*!
* \file cap_gstreamer.cpp
* \author Nils Hasler <hasler@mpi-inf.mpg.de>
* Max-Planck-Institut Informatik
* \author Dirk Van Haerenborgh <vhdirk@gmail.com>
*
* \brief Use GStreamer to read/write video
*/
#include "precomp.hpp"
#include <unistd.h>
#include <string.h>
#include <gst/gst.h>
#include <gst/gstbuffer.h>
#include <gst/video/video.h>
#include <gst/app/gstappsink.h>
#include <gst/app/gstappsrc.h>
#include <gst/riff/riff-media.h>
#include <gst/pbutils/missing-plugins.h>
#define VERSION_NUM(major, minor, micro) (major * 1000000 + minor * 1000 + micro)
#define FULL_GST_VERSION VERSION_NUM(GST_VERSION_MAJOR, GST_VERSION_MINOR, GST_VERSION_MICRO)
#if FULL_GST_VERSION >= VERSION_NUM(0,10,32)
#include <gst/pbutils/encoding-profile.h>
//#include <gst/base/gsttypefindhelper.h>
#endif
#ifdef NDEBUG
#define CV_WARN(message)
#else
#define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__)
#endif
#if GST_VERSION_MAJOR == 0
#define COLOR_ELEM "ffmpegcolorspace"
#define COLOR_ELEM_NAME "ffmpegcsp"
#elif FULL_GST_VERSION < VERSION_NUM(1,5,0)
#define COLOR_ELEM "videoconvert"
#define COLOR_ELEM_NAME COLOR_ELEM
#else
#define COLOR_ELEM "autovideoconvert"
#define COLOR_ELEM_NAME COLOR_ELEM
#endif
void toFraction(double decimal, double &numerator, double &denominator);
void handleMessage(GstElement * pipeline);
static cv::Mutex gst_initializer_mutex;
/*!
* \brief The gst_initializer class
* Initializes gstreamer once in the whole process
*/
class gst_initializer
{
public:
static void init()
{
gst_initializer_mutex.lock();
static gst_initializer init;
gst_initializer_mutex.unlock();
}
private:
gst_initializer()
{
gst_init(NULL, NULL);
// gst_debug_set_active(1);
// gst_debug_set_colored(1);
// gst_debug_set_default_threshold(GST_LEVEL_INFO);
}
};
/*!
* \brief The CvCapture_GStreamer class
* Use GStreamer to capture video
*/
class CvCapture_GStreamer : public CvCapture
{
public:
CvCapture_GStreamer() { init(); }
virtual ~CvCapture_GStreamer() { close(); }
virtual bool open( int type, const char* filename );
virtual void close();
virtual double getProperty(int);
virtual bool setProperty(int, double);
virtual bool grabFrame();
virtual IplImage* retrieveFrame(int);
protected:
void init();
bool reopen();
bool isPipelinePlaying();
void startPipeline();
void stopPipeline();
void restartPipeline();
void setFilter(const char* prop, int type, int v1, int v2 = 0);
void removeFilter(const char *filter);
static void newPad(GstElement *myelement,
GstPad *pad,
gpointer data);
GstElement* pipeline;
GstElement* uridecodebin;
GstElement* v4l2src;
GstElement* color;
GstElement* sink;
#if GST_VERSION_MAJOR > 0
GstSample* sample;
GstMapInfo* info;
#endif
GstBuffer* buffer;
GstCaps* caps;
IplImage* frame;
gint64 duration;
gint width;
gint height;
double fps;
};
/*!
* \brief CvCapture_GStreamer::init
* inits the class
*/
void CvCapture_GStreamer::init()
{
pipeline = NULL;
uridecodebin = NULL;
v4l2src = NULL;
color = NULL;
sink = NULL;
#if GST_VERSION_MAJOR > 0
sample = NULL;
info = new GstMapInfo;
#endif
buffer = NULL;
caps = NULL;
frame = NULL;
duration = -1;
width = -1;
height = -1;
fps = -1;
}
/*!
* \brief CvCapture_GStreamer::close
* Closes the pipeline and destroys all instances
*/
void CvCapture_GStreamer::close()
{
if (isPipelinePlaying())
this->stopPipeline();
if(pipeline) {
gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL);
gst_object_unref(GST_OBJECT(pipeline));
pipeline = NULL;
}
duration = -1;
width = -1;
height = -1;
fps = -1;
}
/*!
* \brief CvCapture_GStreamer::grabFrame
* \return
* Grabs a sample from the pipeline, awaiting consumation by retreiveFrame.
* The pipeline is started if it was not running yet
*/
bool CvCapture_GStreamer::grabFrame()
{
if(!pipeline)
return false;
// start the pipeline if it was not in playing state yet
if(!this->isPipelinePlaying())
this->startPipeline();
// bail out if EOS
if(gst_app_sink_is_eos(GST_APP_SINK(sink)))
return false;
#if GST_VERSION_MAJOR == 0
if(buffer)
gst_buffer_unref(buffer);
buffer = gst_app_sink_pull_buffer(GST_APP_SINK(sink));
#else
if(sample)
gst_sample_unref(sample);
sample = gst_app_sink_pull_sample(GST_APP_SINK(sink));
if(!sample)
return false;
buffer = gst_sample_get_buffer(sample);
#endif
if(!buffer)
return false;
return true;
}
/*!
* \brief CvCapture_GStreamer::retrieveFrame
* \return IplImage pointer. [Transfer Full]
* Retreive the previously grabbed buffer, and wrap it in an IPLImage structure
*/
IplImage * CvCapture_GStreamer::retrieveFrame(int)
{
if(!buffer)
return 0;
//construct a frame header if we did not have any yet
if(!frame)
{
#if GST_VERSION_MAJOR == 0
GstCaps* buffer_caps = gst_buffer_get_caps(buffer);
#else
GstCaps* buffer_caps = gst_sample_get_caps(sample);
#endif
// bail out in no caps
assert(gst_caps_get_size(buffer_caps) == 1);
GstStructure* structure = gst_caps_get_structure(buffer_caps, 0);
// bail out if width or height are 0
if(!gst_structure_get_int(structure, "width", &width) ||
!gst_structure_get_int(structure, "height", &height))
{
gst_caps_unref(buffer_caps);
return 0;
}
int depth = 3;
#if GST_VERSION_MAJOR > 0
depth = 0;
const gchar* name = gst_structure_get_name(structure);
const gchar* format = gst_structure_get_string(structure, "format");
if (!name || !format)
return 0;
// we support 3 types of data:
// video/x-raw, format=BGR -> 8bit, 3 channels
// video/x-raw, format=GRAY8 -> 8bit, 1 channel
// video/x-bayer -> 8bit, 1 channel
// bayer data is never decoded, the user is responsible for that
// everything is 8 bit, so we just test the caps for bit depth
if (strcasecmp(name, "video/x-raw") == 0)
{
if (strcasecmp(format, "BGR") == 0) {
depth = 3;
}
else if(strcasecmp(format, "GRAY8") == 0){
depth = 1;
}
}
else if (strcasecmp(name, "video/x-bayer") == 0)
{
depth = 1;
}
#endif
if (depth > 0) {
frame = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, depth);
} else {
gst_caps_unref(buffer_caps);
return 0;
}
gst_caps_unref(buffer_caps);
}
// gstreamer expects us to handle the memory at this point
// so we can just wrap the raw buffer and be done with it
#if GST_VERSION_MAJOR == 0
frame->imageData = (char *)GST_BUFFER_DATA(buffer);
#else
// the data ptr in GstMapInfo is only valid throughout the mapifo objects life.
// TODO: check if reusing the mapinfo object is ok.
gboolean success = gst_buffer_map(buffer,info, (GstMapFlags)GST_MAP_READ);
if (!success){
//something weird went wrong here. abort. abort.
//fprintf(stderr,"GStreamer: unable to map buffer");
return 0;
}
frame->imageData = (char*)info->data;
gst_buffer_unmap(buffer,info);
#endif
return frame;
}
/*!
* \brief CvCapture_GStreamer::isPipelinePlaying
* \return if the pipeline is currently playing.
*/
bool CvCapture_GStreamer::isPipelinePlaying()
{
GstState current, pending;
GstClockTime timeout = 5*GST_SECOND;
if(!GST_IS_ELEMENT(pipeline)){
return false;
}
GstStateChangeReturn ret = gst_element_get_state(GST_ELEMENT(pipeline),¤t, &pending, timeout);
if (!ret){
//fprintf(stderr, "GStreamer: unable to query pipeline state\n");
return false;
}
return current == GST_STATE_PLAYING;
}
/*!
* \brief CvCapture_GStreamer::startPipeline
* Start the pipeline by setting it to the playing state
*/
void CvCapture_GStreamer::startPipeline()
{
CV_FUNCNAME("icvStartPipeline");
__BEGIN__;
//fprintf(stderr, "relinked, pausing\n");
GstStateChangeReturn status = gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_PLAYING);
if (status == GST_STATE_CHANGE_ASYNC)
{
// wait for status update
status = gst_element_get_state(pipeline, NULL, NULL, GST_CLOCK_TIME_NONE);
}
if (status == GST_STATE_CHANGE_FAILURE)
{
handleMessage(pipeline);
gst_object_unref(pipeline);
pipeline = NULL;
CV_ERROR(CV_StsError, "GStreamer: unable to start pipeline\n");
return;
}
//printf("state now playing\n");
handleMessage(pipeline);
__END__;
}
/*!
* \brief CvCapture_GStreamer::stopPipeline
* Stop the pipeline by setting it to NULL
*/
void CvCapture_GStreamer::stopPipeline()
{
CV_FUNCNAME("icvStopPipeline");
__BEGIN__;
//fprintf(stderr, "restarting pipeline, going to ready\n");
if(gst_element_set_state(GST_ELEMENT(pipeline), GST_STATE_NULL) ==
GST_STATE_CHANGE_FAILURE) {
CV_ERROR(CV_StsError, "GStreamer: unable to stop pipeline\n");
gst_object_unref(pipeline);
pipeline = NULL;
return;
}
__END__;
}
/*!
* \brief CvCapture_GStreamer::restartPipeline
* Restart the pipeline
*/
void CvCapture_GStreamer::restartPipeline()
{
handleMessage(pipeline);
this->stopPipeline();
this->startPipeline();
}
/*!
* \brief CvCapture_GStreamer::setFilter
* \param prop the property name
* \param type glib property type
* \param v1 the value
* \param v2 second value of property type requires it, else NULL
* Filter the output formats by setting appsink caps properties
*/
void CvCapture_GStreamer::setFilter(const char *prop, int type, int v1, int v2)
{
//printf("GStreamer: setFilter \n");
if(!caps || !( GST_IS_CAPS (caps) ))
{
if(type == G_TYPE_INT)
{
#if GST_VERSION_MAJOR == 0
caps = gst_caps_new_simple("video/x-raw-rgb", prop, type, v1, NULL);
#else
caps = gst_caps_new_simple("video/x-raw","format",G_TYPE_STRING,"BGR", prop, type, v1, NULL);
#endif
}
else
{
#if GST_VERSION_MAJOR == 0
caps = gst_caps_new_simple("video/x-raw-rgb", prop, type, v1, v2, NULL);
#else
caps = gst_caps_new_simple("video/x-raw","format",G_TYPE_STRING,"BGR", prop, type, v1, v2, NULL);
#endif
}
}
else
{
#if GST_VERSION_MAJOR > 0
if (! gst_caps_is_writable(caps))
caps = gst_caps_make_writable (caps);
#endif
if(type == G_TYPE_INT){
gst_caps_set_simple(caps, prop, type, v1, NULL);
}else{
gst_caps_set_simple(caps, prop, type, v1, v2, NULL);
}
}
#if GST_VERSION_MAJOR > 0
caps = gst_caps_fixate(caps);
#endif
gst_app_sink_set_caps(GST_APP_SINK(sink), caps);
//printf("filtering with %s\n", gst_caps_to_string(caps));
}
/*!
* \brief CvCapture_GStreamer::removeFilter
* \param filter filter to remove
* remove the specified filter from the appsink template caps
*/
void CvCapture_GStreamer::removeFilter(const char *filter)
{
if(!caps)
return;
#if GST_VERSION_MAJOR > 0
if (! gst_caps_is_writable(caps))
caps = gst_caps_make_writable (caps);
#endif
GstStructure *s = gst_caps_get_structure(caps, 0);
gst_structure_remove_field(s, filter);
gst_app_sink_set_caps(GST_APP_SINK(sink), caps);
}
/*!
* \brief CvCapture_GStreamer::newPad link dynamic padd
* \param pad
* \param data
* decodebin creates pads based on stream information, which is not known upfront
* on receiving the pad-added signal, we connect it to the colorspace conversion element
*/
void CvCapture_GStreamer::newPad(GstElement * /*elem*/,
GstPad *pad,
gpointer data)
{
GstPad *sinkpad;
GstElement *color = (GstElement *) data;
sinkpad = gst_element_get_static_pad (color, "sink");
if (!sinkpad){
//fprintf(stderr, "Gstreamer: no pad named sink\n");
return;
}
gst_pad_link (pad, sinkpad);
gst_object_unref (sinkpad);
}
/*!
* \brief CvCapture_GStreamer::open Open the given file with gstreamer
* \param type CvCapture type. One of CV_CAP_GSTREAMER_*
* \param filename Filename to open in case of CV_CAP_GSTREAMER_FILE
* \return boolean. Specifies if opening was succesful.
*
* In case of CV_CAP_GSTREAMER_V4L(2), a pipelin is constructed as follows:
* v4l2src ! autoconvert ! appsink
*
*
* The 'filename' parameter is not limited to filesystem paths, and may be one of the following:
*
* - a normal filesystem path:
* e.g. video.avi or /path/to/video.avi or C:\\video.avi
* - an uri:
* e.g. file:///path/to/video.avi or rtsp:///path/to/stream.asf
* - a gstreamer pipeline description:
* e.g. videotestsrc ! videoconvert ! appsink
* the appsink name should be either 'appsink0' (the default) or 'opencvsink'
*
* When dealing with a file, CvCapture_GStreamer will not drop frames if the grabbing interval
* larger than the framerate period. (Unlike the uri or manual pipeline description, which assume
* a live source)
*
* The pipeline will only be started whenever the first frame is grabbed. Setting pipeline properties
* is really slow if we need to restart the pipeline over and over again.
*
* TODO: the 'type' parameter is imo unneeded. for v4l2, filename 'v4l2:///dev/video0' can be used.
* I expect this to be the same for CV_CAP_GSTREAMER_1394. Is anyone actually still using v4l (v1)?
*
*/
bool CvCapture_GStreamer::open( int type, const char* filename )
{
CV_FUNCNAME("cvCaptureFromCAM_GStreamer");
__BEGIN__;
gst_initializer::init();
bool file = false;
bool stream = false;
bool manualpipeline = false;
char *uri = NULL;
uridecodebin = NULL;
GstElementFactory * testfac;
GstStateChangeReturn status;
int cameraID = -1;
if (type == CV_CAP_GSTREAMER_V4L ||
type == CV_CAP_GSTREAMER_V4L2)
{
cameraID = static_cast<int>(reinterpret_cast<intptr_t>(filename));
}
std::stringstream stdstream;
std::string stdfilename;
if (type == CV_CAP_GSTREAMER_V4L)
{
testfac = gst_element_factory_find("v4lsrc");
if (!testfac){
return false;
}
g_object_unref(G_OBJECT(testfac));
stdstream << "v4lsrc device=/dev/video" << cameraID << " ! " << COLOR_ELEM << " ! appsink";
stdfilename = stdstream.str();
filename = stdfilename.c_str();
}
else if (type == CV_CAP_GSTREAMER_V4L2)
{
testfac = gst_element_factory_find("v4l2src");
if (!testfac){
return false;
}
g_object_unref(G_OBJECT(testfac));
stdstream << "v4l2src device=/dev/video" << cameraID << " ! " << COLOR_ELEM << " ! appsink";
stdfilename = stdstream.str();
filename = stdfilename.c_str();
}
// test if we have a valid uri. If so, open it with an uridecodebin
// else, we might have a file or a manual pipeline.
// if gstreamer cannot parse the manual pipeline, we assume we were given and
// ordinary file path.
if(!gst_uri_is_valid(filename))
{
uri = realpath(filename, NULL);
stream = false;
if(uri)
{
uri = g_filename_to_uri(uri, NULL, NULL);
if(uri)
{
file = true;
}
else
{
CV_WARN("GStreamer: Error opening file\n");
close();
return false;
}
}
else
{
GError *err = NULL;
uridecodebin = gst_parse_launch(filename, &err);
if(!uridecodebin)
{
fprintf(stderr, "GStreamer: Error opening bin: %s\n", err->message);
return false;
}
stream = true;
manualpipeline = true;
}
}
else
{
stream = true;
uri = g_strdup(filename);
}
bool element_from_uri = false;
if(!uridecodebin)
{
// At this writing, the v4l2 element (and maybe others too) does not support caps renegotiation.
// This means that we cannot use an uridecodebin when dealing with v4l2, since setting
// capture properties will not work.
// The solution (probably only until gstreamer 1.2) is to make an element from uri when dealing with v4l2.
gchar * protocol = gst_uri_get_protocol(uri);
if (!strcasecmp(protocol , "v4l2"))
{
#if GST_VERSION_MAJOR == 0
uridecodebin = gst_element_make_from_uri(GST_URI_SRC, uri, "src");
#else
uridecodebin = gst_element_make_from_uri(GST_URI_SRC, uri, "src", NULL);
#endif
element_from_uri = true;
}
else
{
uridecodebin = gst_element_factory_make("uridecodebin", NULL);
g_object_set(G_OBJECT(uridecodebin), "uri", uri, NULL);
}
g_free(protocol);
if(!uridecodebin)
{
//fprintf(stderr, "GStreamer: Error opening bin: %s\n", err->message);
close();
return false;
}
}
if (manualpipeline)
{
GstIterator *it = gst_bin_iterate_elements(GST_BIN(uridecodebin));
GstElement *element = NULL;
gboolean done = false;
gchar* name = NULL;
#if GST_VERSION_MAJOR > 0
GValue value = G_VALUE_INIT;
#endif
while (!done)
{
#if GST_VERSION_MAJOR > 0
switch (gst_iterator_next (it, &value))
{
case GST_ITERATOR_OK:
element = GST_ELEMENT (g_value_get_object (&value));
#else
switch (gst_iterator_next (it, (gpointer *)&element))
{
case GST_ITERATOR_OK:
#endif
name = gst_element_get_name(element);
if (name)
{
if (strstr(name, "opencvsink") != NULL || strstr(name, "appsink") != NULL)
{
sink = GST_ELEMENT ( gst_object_ref (element) );
}
else if (strstr(name, COLOR_ELEM_NAME) != NULL)
{
color = GST_ELEMENT ( gst_object_ref (element) );
}
else if (strstr(name, "v4l") != NULL)
{
v4l2src = GST_ELEMENT ( gst_object_ref (element) );
}
g_free(name);
done = sink && color && v4l2src;
}
#if GST_VERSION_MAJOR > 0
g_value_unset (&value);
#endif
break;
case GST_ITERATOR_RESYNC:
gst_iterator_resync (it);
break;
case GST_ITERATOR_ERROR:
case GST_ITERATOR_DONE:
done = TRUE;
break;
}
}
gst_iterator_free (it);
if (!sink)
{
CV_ERROR(CV_StsError, "GStreamer: cannot find appsink in manual pipeline\n");
return false;
}
pipeline = uridecodebin;
}
else
{
pipeline = gst_pipeline_new(NULL);
// videoconvert (in 0.10: ffmpegcolorspace, in 1.x autovideoconvert)
//automatically selects the correct colorspace conversion based on caps.
color = gst_element_factory_make(COLOR_ELEM, NULL);
sink = gst_element_factory_make("appsink", NULL);
gst_bin_add_many(GST_BIN(pipeline), uridecodebin, color, sink, NULL);
if(element_from_uri)
{
if(!gst_element_link(uridecodebin, color))
{
CV_ERROR(CV_StsError, "GStreamer: cannot link color -> sink\n");
gst_object_unref(pipeline);
pipeline = NULL;
return false;
}
}
else
{
g_signal_connect(uridecodebin, "pad-added", G_CALLBACK(newPad), color);
}
if(!gst_element_link(color, sink))
{
CV_ERROR(CV_StsError, "GStreamer: cannot link color -> sink\n");
gst_object_unref(pipeline);
pipeline = NULL;
return false;
}
}
//TODO: is 1 single buffer really high enough?
gst_app_sink_set_max_buffers (GST_APP_SINK(sink), 1);
gst_app_sink_set_drop (GST_APP_SINK(sink), stream);
//do not emit signals: all calls will be synchronous and blocking
gst_app_sink_set_emit_signals (GST_APP_SINK(sink), 0);
#if GST_VERSION_MAJOR == 0
caps = gst_caps_new_simple("video/x-raw-rgb",
"bpp", G_TYPE_INT, 24,
"red_mask", G_TYPE_INT, 0x0000FF,
"green_mask", G_TYPE_INT, 0x00FF00,
"blue_mask", G_TYPE_INT, 0xFF0000,
NULL);
#else
// support 1 and 3 channel 8 bit data, as well as bayer (also 1 channel, 8bit)
caps = gst_caps_from_string("video/x-raw, format=(string){BGR, GRAY8}; video/x-bayer,format=(string){rggb,bggr,grbg,gbrg}");
#endif
gst_app_sink_set_caps(GST_APP_SINK(sink), caps);
gst_caps_unref(caps);
{
status = gst_element_set_state(GST_ELEMENT(pipeline),
file ? GST_STATE_PAUSED : GST_STATE_PLAYING);
if (status == GST_STATE_CHANGE_ASYNC)
{
// wait for status update
status = gst_element_get_state(pipeline, NULL, NULL, GST_CLOCK_TIME_NONE);
}
if (status == GST_STATE_CHANGE_FAILURE)
{
handleMessage(pipeline);
gst_object_unref(pipeline);
pipeline = NULL;
CV_ERROR(CV_StsError, "GStreamer: unable to start pipeline\n");
return false;
}
GstFormat format;
format = GST_FORMAT_DEFAULT;
#if GST_VERSION_MAJOR == 0
if(!gst_element_query_duration(sink, &format, &duration))
#else
if(!gst_element_query_duration(sink, format, &duration))
#endif
{
handleMessage(pipeline);
CV_WARN("GStreamer: unable to query duration of stream");
duration = -1;
}
GstPad* pad = gst_element_get_static_pad(color, "src");
#if GST_VERSION_MAJOR == 0
GstCaps* buffer_caps = gst_pad_get_caps(pad);
#else
GstCaps* buffer_caps = gst_pad_get_current_caps(pad);
#endif
const GstStructure *structure = gst_caps_get_structure (buffer_caps, 0);
if (!gst_structure_get_int (structure, "width", &width))
{
CV_WARN("Cannot query video width\n");
}
if (!gst_structure_get_int (structure, "height", &height))
{
CV_WARN("Cannot query video heigth\n");
}
gint num = 0, denom=1;
if(!gst_structure_get_fraction(structure, "framerate", &num, &denom))
{
CV_WARN("Cannot query video fps\n");
}
fps = (double)num/(double)denom;
// GST_DEBUG_BIN_TO_DOT_FILE(GST_BIN(pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "pipeline")
stopPipeline();
}
__END__;
return true;
}
/*!
* \brief CvCapture_GStreamer::getProperty retreive the requested property from the pipeline
* \param propId requested property
* \return property value
*
* There are two ways the properties can be retreived. For seek-based properties we can query the pipeline.
* For frame-based properties, we use the caps of the lasst receivef sample. This means that some properties
* are not available until a first frame was received
*/
double CvCapture_GStreamer::getProperty( int propId )
{
GstFormat format;
gint64 value;
gboolean status;
#if GST_VERSION_MAJOR == 0
#define FORMAT &format
#else
#define FORMAT format
#endif
if(!pipeline) {
CV_WARN("GStreamer: no pipeline");
return 0;
}
switch(propId) {
case CV_CAP_PROP_POS_MSEC:
format = GST_FORMAT_TIME;
status = gst_element_query_position(sink, FORMAT, &value);
if(!status) {
CV_WARN("GStreamer: unable to query position of stream");
return 0;
}
return value * 1e-6; // nano seconds to milli seconds
case CV_CAP_PROP_POS_FRAMES:
format = GST_FORMAT_DEFAULT;
status = gst_element_query_position(sink, FORMAT, &value);
if(!status) {
CV_WARN("GStreamer: unable to query position of stream");
return 0;
}
return value;
case CV_CAP_PROP_POS_AVI_RATIO:
format = GST_FORMAT_PERCENT;
status = gst_element_query_position(sink, FORMAT, &value);
if(!status) {
CV_WARN("GStreamer: unable to query position of stream");
return 0;
}
return ((double) value) / GST_FORMAT_PERCENT_MAX;
case CV_CAP_PROP_FRAME_WIDTH:
return width;
case CV_CAP_PROP_FRAME_HEIGHT:
return height;
case CV_CAP_PROP_FPS:
return fps;
case CV_CAP_PROP_FOURCC:
break;
case CV_CAP_PROP_FRAME_COUNT:
return duration;
case CV_CAP_PROP_FORMAT:
case CV_CAP_PROP_MODE:
case CV_CAP_PROP_BRIGHTNESS:
case CV_CAP_PROP_CONTRAST:
case CV_CAP_PROP_SATURATION:
case CV_CAP_PROP_HUE:
if (v4l2src)
{
const gchar * propName =
propId == CV_CAP_PROP_BRIGHTNESS ? "brightness" :
propId == CV_CAP_PROP_CONTRAST ? "contrast" :
propId == CV_CAP_PROP_SATURATION ? "saturation" :
propId == CV_CAP_PROP_HUE ? "hue" : NULL;
if (propName)
{
gint32 value32 = 0;
g_object_get(G_OBJECT(v4l2src), propName, &value32, NULL);
return value32;
}
}
case CV_CAP_PROP_GAIN:
case CV_CAP_PROP_CONVERT_RGB:
break;
case CV_CAP_GSTREAMER_QUEUE_LENGTH:
if(!sink) {
CV_WARN("GStreamer: there is no sink yet");
return false;
}
return gst_app_sink_get_max_buffers(GST_APP_SINK(sink));
default:
CV_WARN("GStreamer: unhandled property");
break;
}
#undef FORMAT
return 0;
}
/*!
* \brief CvCapture_GStreamer::setProperty
* \param propId
* \param value
* \return success
* Sets the desired property id with val. If the pipeline is running,
* it is briefly stopped and started again after the property was set
*/
bool CvCapture_GStreamer::setProperty( int propId, double value )
{
GstFormat format;
GstSeekFlags flags;
if(!pipeline) {
CV_WARN("GStreamer: no pipeline");
return false;
}
bool wasPlaying = this->isPipelinePlaying();
if (wasPlaying)
this->stopPipeline();
switch(propId) {
case CV_CAP_PROP_POS_MSEC:
format = GST_FORMAT_TIME;
flags = (GstSeekFlags) (GST_SEEK_FLAG_FLUSH|GST_SEEK_FLAG_ACCURATE);
if(!gst_element_seek_simple(GST_ELEMENT(pipeline), format,
flags, (gint64) (value * GST_MSECOND))) {
CV_WARN("GStreamer: unable to seek");