2 title: Pipeline manipulation
5 # Pipeline manipulation
7 This chapter presents many ways in which you can manipulate pipelines from
8 your application. These are some of the topics that will be covered:
10 - How to insert data from an application into a pipeline
11 - How to read data from a pipeline
12 - How to manipulate the pipeline's speed, length and starting point
13 - How to *listen* to a pipeline's data processing.
15 Parts of this chapter are very low level so you'll need some programming
16 experience and a good understanding of GStreamer to follow them.
20 Probing is best envisioned as having access to a pad listener. Technically, a
21 probe is nothing more than a callback that can be attached to a pad using
22 `gst_pad_add_probe ()`. Conversely, you can use `gst_pad_remove_probe ()` to
23 remove the callback. While attached, the probe notifies you of any activity
24 on the pad. You can define what kind of notifications you are interested in when
29 - A buffer is pushed or pulled. You want to specify the
30 `GST_PAD_PROBE_TYPE_BUFFER` when registering the probe. Because
31 the pad can be scheduled in different ways. It is also possible to
32 specify in what scheduling mode you are interested with the optional
33 `GST_PAD_PROBE_TYPE_PUSH` and `GST_PAD_PROBE_TYPE_PULL` flags.
34 You can use this probe to inspect, modify or drop the buffer. See
35 [Data probes](#data-probes).
37 - A buffer list is pushed. Use the `GST_PAD_PROBE_TYPE_BUFFER_LIST`
38 when registering the probe.
40 - An event travels over a pad. Use the
41 `GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM` and
42 `GST_PAD_PROBE_TYPE_EVENT_UPSTREAM` flags to select downstream
43 and upstream events. There is also a convenience
44 `GST_PAD_PROBE_TYPE_EVENT_BOTH` to be notified of events going
45 in both directions. By default, flush events do not cause
46 a notification. You need to explicitly enable
47 `GST_PAD_PROBE_TYPE_EVENT_FLUSH` to receive callbacks from
48 flushing events. Events are always only notified in push mode.
49 You can use this type of probe to inspect, modify or drop the event.
51 - A query travels over a pad. Use the
52 `GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM` and
53 `GST_PAD_PROBE_TYPE_QUERY_UPSTREAM` flags to select downstream
54 and upstream queries. The convenience
55 `GST_PAD_PROBE_TYPE_QUERY_BOTH` can also be used to select both
56 directions. Query probes are notified twice: when the query
57 travels upstream/downstream and when the query result is
58 returned. You can select in what stage the callback will be called
59 with the `GST_PAD_PROBE_TYPE_PUSH` and
60 `GST_PAD_PROBE_TYPE_PULL`, respectively when the query is
61 performed and when the query result is returned.
63 You can use a query probe to inspect or modify queries, or even to answer
64 them in the probe callback. To answer a query you place the result value
65 in the query and return `GST_PAD_PROBE_DROP` from the callback.
67 - In addition to notifying you of dataflow, you can also ask the probe
68 to block the dataflow when the callback returns. This is called a
69 blocking probe and is activated by specifying the
70 `GST_PAD_PROBE_TYPE_BLOCK` flag. You can use this flag with the
71 other flags to only block dataflow on selected activity. A pad
72 becomes unblocked again if you remove the probe or when you return
73 `GST_PAD_PROBE_REMOVE` from the callback. You can let only the
74 currently blocked item pass by returning `GST_PAD_PROBE_PASS` from
75 the callback, it will block again on the next item.
77 Blocking probes are used to temporarily block pads because they are
78 unlinked or because you are going to unlink them. If the dataflow is
79 not blocked, the pipeline would go into an error state if data is
80 pushed on an unlinked pad. We will see how to use blocking probes to
81 partially preroll a pipeline. See also [Play a section of a media
82 file](#play-a-section-of-a-media-file).
84 - Be notified when no activity is happening on a pad. You install this
85 probe with the `GST_PAD_PROBE_TYPE_IDLE` flag. You can specify
86 `GST_PAD_PROBE_TYPE_PUSH` and/or `GST_PAD_PROBE_TYPE_PULL` to
87 only be notified depending on the pad scheduling mode. The IDLE
88 probe is also a blocking probe in that it will not let any data pass
89 on the pad for as long as the IDLE probe is installed.
91 You can use idle probes to dynamically relink a pad. We will see how
92 to use idle probes to replace an element in the pipeline. See also
93 [Dynamically changing the
94 pipeline](#dynamically-changing-the-pipeline).
98 Data probes notify you when there is data passing on a pad. Pass
99 `GST_PAD_PROBE_TYPE_BUFFER` and/or `GST_PAD_PROBE_TYPE_BUFFER_LIST` to
100 `gst_pad_add_probe ()` for creating this kind of probe. Most common buffer
101 operations elements can do in `_chain ()` functions, can be done in probe
104 Data probes run in the pipeline's streaming thread context, so callbacks
105 should try to avoid blocking and generally, avoid doing weird stuff. Doing so
106 could have a negative impact on the pipeline's performance or, in case of bugs,
107 lead to deadlocks or crashes. More precisely, one should usually avoid calling
108 GUI-related functions from within a probe callback, nor try to change the state
109 of the pipeline. An application may post custom messages on the pipeline's bus
110 to communicate with the main application thread and have it do things like stop
113 The following is an example on using data probes. Compare this program's output
114 with that of `gst-launch-1.0 videotestsrc ! xvimagesink` if you are not
115 sure what to look for:
120 static GstPadProbeReturn
121 cb_have_data (GstPad *pad,
122 GstPadProbeInfo *info,
130 buffer = GST_PAD_PROBE_INFO_BUFFER (info);
132 buffer = gst_buffer_make_writable (buffer);
134 /* Making a buffer writable can fail (for example if it
135 * cannot be copied and is used more than once)
138 return GST_PAD_PROBE_OK;
140 /* Mapping a buffer can fail (non-writable) */
141 if (gst_buffer_map (buffer, &map, GST_MAP_WRITE)) {
142 ptr = (guint16 *) map.data;
144 for (y = 0; y < 288; y++) {
145 for (x = 0; x < 384 / 2; x++) {
146 t = ptr[384 - 1 - x];
147 ptr[384 - 1 - x] = ptr[x];
152 gst_buffer_unmap (buffer, &map);
155 GST_PAD_PROBE_INFO_DATA (info) = buffer;
157 return GST_PAD_PROBE_OK;
165 GstElement *pipeline, *src, *sink, *filter, *csp;
170 gst_init (&argc, &argv);
171 loop = g_main_loop_new (NULL, FALSE);
174 pipeline = gst_pipeline_new ("my-pipeline");
175 src = gst_element_factory_make ("videotestsrc", "src");
177 g_error ("Could not create 'videotestsrc' element");
179 filter = gst_element_factory_make ("capsfilter", "filter");
180 g_assert (filter != NULL); /* should always exist */
182 csp = gst_element_factory_make ("videoconvert", "csp");
184 g_error ("Could not create 'videoconvert' element");
186 sink = gst_element_factory_make ("xvimagesink", "sink");
188 sink = gst_element_factory_make ("ximagesink", "sink");
190 g_error ("Could not create neither 'xvimagesink' nor 'ximagesink' element");
193 gst_bin_add_many (GST_BIN (pipeline), src, filter, csp, sink, NULL);
194 gst_element_link_many (src, filter, csp, sink, NULL);
195 filtercaps = gst_caps_new_simple ("video/x-raw",
196 "format", G_TYPE_STRING, "RGB16",
197 "width", G_TYPE_INT, 384,
198 "height", G_TYPE_INT, 288,
199 "framerate", GST_TYPE_FRACTION, 25, 1,
201 g_object_set (G_OBJECT (filter), "caps", filtercaps, NULL);
202 gst_caps_unref (filtercaps);
204 pad = gst_element_get_static_pad (src, "src");
205 gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER,
206 (GstPadProbeCallback) cb_have_data, NULL, NULL);
207 gst_object_unref (pad);
210 gst_element_set_state (pipeline, GST_STATE_PLAYING);
212 /* wait until it's up and running or failed */
213 if (gst_element_get_state (pipeline, NULL, NULL, -1) == GST_STATE_CHANGE_FAILURE) {
214 g_error ("Failed to go into PLAYING state");
217 g_print ("Running ...\n");
218 g_main_loop_run (loop);
221 gst_element_set_state (pipeline, GST_STATE_NULL);
222 gst_object_unref (pipeline);
228 Strictly speaking, a pad probe callback is only allowed to modify the
229 buffer content if the buffer is writable. Whether this is the case or
230 not depends a lot on the pipeline and the elements involved. Often
231 enough, this is the case, but sometimes it is not, and if it is not then
232 unexpected modification of the data or metadata can introduce bugs that
233 are very hard to debug and track down. You can check if a buffer is
234 writable with `gst_buffer_is_writable ()`. Since you can pass back a
235 different buffer than the one passed in, it is a good idea to make the
236 buffer writable in the callback function with `gst_buffer_make_writable
239 Pad probes are best suited for looking at data as it passes through the
240 pipeline. If you need to modify data, you should rather write your own
241 GStreamer element. Base classes like `GstAudioFilter`, `GstVideoFilter` or
242 `GstBaseTransform` make this fairly easy.
244 If you just want to inspect buffers as they pass through the pipeline,
245 you don't even need to set up pad probes. You could also just insert an
246 identity element into the pipeline and connect to its "handoff" signal.
247 The identity element also provides a few useful debugging tools like the
248 `dump` and `last-message` properties; the latter is enabled by
249 passing the '-v' switch to `gst-launch` and setting the `silent` property
250 on the identity to `FALSE`.
252 ### Play a section of a media file
254 In this example we will show you how to play back a section of a media
255 file. The goal is to only play the part from 2 to 5 seconds and then
258 In a first step we will set a `uridecodebin` element to the `PAUSED` state
259 and make sure that we block all the source pads that are created. When
260 all the source pads are blocked, we have data on all of them and we say
261 that the `uridecodebin` is prerolled.
263 In a prerolled pipeline we can ask for the duration of the media and we
264 can also perform seeks. We are interested in performing a seek operation
265 on the pipeline to select the 2-to-5-seconds section.
267 After we configure the section we want, we can link the sink element, unblock the
268 source pads and set the pipeline to the `PLAYING` state. You will see that
269 exactly the requested region is displayed by the sink before it goes to `EOS`.
276 static GMainLoop *loop;
279 static gboolean prerolled = FALSE;
280 static GstPad *sinkpad;
283 dec_counter (GstElement * pipeline)
288 if (g_atomic_int_dec_and_test (&counter)) {
289 /* all probes blocked and no-more-pads signaled, post
290 * message on the bus. */
293 gst_bus_post (bus, gst_message_new_application (
294 GST_OBJECT_CAST (pipeline),
295 gst_structure_new_empty ("ExPrerolled")));
299 /* called when a source pad of uridecodebin is blocked */
300 static GstPadProbeReturn
301 cb_blocked (GstPad *pad,
302 GstPadProbeInfo *info,
305 GstElement *pipeline = GST_ELEMENT (user_data);
308 return GST_PAD_PROBE_REMOVE;
310 dec_counter (pipeline);
312 return GST_PAD_PROBE_OK;
315 /* called when uridecodebin has a new pad */
317 cb_pad_added (GstElement *element,
321 GstElement *pipeline = GST_ELEMENT (user_data);
326 g_atomic_int_inc (&counter);
328 gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
329 (GstPadProbeCallback) cb_blocked, pipeline, NULL);
331 /* try to link to the video pad */
332 gst_pad_link (pad, sinkpad);
335 /* called when uridecodebin has created all pads */
337 cb_no_more_pads (GstElement *element,
340 GstElement *pipeline = GST_ELEMENT (user_data);
345 dec_counter (pipeline);
348 /* called when a new message is posted on the bus */
350 cb_message (GstBus *bus,
354 GstElement *pipeline = GST_ELEMENT (user_data);
356 switch (GST_MESSAGE_TYPE (message)) {
357 case GST_MESSAGE_ERROR:
358 g_print ("we received an error!\n");
359 g_main_loop_quit (loop);
361 case GST_MESSAGE_EOS:
362 g_print ("we reached EOS\n");
363 g_main_loop_quit (loop);
365 case GST_MESSAGE_APPLICATION:
367 if (gst_message_has_name (message, "ExPrerolled")) {
368 /* it's our message */
369 g_print ("we are all prerolled, do seek\n");
370 gst_element_seek (pipeline,
371 1.0, GST_FORMAT_TIME,
372 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
373 GST_SEEK_TYPE_SET, 2 * GST_SECOND,
374 GST_SEEK_TYPE_SET, 5 * GST_SECOND);
376 gst_element_set_state (pipeline, GST_STATE_PLAYING);
389 GstElement *pipeline, *src, *csp, *vs, *sink;
392 gst_init (&argc, &argv);
393 loop = g_main_loop_new (NULL, FALSE);
396 g_print ("usage: %s <uri>", argv[0]);
401 pipeline = gst_pipeline_new ("my-pipeline");
403 bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
404 gst_bus_add_signal_watch (bus);
405 g_signal_connect (bus, "message", (GCallback) cb_message,
408 src = gst_element_factory_make ("uridecodebin", "src");
410 g_error ("Could not create 'uridecodebin' element");
412 g_object_set (src, "uri", argv[1], NULL);
414 csp = gst_element_factory_make ("videoconvert", "csp");
416 g_error ("Could not create 'videoconvert' element");
418 vs = gst_element_factory_make ("videoscale", "vs");
420 g_error ("Could not create 'videoscale' element");
422 sink = gst_element_factory_make ("autovideosink", "sink");
424 g_error ("Could not create 'autovideosink' element");
426 gst_bin_add_many (GST_BIN (pipeline), src, csp, vs, sink, NULL);
428 /* can't link src yet, it has no pads */
429 gst_element_link_many (csp, vs, sink, NULL);
431 sinkpad = gst_element_get_static_pad (csp, "sink");
433 /* for each pad block that is installed, we will increment
434 * the counter. for each pad block that is signaled, we
435 * decrement the counter. When the counter is 0 we post
436 * an app message to tell the app that all pads are
437 * blocked. Start with 1 that is decremented when no-more-pads
438 * is signaled to make sure that we only post the message
439 * after no-more-pads */
440 g_atomic_int_set (&counter, 1);
442 g_signal_connect (src, "pad-added",
443 (GCallback) cb_pad_added, pipeline);
444 g_signal_connect (src, "no-more-pads",
445 (GCallback) cb_no_more_pads, pipeline);
447 gst_element_set_state (pipeline, GST_STATE_PAUSED);
449 g_main_loop_run (loop);
451 gst_element_set_state (pipeline, GST_STATE_NULL);
453 gst_object_unref (sinkpad);
454 gst_object_unref (bus);
455 gst_object_unref (pipeline);
456 g_main_loop_unref (loop);
462 Note that we use a custom application message to signal the main thread that the
463 `uridecodebin` is prerolled. The main thread will then issue a flushing seek to
464 the requested region. The flush will temporarily unblock the pad and reblock
465 them when new data arrives again. We detect this second block to remove the
466 probes. Then we set the pipeline to `PLAYING` and it should play the selected
467 2-to-5-seconds section; the application waits for the `EOS` message and quits.
469 ## Manually adding or removing data from/to a pipeline
471 Many people have expressed the wish to use their own sources to inject data into
472 a pipeline, others, the wish to grab a pipeline's output and take care of it in
473 their application. While these methods are strongly discouraged, GStreamer
474 offers support for them -- *Beware\! You need to know what you are doing* --.
475 Since you don't have any support from a base class you need to thoroughly
476 understand state changes and synchronization. If it doesn't work, there are a
477 million ways to shoot yourself in the foot. It's always better to simply write a
478 plugin and have the base class manage it. See the Plugin Writer's Guide for more
479 information on this topic. Additionally, review the next section, which explains
480 how to statically embed plugins in your application.
482 There are two possible elements that you can use for the above-mentioned
483 purposes: `appsrc` (an imaginary source) and `appsink` (an imaginary sink). The
484 same method applies to these elements. We will discuss how to use them to insert
485 (using `appsrc`) or to grab (using `appsink`) data from a pipeline, and how to set
488 Both `appsrc` and `appsink` provide 2 sets of API. One API uses standard
489 `GObject` (action) signals and properties. The same API is also available
490 as a regular C API. The C API is more performant but requires you to
491 link to the app library in order to use the elements.
493 ### Inserting data with appsrc
495 Let's take a look at `appsrc` and how to insert application data into the
498 `appsrc` has some configuration options that control the way it operates. You
499 should decide about the following:
501 - Will `appsrc` operate in push or pull mode. The `stream-type`
502 property can be used to control this. A `random-access` `stream-type`
503 will make `appsrc` activate pull mode scheduling while the other
504 `stream-types` activate push mode.
506 - The caps of the buffers that `appsrc` will push out. This needs to be
507 configured with the `caps` property. This property must be set to a fixed
508 caps and will be used to negotiate a format downstream.
510 - Whether `appsrc` operates in live mode or not. This is configured
511 with the `is-live` property. When operating in live-mode it is
512 also important to set the `min-latency` and `max-latency` properties.
513 `min-latency` should be set to the amount of time it takes between
514 capturing a buffer and when it is pushed inside `appsrc`. In live
515 mode, you should timestamp the buffers with the pipeline `running-time`
516 when the first byte of the buffer was captured before feeding them to
517 `appsrc`. You can let `appsrc` do the timestamping with
518 the `do-timestamp` property, but then the `min-latency` must be set to 0
519 because `appsrc` timestamps based on what was the `running-time` when it got
522 - The format of the SEGMENT event that `appsrc` will push. This format
523 has implications for how the buffers' `running-time` will be calculated,
524 so you must be sure you understand this. For live sources
525 you probably want to set the format property to `GST_FORMAT_TIME`.
526 For non-live sources, it depends on the media type that you are
527 handling. If you plan to timestamp the buffers, you should probably
528 use `GST_FORMAT_TIME` as format, if you don't, `GST_FORMAT_BYTES` might
531 - If `appsrc` operates in random-access mode, it is important to
532 configure the size property with the number of bytes in the stream. This
533 will allow downstream elements to know the size of the media and seek to the
534 end of the stream when needed.
536 The main way of handling data to `appsrc` is by using the
537 `gst_app_src_push_buffer ()` function or by emitting the `push-buffer` action
538 signal. This will put the buffer onto a queue from which `appsrc` will
539 read in its streaming thread. It's important to note that data
540 transport will not happen from the thread that performed the `push-buffer`
543 The `max-bytes` property controls how much data can be queued in `appsrc`
544 before `appsrc` considers the queue full. A filled internal queue will
545 always signal the `enough-data` signal, which signals the application
546 that it should stop pushing data into `appsrc`. The `block` property will
547 cause `appsrc` to block the `push-buffer` method until free data becomes
550 When the internal queue is running out of data, the `need-data` signal
551 is emitted, which signals the application that it should start pushing
552 more data into `appsrc`.
554 In addition to the `need-data` and `enough-data` signals, `appsrc` can
555 emit `seek-data` when the `stream-mode` property is set to
556 `seekable` or `random-access`. The signal argument will contain the
557 new desired position in the stream expressed in the unit set with the
558 `format` property. After receiving the `seek-data` signal, the
559 application should push buffers from the new position.
561 When the last byte is pushed into `appsrc`, you must call
562 `gst_app_src_end_of_stream ()` to make it send an `EOS` downstream.
564 These signals allow the application to operate `appsrc` in push and pull
565 mode as will be explained next.
567 #### Using appsrc in push mode
569 When `appsrc` is configured in push mode (`stream-type` is stream or
570 seekable), the application repeatedly calls the `push-buffer` method with
571 a new buffer. Optionally, the queue size in the `appsrc` can be controlled
572 with the `enough-data` and `need-data` signals by respectively
573 stopping/starting the `push-buffer` calls. The value of the `min-percent`
574 property defines how empty the internal `appsrc` queue needs to be before
575 the `need-data` signal is issued. You can set this to some positive value
576 to avoid completely draining the queue.
578 Don't forget to implement a `seek-data` callback when the `stream-type` is
579 set to `GST_APP_STREAM_TYPE_SEEKABLE`.
581 Use this mode when implementing various network protocols or hardware
584 #### Using appsrc in pull mode
586 In pull mode, data is fed to `appsrc` from the `need-data` signal
587 handler. You should push exactly the amount of bytes requested in the
588 `need-data` signal. You are only allowed to push less bytes when you are
589 at the end of the stream.
591 Use this mode for file access or other randomly accessible sources.
595 This example application will generate black/white (it switches every
596 second) video to an Xv-window output by using `appsrc` as a source with
597 caps to force a format. We use a colorspace conversion element to make
598 sure that we feed the right format to the X server. We configure a
599 video stream with a variable framerate (0/1) and we set the timestamps
600 on the outgoing buffers in such a way that we play 2 frames per second.
602 Note how we use the pull mode method of pushing new buffers into `appsrc`
603 although `appsrc` is running in push mode.
608 static GMainLoop *loop;
611 cb_need_data (GstElement *appsrc,
615 static gboolean white = FALSE;
616 static GstClockTime timestamp = 0;
621 size = 385 * 288 * 2;
623 buffer = gst_buffer_new_allocate (NULL, size, NULL);
625 /* this makes the image black/white */
626 gst_buffer_memset (buffer, 0, white ? 0xff : 0x0, size);
630 GST_BUFFER_PTS (buffer) = timestamp;
631 GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale_int (1, GST_SECOND, 2);
633 timestamp += GST_BUFFER_DURATION (buffer);
635 g_signal_emit_by_name (appsrc, "push-buffer", buffer, &ret);
636 gst_buffer_unref (buffer);
638 if (ret != GST_FLOW_OK) {
639 /* something wrong, stop pushing */
640 g_main_loop_quit (loop);
648 GstElement *pipeline, *appsrc, *conv, *videosink;
651 gst_init (&argc, &argv);
652 loop = g_main_loop_new (NULL, FALSE);
655 pipeline = gst_pipeline_new ("pipeline");
656 appsrc = gst_element_factory_make ("appsrc", "source");
657 conv = gst_element_factory_make ("videoconvert", "conv");
658 videosink = gst_element_factory_make ("xvimagesink", "videosink");
661 g_object_set (G_OBJECT (appsrc), "caps",
662 gst_caps_new_simple ("video/x-raw",
663 "format", G_TYPE_STRING, "RGB16",
664 "width", G_TYPE_INT, 384,
665 "height", G_TYPE_INT, 288,
666 "framerate", GST_TYPE_FRACTION, 0, 1,
668 gst_bin_add_many (GST_BIN (pipeline), appsrc, conv, videosink, NULL);
669 gst_element_link_many (appsrc, conv, videosink, NULL);
672 g_object_set (G_OBJECT (appsrc),
674 "format", GST_FORMAT_TIME, NULL);
675 g_signal_connect (appsrc, "need-data", G_CALLBACK (cb_need_data), NULL);
678 gst_element_set_state (pipeline, GST_STATE_PLAYING);
679 g_main_loop_run (loop);
682 gst_element_set_state (pipeline, GST_STATE_NULL);
683 gst_object_unref (GST_OBJECT (pipeline));
684 g_main_loop_unref (loop);
690 ### Grabbing data with appsink
692 Unlike `appsrc`, `appsink` is a little easier to use. It also supports
693 pull and push-based modes for getting data from the pipeline.
695 The normal way of retrieving samples from appsink is by using the
696 `gst_app_sink_pull_sample()` and `gst_app_sink_pull_preroll()` methods
697 or by using the `pull-sample` and `pull-preroll` signals. These methods
698 block until a sample becomes available in the sink or when the sink is
699 shut down or reaches `EOS`.
701 `appsink` will internally use a queue to collect buffers from the
702 streaming thread. If the application is not pulling samples fast enough,
703 this queue will consume a lot of memory over time. The `max-buffers`
704 property can be used to limit the queue size. The `drop` property
705 controls whether the streaming thread blocks or if older buffers are
706 dropped when the maximum queue size is reached. Note that blocking the
707 streaming thread can negatively affect real-time performance and should
710 If a blocking behaviour is not desirable, setting the `emit-signals`
711 property to `TRUE` will make appsink emit the `new-sample` and
712 `new-preroll` signals when a sample can be pulled without blocking.
714 The `caps` property on `appsink` can be used to control the formats that
715 the latter can receive. This property can contain non-fixed caps, the
716 format of the pulled samples can be obtained by getting the sample caps.
718 If one of the pull-preroll or pull-sample methods return `NULL`, the
719 `appsink` is stopped or in the `EOS` state. You can check for the `EOS` state
720 with the `eos` property or with the `gst_app_sink_is_eos()` method.
722 The `eos` signal can also be used to be informed when the `EOS` state is
723 reached to avoid polling.
725 Consider configuring the following properties in the `appsink`:
727 - The `sync` property if you want to have the sink base class
728 synchronize the buffer against the pipeline clock before handing you
731 - Enable Quality-of-Service with the `qos` property. If you are
732 dealing with raw video frames and let the base class synchronize on
733 the clock. It might also be a good idea to let the base class send
734 `QOS` events upstream.
736 - The caps property that contains the accepted caps. Upstream elements
737 will try to convert the format so that it matches the configured
738 caps on `appsink`. You must still check the `GstSample` to get the
739 actual caps of the buffer.
743 What follows is an example on how to capture a snapshot of a video
744 stream using `appsink`.
754 #define CAPS "video/x-raw,format=RGB,width=160,pixel-aspect-ratio=1/1"
757 main (int argc, char *argv[])
759 GstElement *pipeline, *sink;
763 GError *error = NULL;
764 gint64 duration, position;
765 GstStateChangeReturn ret;
769 gst_init (&argc, &argv);
772 g_print ("usage: %s <uri>\n Writes snapshot.png in the current directory\n",
777 /* create a new pipeline */
779 g_strdup_printf ("uridecodebin uri=%s ! videoconvert ! videoscale ! "
780 " appsink name=sink caps=\"" CAPS "\"", argv[1]);
781 pipeline = gst_parse_launch (descr, &error);
784 g_print ("could not construct pipeline: %s\n", error->message);
785 g_clear_error (&error);
790 sink = gst_bin_get_by_name (GST_BIN (pipeline), "sink");
792 /* set to PAUSED to make the first frame arrive in the sink */
793 ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
795 case GST_STATE_CHANGE_FAILURE:
796 g_print ("failed to play the file\n");
798 case GST_STATE_CHANGE_NO_PREROLL:
799 /* for live sources, we need to set the pipeline to PLAYING before we can
800 * receive a buffer. We don't do that yet */
801 g_print ("live sources not supported yet\n");
806 /* This can block for up to 5 seconds. If your machine is really overloaded,
807 * it might time out before the pipeline prerolled and we generate an error. A
808 * better way is to run a mainloop and catch errors there. */
809 ret = gst_element_get_state (pipeline, NULL, NULL, 5 * GST_SECOND);
810 if (ret == GST_STATE_CHANGE_FAILURE) {
811 g_print ("failed to play the file\n");
815 /* get the duration */
816 gst_element_query_duration (pipeline, GST_FORMAT_TIME, &duration);
819 /* we have a duration, seek to 5% */
820 position = duration * 5 / 100;
822 /* no duration, seek to 1 second, this could EOS */
823 position = 1 * GST_SECOND;
825 /* seek to the a position in the file. Most files have a black first frame so
826 * by seeking to somewhere else we have a bigger chance of getting something
827 * more interesting. An optimisation would be to detect black images and then
828 * seek a little more */
829 gst_element_seek_simple (pipeline, GST_FORMAT_TIME,
830 GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_FLUSH, position);
832 /* get the preroll buffer from appsink, this block untils appsink really
834 g_signal_emit_by_name (sink, "pull-preroll", &sample, NULL);
836 /* if we have a buffer now, convert it to a pixbuf. It's possible that we
837 * don't have a buffer because we went EOS right away or had an error. */
843 /* get the snapshot buffer format now. We set the caps on the appsink so
844 * that it can only be an rgb buffer. The only thing we have not specified
845 * on the caps is the height, which is dependant on the pixel-aspect-ratio
846 * of the source material */
847 caps = gst_sample_get_caps (sample);
849 g_print ("could not get snapshot format\n");
852 s = gst_caps_get_structure (caps, 0);
854 /* we need to get the final caps on the buffer to get the size */
855 res = gst_structure_get_int (s, "width", &width);
856 res |= gst_structure_get_int (s, "height", &height);
858 g_print ("could not get snapshot dimension\n");
862 /* create pixmap from buffer and save, gstreamer video buffers have a stride
863 * that is rounded up to the nearest multiple of 4 */
864 buffer = gst_sample_get_buffer (sample);
865 /* Mapping a buffer can fail (non-readable) */
866 if (gst_buffer_map (buffer, &map, GST_MAP_READ)) {
868 pixbuf = gdk_pixbuf_new_from_data (map.data,
869 GDK_COLORSPACE_RGB, FALSE, 8, width, height,
870 GST_ROUND_UP_4 (width * 3), NULL, NULL);
872 /* save the pixbuf */
873 gdk_pixbuf_save (pixbuf, "snapshot.png", "png", &error, NULL);
875 gst_buffer_unmap (buffer, &map);
877 gst_sample_unref (sample);
879 g_print ("could not make snapshot\n");
882 /* cleanup and exit */
883 gst_element_set_state (pipeline, GST_STATE_NULL);
884 gst_object_unref (sink);
885 gst_object_unref (pipeline);
893 Sometimes you'll want to set a specific format. You can do this with a
894 `capsfilter` element.
896 If you want, for example, a specific video size and color format or an audio
897 bitsize and a number of channels; you can force a specific `GstCaps` on the
898 pipeline using *filtered caps*. You set *filtered caps* on a link by putting a
899 `capsfilter` between two elements and specifying your desired `GstCaps` in its
900 `caps` property. The `capsfilter` will only allow types compatible with these
901 capabilities to be negotiated.
903 See also [Creating capabilities for filtering][filter-caps].
905 [filter-caps]: application-development/basics/pads.md#creating-capabilities-for-filtering
907 ### Changing format in a PLAYING pipeline
909 It is also possible to dynamically change the format in a pipeline while
910 `PLAYING`. This can simply be done by changing the `caps` property on a
911 `capsfilter`. The `capsfilter` will send a `RECONFIGURE` event upstream that
912 will make the upstream element attempt to renegotiate a new format and
913 allocator. This only works if the upstream element is not using fixed caps on
916 Below is an example of how you can change the caps of a pipeline while
917 in the `PLAYING` state:
924 #define MAX_ROUND 100
927 main (int argc, char **argv)
929 GstElement *pipe, *filter;
936 gst_init (&argc, &argv);
938 pipe = gst_parse_launch_full ("videotestsrc ! capsfilter name=filter ! "
939 "ximagesink", NULL, GST_PARSE_FLAG_NONE, NULL);
940 g_assert (pipe != NULL);
942 filter = gst_bin_get_by_name (GST_BIN (pipe), "filter");
949 for (round = 0; round < MAX_ROUND; round++) {
951 g_print ("resize to %dx%d (%d/%d) \r", width, height, round, MAX_ROUND);
953 /* we prefer our fixed width and height but allow other dimensions to pass
955 capsstr = g_strdup_printf ("video/x-raw, width=(int)%d, height=(int)%d",
958 caps = gst_caps_from_string (capsstr);
960 g_object_set (filter, "caps", caps, NULL);
961 gst_caps_unref (caps);
964 gst_element_set_state (pipe, GST_STATE_PLAYING);
969 else if (width < 200)
975 else if (height < 150)
979 gst_bus_poll (GST_ELEMENT_BUS (pipe), GST_MESSAGE_ERROR,
982 g_print ("got error \n");
984 gst_message_unref (message);
989 gst_object_unref (filter);
990 gst_element_set_state (pipe, GST_STATE_NULL);
991 gst_object_unref (pipe);
997 Note how we use `gst_bus_poll()` with a small timeout to get messages
998 and also introduce a short sleep.
1000 It is possible to set multiple caps for the capsfilter separated with a
1001 `;`. The capsfilter will try to renegotiate to the first possible format
1004 ## Dynamically changing the pipeline
1006 In this section we talk about some techniques for dynamically modifying
1007 the pipeline. We are talking specifically about changing the pipeline
1008 while in `PLAYING` state and without interrupting the data flow.
1010 There are some important things to consider when building dynamic
1013 - When removing elements from the pipeline, make sure that there is no
1014 dataflow on unlinked pads because that will cause a fatal pipeline
1015 error. Always block source pads (in push mode) or sink pads (in pull
1016 mode) before unlinking pads. See also [Changing elements in a
1017 pipeline](#changing-elements-in-a-pipeline).
1019 - When adding elements to a pipeline, make sure to put the element
1020 into the right state, usually the same state as the parent, before
1021 allowing dataflow. When an element is newly created, it is in the
1022 `NULL` state and will return an error when it receives data.
1023 See also [Changing elements in a pipeline](#changing-elements-in-a-pipeline).
1025 - When adding elements to a pipeline, GStreamer will by default set
1026 the clock and base-time on the element to the current values of the
1027 pipeline. This means that the element will be able to construct the
1028 same pipeline running-time as the other elements in the pipeline.
1029 This means that sinks will synchronize buffers like the other sinks
1030 in the pipeline and that sources produce buffers with a running-time
1031 that matches the other sources.
1033 - When unlinking elements from an upstream chain, always make sure to
1034 flush any queued data in the element by sending an `EOS` event down
1035 the element sink pad(s) and by waiting that the `EOS` leaves the
1036 elements (with an event probe).
1038 If you don't perform a flush, you will lose the data buffered by the
1039 unlinked element. This can result in a simple frame loss (a few video frames,
1040 several milliseconds of audio, etc) but If you remove a muxer -- and in
1041 some cases an encoder or similar elements --, you risk getting a corrupted
1042 file which can't be played properly because some relevant metadata (header,
1043 seek/index tables, internal sync tags) might not be properly stored or updated.
1045 See also [Changing elements in a pipeline](#changing-elements-in-a-pipeline).
1047 - A live source will produce buffers with a `running-time` equal to the
1048 pipeline's current `running-time`.
1050 A pipeline without a live source produces buffers with a
1051 `running-time` starting from 0. Likewise, after a flushing seek, these
1052 pipelines reset the `running-time` back to 0.
1054 The `running-time` can be changed with `gst_pad_set_offset ()`. It is
1055 important to know the `running-time` of the elements in the pipeline
1056 in order to maintain synchronization.
1058 - Adding elements might change the state of the pipeline. Adding a
1059 non-prerolled sink, for example, brings the pipeline back to the
1060 prerolling state. Removing a non-prerolled sink, for example, might
1061 change the pipeline to PAUSED and PLAYING state.
1063 Adding a live source cancels the preroll stage and puts the pipeline
1064 in the playing state. Adding any live element might also change the
1067 Adding or removing pipeline's elements might change the clock
1068 selection of the pipeline. If the newly added element provides a
1069 clock, it might be good for the pipeline to use the new clock. If, on
1070 the other hand, the element that is providing the clock for the
1071 pipeline is removed, a new clock has to be selected.
1073 - Adding and removing elements might cause upstream or downstream
1074 elements to renegotiate caps and/or allocators. You don't really
1075 need to do anything from the application, plugins largely adapt
1076 themselves to the new pipeline topology in order to optimize their
1077 formats and allocation strategy.
1079 What is important is that when you add, remove or change elements in
1080 a pipeline, it is possible that the pipeline needs to negotiate a
1081 new format and this can fail. Usually you can fix this by inserting
1082 the right converter elements where needed. See also [Changing
1083 elements in a pipeline](#changing-elements-in-a-pipeline).
1085 GStreamer offers support for doing almost any dynamic pipeline modification but
1086 you need to know a few details before you can do this without causing pipeline
1087 errors. In the following sections we will demonstrate a few typical modification
1090 ### Changing elements in a pipeline
1092 In this example we have the following element chain:
1095 - ----. .----------. .---- -
1096 element1 | | element2 | | element3
1097 src -> sink src -> sink
1098 - ----' '----------' '---- -
1102 We want to replace element2 by element4 while the pipeline is in the
1103 PLAYING state. Let's say that element2 is a visualization and that you
1104 want to switch the visualization in the pipeline.
1106 We can't just unlink element2's sinkpad from element1's source pad
1107 because that would leave element1's source pad unlinked and would cause
1108 a streaming error in the pipeline when data is pushed on the source pad.
1109 The technique is to block the dataflow from element1's source pad before
1110 we replace element2 by element4 and then resume dataflow as shown in the
1113 - Block element1's source pad with a blocking pad probe. When the pad
1114 is blocked, the probe callback will be called.
1116 - Inside the block callback nothing is flowing between element1 and
1117 element2 and nothing will flow until unblocked.
1119 - Unlink element1 and element2.
1121 - Make sure data is flushed out of element2. Some elements might
1122 internally keep some data, you need to make sure not to lose any by
1123 forcing it out of element2. You can do this by pushing `EOS` into
1124 element2, like this:
1126 - Put an event probe on element2's source pad.
1128 - Send `EOS` to element2's sink pad. This makes sure that all the data
1129 inside element2 is forced out.
1131 - Wait for the `EOS` event to appear on element2's source pad. When
1132 the `EOS` is received, drop it and remove the event probe.
1134 - Unlink element2 and element3. You can now also remove element2 from
1135 the pipeline and set the state to `NULL`.
1137 - Add element4 to the pipeline, if not already added. Link element4
1138 and element3. Link element1 and element4.
1140 - Make sure element4 is in the same state as the rest of the elements
1141 in the pipeline. It should be at least in the `PAUSED` state before it
1142 can receive buffers and events.
1144 - Unblock element1's source pad probe. This will let new data into
1145 element4 and continue streaming.
1147 The above algorithm works when the source pad is blocked, i.e. when
1148 there is dataflow in the pipeline. If there is no dataflow, there is
1149 also no point in changing the element (just yet) so this algorithm can
1150 be used in the `PAUSED` state as well.
1152 This example changes the video effect on a simple pipeline once per
1156 #include <gst/gst.h>
1158 static gchar *opt_effects = NULL;
1160 #define DEFAULT_EFFECTS "identity,exclusion,navigationtest," \
1161 "agingtv,videoflip,vertigotv,gaussianblur,shagadelictv,edgetv"
1163 static GstPad *blockpad;
1164 static GstElement *conv_before;
1165 static GstElement *conv_after;
1166 static GstElement *cur_effect;
1167 static GstElement *pipeline;
1169 static GQueue effects = G_QUEUE_INIT;
1171 static GstPadProbeReturn
1172 event_probe_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
1174 GMainLoop *loop = user_data;
1177 if (GST_EVENT_TYPE (GST_PAD_PROBE_INFO_DATA (info)) != GST_EVENT_EOS)
1178 return GST_PAD_PROBE_PASS;
1180 gst_pad_remove_probe (pad, GST_PAD_PROBE_INFO_ID (info));
1182 /* push current effect back into the queue */
1183 g_queue_push_tail (&effects, gst_object_ref (cur_effect));
1184 /* take next effect from the queue */
1185 next = g_queue_pop_head (&effects);
1187 GST_DEBUG_OBJECT (pad, "no more effects");
1188 g_main_loop_quit (loop);
1189 return GST_PAD_PROBE_DROP;
1192 g_print ("Switching from '%s' to '%s'..\n", GST_OBJECT_NAME (cur_effect),
1193 GST_OBJECT_NAME (next));
1195 gst_element_set_state (cur_effect, GST_STATE_NULL);
1197 /* remove unlinks automatically */
1198 GST_DEBUG_OBJECT (pipeline, "removing %" GST_PTR_FORMAT, cur_effect);
1199 gst_bin_remove (GST_BIN (pipeline), cur_effect);
1201 GST_DEBUG_OBJECT (pipeline, "adding %" GST_PTR_FORMAT, next);
1202 gst_bin_add (GST_BIN (pipeline), next);
1204 GST_DEBUG_OBJECT (pipeline, "linking..");
1205 gst_element_link_many (conv_before, next, conv_after, NULL);
1207 gst_element_set_state (next, GST_STATE_PLAYING);
1210 GST_DEBUG_OBJECT (pipeline, "done");
1212 return GST_PAD_PROBE_DROP;
1215 static GstPadProbeReturn
1216 pad_probe_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
1218 GstPad *srcpad, *sinkpad;
1220 GST_DEBUG_OBJECT (pad, "pad is blocked now");
1222 /* remove the probe first */
1223 gst_pad_remove_probe (pad, GST_PAD_PROBE_INFO_ID (info));
1225 /* install new probe for EOS */
1226 srcpad = gst_element_get_static_pad (cur_effect, "src");
1227 gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_BLOCK |
1228 GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, event_probe_cb, user_data, NULL);
1229 gst_object_unref (srcpad);
1231 /* push EOS into the element, the probe will be fired when the
1232 * EOS leaves the effect and it has thus drained all of its data */
1233 sinkpad = gst_element_get_static_pad (cur_effect, "sink");
1234 gst_pad_send_event (sinkpad, gst_event_new_eos ());
1235 gst_object_unref (sinkpad);
1237 return GST_PAD_PROBE_OK;
1241 timeout_cb (gpointer user_data)
1243 gst_pad_add_probe (blockpad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
1244 pad_probe_cb, user_data, NULL);
1250 bus_cb (GstBus * bus, GstMessage * msg, gpointer user_data)
1252 GMainLoop *loop = user_data;
1254 switch (GST_MESSAGE_TYPE (msg)) {
1255 case GST_MESSAGE_ERROR:{
1259 gst_message_parse_error (msg, &err, &dbg);
1260 gst_object_default_error (msg->src, err, dbg);
1261 g_clear_error (&err);
1263 g_main_loop_quit (loop);
1273 main (int argc, char **argv)
1275 GOptionEntry options[] = {
1276 {"effects", 'e', 0, G_OPTION_ARG_STRING, &opt_effects,
1277 "Effects to use (comma-separated list of element names)", NULL},
1280 GOptionContext *ctx;
1283 GstElement *src, *q1, *q2, *effect, *filter1, *filter2, *sink;
1284 gchar **effect_names, **e;
1286 ctx = g_option_context_new ("");
1287 g_option_context_add_main_entries (ctx, options, NULL);
1288 g_option_context_add_group (ctx, gst_init_get_option_group ());
1289 if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1290 g_print ("Error initializing: %s\n", err->message);
1291 g_clear_error (&err);
1292 g_option_context_free (ctx);
1295 g_option_context_free (ctx);
1297 if (opt_effects != NULL)
1298 effect_names = g_strsplit (opt_effects, ",", -1);
1300 effect_names = g_strsplit (DEFAULT_EFFECTS, ",", -1);
1302 for (e = effect_names; e != NULL && *e != NULL; ++e) {
1305 el = gst_element_factory_make (*e, NULL);
1307 g_print ("Adding effect '%s'\n", *e);
1308 g_queue_push_tail (&effects, el);
1312 pipeline = gst_pipeline_new ("pipeline");
1314 src = gst_element_factory_make ("videotestsrc", NULL);
1315 g_object_set (src, "is-live", TRUE, NULL);
1317 filter1 = gst_element_factory_make ("capsfilter", NULL);
1318 gst_util_set_object_arg (G_OBJECT (filter1), "caps",
1319 "video/x-raw, width=320, height=240, "
1320 "format={ I420, YV12, YUY2, UYVY, AYUV, Y41B, Y42B, "
1321 "YVYU, Y444, v210, v216, NV12, NV21, UYVP, A420, YUV9, YVU9, IYU1 }");
1323 q1 = gst_element_factory_make ("queue", NULL);
1325 blockpad = gst_element_get_static_pad (q1, "src");
1327 conv_before = gst_element_factory_make ("videoconvert", NULL);
1329 effect = g_queue_pop_head (&effects);
1330 cur_effect = effect;
1332 conv_after = gst_element_factory_make ("videoconvert", NULL);
1334 q2 = gst_element_factory_make ("queue", NULL);
1336 filter2 = gst_element_factory_make ("capsfilter", NULL);
1337 gst_util_set_object_arg (G_OBJECT (filter2), "caps",
1338 "video/x-raw, width=320, height=240, "
1339 "format={ RGBx, BGRx, xRGB, xBGR, RGBA, BGRA, ARGB, ABGR, RGB, BGR }");
1341 sink = gst_element_factory_make ("ximagesink", NULL);
1343 gst_bin_add_many (GST_BIN (pipeline), src, filter1, q1, conv_before, effect,
1344 conv_after, q2, sink, NULL);
1346 gst_element_link_many (src, filter1, q1, conv_before, effect, conv_after,
1349 gst_element_set_state (pipeline, GST_STATE_PLAYING);
1351 loop = g_main_loop_new (NULL, FALSE);
1353 gst_bus_add_watch (GST_ELEMENT_BUS (pipeline), bus_cb, loop);
1355 g_timeout_add_seconds (1, timeout_cb, loop);
1357 g_main_loop_run (loop);
1359 gst_element_set_state (pipeline, GST_STATE_NULL);
1360 gst_object_unref (pipeline);
1366 Note how we added `videoconvert` elements before and after the effect.
1367 This is needed because some elements might operate in different
1368 colorspaces; by inserting the conversion elements, we can help ensure
1369 a proper format can be negotiated.