1 # Basic tutorial 4: Time management
5 This tutorial shows how to use GStreamer time-related facilities. In
8 - How to query the pipeline for information like stream position or
11 - How to seek (jump) to a different position (time instant) inside the
16 `GstQuery` is a mechanism that allows asking an element or pad for a
17 piece of information. In this example we ask the pipeline if seeking is
18 allowed (some sources, like live streams, do not allow seeking). If it
19 is allowed, then, once the movie has been running for ten seconds, we
20 skip to a different position using a seek.
22 In the previous tutorials, once we had the pipeline setup and running,
23 our main function just sat and waited to receive an ERROR or an EOS
24 through the bus. Here we modify this function to periodically wake up
25 and query the pipeline for the stream position, so we can print it on
26 screen. This is similar to what a media player would do, updating the
27 User Interface on a periodic basis.
29 Finally, the stream duration is queried and updated whenever it changes.
33 Copy this code into a text file named `basic-tutorial-4.c` (or find it
34 in the SDK installation).
36 **basic-tutorial-4.c**
41 /* Structure to contain all our information, so we can pass it around */
42 typedef struct _CustomData {
43 GstElement *playbin; /* Our one and only element */
44 gboolean playing; /* Are we in the PLAYING state? */
45 gboolean terminate; /* Should we terminate execution? */
46 gboolean seek_enabled; /* Is seeking enabled for this media? */
47 gboolean seek_done; /* Have we performed the seek already? */
48 gint64 duration; /* How long does this media last, in nanoseconds */
51 /* Forward definition of the message processing function */
52 static void handle_message (CustomData *data, GstMessage *msg);
54 int main(int argc, char *argv[]) {
58 GstStateChangeReturn ret;
61 data.terminate = FALSE;
62 data.seek_enabled = FALSE;
63 data.seek_done = FALSE;
64 data.duration = GST_CLOCK_TIME_NONE;
66 /* Initialize GStreamer */
67 gst_init (&argc, &argv);
69 /* Create the elements */
70 data.playbin = gst_element_factory_make ("playbin", "playbin");
73 g_printerr ("Not all elements could be created.\n");
77 /* Set the URI to play */
78 g_object_set (data.playbin, "uri", "https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", NULL);
81 ret = gst_element_set_state (data.playbin, GST_STATE_PLAYING);
82 if (ret == GST_STATE_CHANGE_FAILURE) {
83 g_printerr ("Unable to set the pipeline to the playing state.\n");
84 gst_object_unref (data.playbin);
88 /* Listen to the bus */
89 bus = gst_element_get_bus (data.playbin);
91 msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND,
92 GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION);
96 handle_message (&data, msg);
98 /* We got no message, this means the timeout expired */
102 /* Query the current position of the stream */
103 if (!gst_element_query_position (data.playbin, GST_TIME_FORMAT, ¤t)) {
104 g_printerr ("Could not query current position.\n");
107 /* If we didn't know it yet, query the stream duration */
108 if (!GST_CLOCK_TIME_IS_VALID (data.duration)) {
109 if (!gst_element_query_duration (data.playbin, GST_TIME_FORMAT, &data.duration)) {
110 g_printerr ("Could not query current duration.\n");
114 /* Print current position and total duration */
115 g_print ("Position %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r",
116 GST_TIME_ARGS (current), GST_TIME_ARGS (data.duration));
118 /* If seeking is enabled, we have not done it yet, and the time is right, seek */
119 if (data.seek_enabled && !data.seek_done && current > 10 * GST_SECOND) {
120 g_print ("\nReached 10s, performing seek...\n");
121 gst_element_seek_simple (data.playbin, GST_FORMAT_TIME,
122 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 30 * GST_SECOND);
123 data.seek_done = TRUE;
127 } while (!data.terminate);
130 gst_object_unref (bus);
131 gst_element_set_state (data.playbin, GST_STATE_NULL);
132 gst_object_unref (data.playbin);
136 static void handle_message (CustomData *data, GstMessage *msg) {
140 switch (GST_MESSAGE_TYPE (msg)) {
141 case GST_MESSAGE_ERROR:
142 gst_message_parse_error (msg, &err, &debug_info);
143 g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
144 g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
145 g_clear_error (&err);
147 data->terminate = TRUE;
149 case GST_MESSAGE_EOS:
150 g_print ("End-Of-Stream reached.\n");
151 data->terminate = TRUE;
153 case GST_MESSAGE_DURATION:
154 /* The duration has changed, mark the current one as invalid */
155 data->duration = GST_CLOCK_TIME_NONE;
157 case GST_MESSAGE_STATE_CHANGED: {
158 GstState old_state, new_state, pending_state;
159 gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
160 if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->playbin)) {
161 g_print ("Pipeline state changed from %s to %s:\n",
162 gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
164 /* Remember whether we are in the PLAYING state or not */
165 data->playing = (new_state == GST_STATE_PLAYING);
168 /* We just moved to PLAYING. Check if seeking is possible */
171 query = gst_query_new_seeking (GST_FORMAT_TIME);
172 if (gst_element_query (data->playbin, query)) {
173 gst_query_parse_seeking (query, NULL, &data->seek_enabled, &start, &end);
174 if (data->seek_enabled) {
175 g_print ("Seeking is ENABLED from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT "\n",
176 GST_TIME_ARGS (start), GST_TIME_ARGS (end));
178 g_print ("Seeking is DISABLED for this stream.\n");
182 g_printerr ("Seeking query failed.");
184 gst_query_unref (query);
189 /* We should not reach here */
190 g_printerr ("Unexpected message received.\n");
193 gst_message_unref (msg);
197 > ![Information](images/icons/emoticons/information.png)
200 > 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:
202 > ``gcc basic-tutorial-4.c -o basic-tutorial-4 `pkg-config --cflags --libs gstreamer-1.0` ``
204 >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).
206 > This tutorial opens a window and displays a movie, with accompanying audio. The media is fetched from the Internet, so the window might take a few seconds to appear, depending on your connection speed. 10 seconds into the movie it skips to a new position
208 >Required libraries: `gstreamer-1.0`
213 /* Structure to contain all our information, so we can pass it around */
214 typedef struct _CustomData {
215 GstElement *playbin; /* Our one and only element */
216 gboolean playing; /* Are we in the PLAYING state? */
217 gboolean terminate; /* Should we terminate execution? */
218 gboolean seek_enabled; /* Is seeking enabled for this media? */
219 gboolean seek_done; /* Have we performed the seek already? */
220 gint64 duration; /* How long does this media last, in nanoseconds */
223 /* Forward definition of the message processing function */
224 static void handle_message (CustomData *data, GstMessage *msg);
227 We start by defining a structure to contain all our information, so we
228 can pass it around to other functions. In particular, in this example we
229 move the message handling code to its own function
230 `handle_message` because it is growing a bit too big.
232 We would then build a pipeline composed of a single element, a
233 `playbin`, which we already saw in [Basic tutorial 1: Hello
234 world!](tutorials/basic/hello-world.md). However,
235 `playbin` is in itself a pipeline, and in this case it is the only
236 element in the pipeline, so we use directly the `playbin` element. We
237 will skip the details: the URI of the clip is given to `playbin` via
238 the URI property and the pipeline is set to the playing state.
241 msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND,
242 GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION);
245 Previously we did not provide a timeout to
246 `gst_bus_timed_pop_filtered()`, meaning that it didn't return until a
247 message was received. Now we use a timeout of 100 milliseconds, so, if
248 no message is received, 10 times per second the function will return
249 with a NULL instead of a `GstMessage`. We are going to use this to
250 update our “UI”. Note that the timeout period is specified in
251 nanoseconds, so usage of the `GST_SECOND` or `GST_MSECOND` macros is
254 If we got a message, we process it in the `handle_message`` `function
255 (next subsection), otherwise:
257 ### User interface resfreshing
260 /* We got no message, this means the timeout expired */
264 First off, if we are not in the PLAYING state, we do not want to do
265 anything here, since most queries would fail. Otherwise, it is time to
268 We get here approximately 10 times per second, a good enough refresh
269 rate for our UI. We are going to print on screen the current media
270 position, which we can learn be querying the pipeline. This involves a
271 few steps that will be shown in the next subsection, but, since position
272 and duration are common enough queries, `GstElement` offers easier,
273 ready-made alternatives:
276 /* Query the current position of the stream */
277 if (!gst_element_query_position (data.pipeline, GST_FORMAT_TIME, ¤t)) {
278 g_printerr ("Could not query current position.\n");
282 `gst_element_query_position()` hides the management of the query object
283 and directly provides us with the result.
286 /* If we didn't know it yet, query the stream duration */
287 if (!GST_CLOCK_TIME_IS_VALID (data.duration)) {
288 if (!gst_element_query_duration (data.pipeline, GST_TIME_FORMAT, &data.duration)) {
289 g_printerr ("Could not query current duration.\n");
294 Now is a good moment to know the length of the stream, with
295 another `GstElement` helper function: `gst_element_query_duration()`
298 /* Print current position and total duration */
299 g_print ("Position %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r",
300 GST_TIME_ARGS (current), GST_TIME_ARGS (data.duration));
303 Note the usage of the `GST_TIME_FORMAT` and `GST_TIME_ARGS` macros to
304 provide user-friendly representation of GStreamer
308 /* If seeking is enabled, we have not done it yet, and the time is right, seek */
309 if (data.seek_enabled && !data.seek_done && current > 10 * GST_SECOND) {
310 g_print ("\nReached 10s, performing seek...\n");
311 gst_element_seek_simple (data.pipeline, GST_FORMAT_TIME,
312 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 30 * GST_SECOND);
313 data.seek_done = TRUE;
317 Now we perform the seek, “simply” by
318 calling `gst_element_seek_simple()` on the pipeline. A lot of the
319 intricacies of seeking are hidden in this method, which is a good
322 Let's review the parameters:
324 `GST_FORMAT_TIME` indicates that we are specifying the destination in
325 time, as opposite to bytes (and other more obscure mechanisms).
327 Then come the GstSeekFlags, let's review the most common:
329 `GST_SEEK_FLAG_FLUSH`: This discards all data currently in the pipeline
330 before doing the seek. Might pause a bit while the pipeline is refilled
331 and the new data starts to show up, but greatly increases the
332 “responsiveness” of the application. If this flag is not provided,
333 “stale” data might be shown for a while until the new position appears
334 at the end of the pipeline.
336 `GST_SEEK_FLAG_KEY_UNIT`: Most encoded video streams cannot seek to
337 arbitrary positions, only to certain frames called Key Frames. When this
338 flag is used, the seek will actually move to the closest key frame and
339 start producing data straight away. If this flag is not used, the
340 pipeline will move internally to the closest key frame (it has no other
341 alternative) but data will not be shown until it reaches the requested
342 position. Not providing the flag is more accurate, but might take longer
345 `GST_SEEK_FLAG_ACCURATE`: Some media clips do not provide enough
346 indexing information, meaning that seeking to arbitrary positions is
347 time-consuming. In these cases, GStreamer usually estimates the position
348 to seek to, and usually works just fine. If this precision is not good
349 enough for your case (you see seeks not going to the exact time you
350 asked for), then provide this flag. Be warned that it might take longer
351 to calculate the seeking position (very long, on some files).
353 And finally we provide the position to seek to. Since we asked
354 for `GST_FORMAT_TIME` , this position is in nanoseconds, so we use
355 the `GST_SECOND` macro for simplicity.
359 The `handle_message` function processes all messages received through
360 the pipeline's bus. ERROR and EOS handling is the same as in previous
361 tutorials, so we skip to the interesting part:
364 case GST_MESSAGE_DURATION:
365 /* The duration has changed, mark the current one as invalid */
366 data->duration = GST_CLOCK_TIME_NONE;
370 This message is posted on the bus whenever the duration of the stream
371 changes. Here we simply mark the current duration as invalid, so it gets
375 case GST_MESSAGE_STATE_CHANGED: {
376 GstState old_state, new_state, pending_state;
377 gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
378 if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->pipeline)) {
379 g_print ("Pipeline state changed from %s to %s:\n",
380 gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
382 /* Remember whether we are in the PLAYING state or not */
383 data->playing = (new_state == GST_STATE_PLAYING);
386 Seeks and time queries generally only get a valid reply when in the
387 PAUSED or PLAYING state, since all elements have had a chance to
388 receive information and configure themselves. Here we take note of
389 whether we are in the PLAYING state or not with the `playing`
392 Also, if we have just entered the PLAYING state, we do our first query.
393 We ask the pipeline if seeking is allowed on this stream:
397 /* We just moved to PLAYING. Check if seeking is possible */
400 query = gst_query_new_seeking (GST_FORMAT_TIME);
401 if (gst_element_query (data->pipeline, query)) {
402 gst_query_parse_seeking (query, NULL, &data->seek_enabled, &start, &end);
403 if (data->seek_enabled) {
404 g_print ("Seeking is ENABLED from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT "\n",
405 GST_TIME_ARGS (start), GST_TIME_ARGS (end));
407 g_print ("Seeking is DISABLED for this stream.\n");
411 g_printerr ("Seeking query failed.");
413 gst_query_unref (query);
417 `gst_query_new_seeking()` creates a new query object of the "seeking"
418 type, with `GST_FORMAT_TIME` format. This indicates that we are
419 interested in seeking by specifying the new time to which we want to
420 move. We could also ask for `GST_FORMAT_BYTES`, and then seek to a
421 particular byte position inside the source file, but this is normally
424 This query object is then passed to the pipeline with
425 `gst_element_query()`. The result is stored in the same query, and can
426 be easily retrieved with `gst_query_parse_seeking()`. It extracts a
427 boolean indicating if seeking is allowed, and the range in which seeking
430 Don't forget to unref the query object when you are done with it.
432 And that's it! With this knowledge a media player can be built which
433 periodically updates a slider based on the current stream position and
434 allows seeking by moving the slider!
438 This tutorial has shown:
440 - How to query the pipeline for information using `GstQuery`
442 - How to obtain common information like position and duration
443 using `gst_element_query_position()` and `gst_element_query_duration()`
445 - How to seek to an arbitrary position in the stream
446 using `gst_element_seek_simple()`
448 - In which states all these operations can be performed.
450 The next tutorial shows how to integrate GStreamer with a Graphical User
453 Remember that attached to this page you should find the complete source
454 code of the tutorial and any accessory files needed to build it.
456 It has been a pleasure having you here, and see you soon!