Split out documentation into subfolders.
[platform/upstream/gstreamer.git] / markdown / tutorials / basic / concepts.md
1 # Basic tutorial 2: GStreamer concepts
2
3 ## Goal
4
5 The previous tutorial showed how to build a pipeline automatically. Now
6 we are going to build a pipeline manually by instantiating each element
7 and linking them all together. In the process, we will learn:
8
9   - What is a GStreamer element and how to create one.
10
11   - How to connect elements to each other.
12
13   - How to customize an element's behavior.
14
15   - How to watch the bus for error conditions and extract information
16     from GStreamer messages.
17
18 ## Manual Hello World
19
20 Copy this code into a text file named `basic-tutorial-2.c` (or find it
21 in the SDK installation).
22
23 **basic-tutorial-2.c**
24
25 ``` c
26 #include <gst/gst.h>
27
28 int main(int argc, char *argv[]) {
29   GstElement *pipeline, *source, *sink;
30   GstBus *bus;
31   GstMessage *msg;
32   GstStateChangeReturn ret;
33
34   /* Initialize GStreamer */
35   gst_init (&argc, &argv);
36
37   /* Create the elements */
38   source = gst_element_factory_make ("videotestsrc", "source");
39   sink = gst_element_factory_make ("autovideosink", "sink");
40
41   /* Create the empty pipeline */
42   pipeline = gst_pipeline_new ("test-pipeline");
43
44   if (!pipeline || !source || !sink) {
45     g_printerr ("Not all elements could be created.\n");
46     return -1;
47   }
48
49   /* Build the pipeline */
50   gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL);
51   if (gst_element_link (source, sink) != TRUE) {
52     g_printerr ("Elements could not be linked.\n");
53     gst_object_unref (pipeline);
54     return -1;
55   }
56
57   /* Modify the source's properties */
58   g_object_set (source, "pattern", 0, NULL);
59
60   /* Start playing */
61   ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
62   if (ret == GST_STATE_CHANGE_FAILURE) {
63     g_printerr ("Unable to set the pipeline to the playing state.\n");
64     gst_object_unref (pipeline);
65     return -1;
66   }
67
68   /* Wait until error or EOS */
69   bus = gst_element_get_bus (pipeline);
70   msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
71
72   /* Parse message */
73   if (msg != NULL) {
74     GError *err;
75     gchar *debug_info;
76
77     switch (GST_MESSAGE_TYPE (msg)) {
78       case GST_MESSAGE_ERROR:
79         gst_message_parse_error (msg, &err, &debug_info);
80         g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
81         g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
82         g_clear_error (&err);
83         g_free (debug_info);
84         break;
85       case GST_MESSAGE_EOS:
86         g_print ("End-Of-Stream reached.\n");
87         break;
88       default:
89         /* We should not reach here because we only asked for ERRORs and EOS */
90         g_printerr ("Unexpected message received.\n");
91         break;
92     }
93     gst_message_unref (msg);
94   }
95
96   /* Free resources */
97   gst_object_unref (bus);
98   gst_element_set_state (pipeline, GST_STATE_NULL);
99   gst_object_unref (pipeline);
100   return 0;
101 }
102 ```
103
104 > ![Information](images/icons/emoticons/information.png)
105 > Need help?
106 >
107 > If you need help to compile this code, refer to the **Building the tutorials**  section for your platform: [Linux](installing/on-linux.md#InstallingonLinux-Build), [Mac OS X](installing/on-mac-osx.md#InstallingonMacOSX-Build) or [Windows](installing/on-windows.md#InstallingonWindows-Build), or use this specific command on Linux:
108 >
109 > `` gcc basic-tutorial-2.c -o basic-tutorial-2 `pkg-config --cflags --libs gstreamer-1.0` ``
110 >
111 >If you need help to run this code, refer to the **Running the tutorials** section for your platform: [Linux](installing/on-linux.md#InstallingonLinux-Run), [Mac OS X](installing/on-mac-osx.md#InstallingonMacOSX-Run) or [Windows](installing/on-windows.md#InstallingonWindows-Run).
112 >
113 >This tutorial opens a window and displays a test pattern, without audio
114 >
115 >Required libraries: `gstreamer-1.0`
116
117 ## Walkthrough
118
119 The basic construction block of GStreamer are the elements, which
120 process the data as it flows *downstream* from the source elements (the
121 producers of data) to the sink elements (the consumers of data), passing
122 through filter elements.
123
124 ![](images/figure-1.png)
125
126 **Figure 1**. Example pipeline
127
128 ### Element creation
129
130 We will skip GStreamer initialization, since it is the same as the
131 previous tutorial:
132
133 ``` c
134 /* Create the elements */
135 source = gst_element_factory_make ("videotestsrc", "source");
136 sink = gst_element_factory_make ("autovideosink", "sink");
137 ```
138
139 As seen in this code, new elements can be created
140 with `gst_element_factory_make()`. The first parameter is the type of
141 element to create ([Basic tutorial 14: Handy
142 elements](tutorials/basic/handy-elements.md) shows a
143 few common types, and [Basic tutorial 10: GStreamer
144 tools](tutorials/basic/gstreamer-tools.md) shows how to
145 obtain the list of all available types). The second parameter is the
146 name we want to give to this particular instance. Naming your elements
147 is useful to retrieve them later if you didn't keep a pointer (and for
148 more meaningful debug output). If you pass NULL for the name, however,
149 GStreamer will provide a unique name for you.
150
151 For this tutorial we create two elements: a `videotestsrc` and
152 an `autovideosink`.
153
154 `videotestsrc` is a source element (it produces data), which creates a
155 test video pattern. This element is useful for debugging purposes (and
156 tutorials) and is not usually found in real applications.
157
158 `autovideosink` is a sink element (it consumes data), which displays on
159 a window the images it receives. There exist several video sinks,
160 depending on the operating system, with a varying range of capabilities.
161 `autovideosink` automatically selects and instantiates the best one, so
162 you do not have to worry with the details, and your code is more
163 platform-independent.
164
165 ### Pipeline creation
166
167 ``` c
168 /* Create the empty pipeline */
169 pipeline = gst_pipeline_new ("test-pipeline");
170 ```
171
172 All elements in GStreamer must typically be contained inside a pipeline
173 before they can be used, because it takes care of some clocking and
174 messaging functions. We create the pipeline with `gst_pipeline_new()`.
175
176 ``` c
177 /* Build the pipeline */
178 gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL);
179 if (gst_element_link (source, sink) != TRUE) {
180   g_printerr ("Elements could not be linked.\n");
181   gst_object_unref (pipeline);
182   return -1;
183 }
184 ```
185
186 A pipeline is a particular type of `bin`, which is the element used to
187 contain other elements. Therefore all methods which apply to bins also
188 apply to pipelines. In our case, we call `gst_bin_add_many()` to add the
189 elements to the pipeline (mind the cast). This function accepts a list
190 of elements to be added, ending with NULL. Individual elements can be
191 added with `gst_bin_add()`.
192
193 These elements, however, are not linked with each other yet. For this,
194 we need to use `gst_element_link()`. Its first parameter is the source,
195 and the second one the destination. The order counts, because links must
196 be established following the data flow (this is, from source elements to
197 sink elements). Keep in mind that only elements residing in the same bin
198 can be linked together, so remember to add them to the pipeline before
199 trying to link them!
200
201 ### Properties
202
203 ``` c
204 /* Modify the source's properties */
205 g_object_set (source, "pattern", 0, NULL);
206 ```
207
208 Most GStreamer elements have customizable properties: named attributes
209 that can be modified to change the element's behavior (writable
210 properties) or inquired to find out about the element's internal state
211 (readable properties).
212
213 Properties are read from with `g_object_get()` and written to
214 with `g_object_set()`.
215
216 `g_object_set()` accepts a NULL-terminated list of property-name,
217 property-value pairs, so multiple properties can be changed in one go
218 (GStreamer elements are all a particular kind of `GObject`, which is the
219 entity offering property facilities: This is why the property handling
220 methods have the `g_` prefix).
221
222 The line of code above changes the “pattern” property of `videotestsrc`,
223 which controls the type of test video the element outputs. Try different
224 values!
225
226 The names and possible values of all the properties an element exposes
227 can be found using the gst-inspect-1.0 tool described in [Basic tutorial 10:
228 GStreamer tools](tutorials/basic/gstreamer-tools.md).
229
230 ### Error checking
231
232 At this point, we have the whole pipeline built and setup, and the rest
233 of the tutorial is very similar to the previous one, but we are going to
234 add more error checking:
235
236 ``` c
237 /* Start playing */
238 ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
239 if (ret == GST_STATE_CHANGE_FAILURE) {
240   g_printerr ("Unable to set the pipeline to the playing state.\n");
241   gst_object_unref (pipeline);
242   return -1;
243 }
244 ```
245
246 We call `gst_element_set_state()`, but this time we check its return
247 value for errors. Changing states is a delicate process and a few more
248 details are given in [Basic tutorial 3: Dynamic
249 pipelines](tutorials/basic/dynamic-pipelines.md).
250
251 ``` c
252 /* Wait until error or EOS */
253 bus = gst_element_get_bus (pipeline);
254 msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
255
256 /* Parse message */
257 if (msg != NULL) {
258   GError *err;
259   gchar *debug_info;
260
261   switch (GST_MESSAGE_TYPE (msg)) {
262     case GST_MESSAGE_ERROR:
263       gst_message_parse_error (msg, &err, &debug_info);
264       g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
265       g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
266       g_clear_error (&err);
267       g_free (debug_info);
268       break;
269     case GST_MESSAGE_EOS:
270       g_print ("End-Of-Stream reached.\n");
271       break;
272     default:
273       /* We should not reach here because we only asked for ERRORs and EOS */
274       g_printerr ("Unexpected message received.\n");
275       break;
276   }
277   gst_message_unref (msg);
278 }
279 ```
280
281 `gst_bus_timed_pop_filtered()` waits for execution to end and returns
282 with a `GstMessage` which we previously ignored. We
283 asked `gst_bus_timed_pop_filtered()` to return when GStreamer
284 encountered either an error condition or an EOS, so we need to check
285 which one happened, and print a message on screen (Your application will
286 probably want to undertake more complex actions).
287
288 `GstMessage` is a very versatile structure which can deliver virtually
289 any kind of information. Fortunately, GStreamer provides a series of
290 parsing functions for each kind of message.
291
292 In this case, once we know the message contains an error (by using the
293 `GST_MESSAGE_TYPE()` macro), we can use
294 `gst_message_parse_error()` which returns a GLib `GError` error
295 structure and a string useful for debugging. Examine the code to see how
296 these are used and freed afterward.
297
298 ### The GStreamer bus
299
300 At this point it is worth introducing the GStreamer bus a bit more
301 formally. It is the object responsible for delivering to the application
302 the `GstMessage`s generated by the elements, in order and to the
303 application thread. This last point is important, because the actual
304 streaming of media is done in another thread than the application.
305
306 Messages can be extracted from the bus synchronously with
307 `gst_bus_timed_pop_filtered()` and its siblings, or asynchronously,
308 using signals (shown in the next tutorial). Your application should
309 always keep an eye on the bus to be notified of errors and other
310 playback-related issues.
311
312 The rest of the code is the cleanup sequence, which is the same as
313 in [Basic tutorial 1: Hello
314 world!](tutorials/basic/hello-world.md).
315
316 ## Exercise
317
318 If you feel like practicing, try this exercise: Add a video filter
319 element in between the source and the sink of this pipeline. Use
320 `vertigotv` for a nice effect. You will need to create it, add it to the
321 pipeline, and link it with the other elements.
322
323 Depending on your platform and available plugins, you might get a
324 “negotiation” error, because the sink does not understand what the
325 filter is producing (more about negotiation in [Basic tutorial 6: Media
326 formats and Pad
327 Capabilities](tutorials/basic/media-formats-and-pad-capabilities.md)).
328 In this case, try to add an element called `videoconvert` after the
329 filter (this is, build a pipeline of 4 elements. More on
330 `videoconvert` in [Basic tutorial 14: Handy
331 elements](tutorials/basic/handy-elements.md)).
332
333 ## Conclusion
334
335 This tutorial showed:
336
337   - How to create elements with `gst_element_factory_make()`
338
339   - How to create an empty pipeline with `gst_pipeline_new()`
340
341   - How to add elements to the pipeline with `gst_bin_add_many()`
342
343   - How to link the elements with each other with `gst_element_link()`
344
345 This concludes the first of the two tutorials devoted to basic GStreamer
346 concepts. The second one comes next.
347
348 Remember that attached to this page you should find the complete source
349 code of the tutorial and any accessory files needed to build it.
350
351 It has been a pleasure having you here, and see you soon!