555d0ba6ac6e19e47944111ecc61f40beb980d6f
[platform/upstream/gstreamer.git] / docs / manual / advanced-dataaccess.xml
1 <chapter id="chapter-dataaccess">
2   <title>Pipeline manipulation</title>
3   <para>
4     This chapter will discuss how you can manipulate your pipeline in several
5     ways from your application on. Parts of this chapter are very
6     lowlevel, so be assured that you'll need some programming knowledge
7     and a good understanding of &GStreamer; before you start reading this.
8   </para>
9   <para>
10     Topics that will be discussed here include how you can insert data into
11     a pipeline from your application, how to read data from a pipeline,
12     how to manipulate the pipeline's speed, length, starting point and how
13     to listen to a pipeline's data processing.
14   </para>
15
16   <sect1 id="section-using-probes">
17     <title>Using probes</title>
18     <para>
19       Probing is best envisioned as a pad listener. Technically, a probe is
20       nothing more than a callback that can be attached to a pad.
21       You can attach a probe using <function>gst_pad_add_probe ()</function>.
22       Similarly, one can use the
23       <function>gst_pad_remove_probe ()</function>
24       to remove the callback again. The probe notifies you of any activity
25       that happens on the pad, like buffers, events and queries. You can
26       define what kind of notifications you are interested in when you
27       add the probe.
28     </para>
29     <para>
30       The probe can notify you of the following activity on pads:
31     </para>
32     <itemizedlist>
33       <listitem>
34         <para>
35           A buffer is pushed or pulled. You want to specify the
36           GST_PAD_PROBE_TYPE_BUFFER when registering the probe. Because the
37           pad can be scheduled in different ways, it is possible to also
38           specify in what scheduling mode you are interested with the
39           optional GST_PAD_PROBE_TYPE_PUSH and GST_PAD_PROBE_TYPE_PULL
40           flags.
41         </para>
42         <para>
43           You can use this probe to inspect, modify or drop the buffer.
44           See <xref linkend="section-data-probes"/>.
45         </para>
46       </listitem>
47       <listitem>
48         <para>
49           A bufferlist is pushed. Use the GST_PAD_PROBE_TYPE_BUFFER_LIST
50           when registering the probe.
51         </para>
52       </listitem>
53       <listitem>
54         <para>
55           An event travels over a pad. Use the GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM
56           and GST_PAD_PROBE_TYPE_EVENT_UPSTREAM flags to select downstream
57           and upstream events. There is also a convenience
58           GST_PAD_PROBE_TYPE_EVENT_BOTH to be notified of events going both
59           upstream and downstream. By default, flush events do not cause
60           a notification. You need to explicitly enable GST_PAD_PROBE_TYPE_EVENT_FLUSH
61           to receive callbacks from flushing events. Events are always
62           only notified in push mode.
63         </para>
64         <para>
65           You can use this probe to inspect, modify or drop the event.
66         </para>
67       </listitem>
68       <listitem>
69         <para>
70           A query travels over a pad. Use the GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM
71           and GST_PAD_PROBE_TYPE_QUERY_UPSTREAM flags to select downstream
72           and upstream queries. The convenience GST_PAD_PROBE_TYPE_QUERY_BOTH
73           can also be used to select both directions. Query probes will be
74           notified twice, once when the query travels upstream/downstream and
75           once when the query result is returned. You can select in what stage
76           the callback will be called with the GST_PAD_PROBE_TYPE_PUSH and
77           GST_PAD_PROBE_TYPE_PULL, respectively when the query is performed
78           and when the query result is returned.
79         </para>
80         <para>
81           You can use this probe to inspect or modify the query. You can also
82           answer the query in the probe callback by placing the result value
83           in the query and by returning GST_PAD_PROBE_DROP from the 
84           callback.
85         </para>
86       </listitem>
87       <listitem>
88         <para>
89           In addition to notifying you of dataflow, you can also ask the
90           probe to block the dataflow when the callback returns. This is
91           called a blocking probe and is activated by specifying the
92           GST_PAD_PROBE_TYPE_BLOCK flag. You can use this flag with the
93           other flags to only block dataflow on selected activity. A pad
94           becomes unblocked again if you remove the probe or when you return
95           GST_PAD_PROBE_REMOVE from the callback. You can let only the
96           currently blocked item pass by returning GST_PAD_PROBE_PASS
97           from the callback, it will block again on the next item.
98         </para>
99         <para>
100           Blocking probes are used to temporarily block pads because they
101           are unlinked or because you are going to unlink them. If the
102           dataflow is not blocked, the pipeline would go into an error
103           state if data is pushed on an unlinked pad. We will se how
104           to use blocking probes to partially preroll a pipeline.
105           See also <xref linkend="section-preroll-probes"/>.
106         </para>
107       </listitem>
108       <listitem>
109         <para>
110           Be notified when no activity is happening on a pad. You install
111           this probe with the GST_PAD_PROBE_TYPE_IDLE flag. You can specify
112           GST_PAD_PROBE_TYPE_PUSH and/or GST_PAD_PROBE_TYPE_PULL to 
113           only be notified depending on the pad scheduling mode.
114           The IDLE probe is also a blocking probe in that it will not let
115           any data pass on the pad for as long as the IDLE probe is
116           installed.
117         </para>
118         <para>
119           You can use idle probes to dynamically relink a pad.  We will see
120           how to use idle probes to replace an element in the pipeline.
121           See also <xref linkend="section-dynamic-pipelines"/>.
122         </para>
123       </listitem>
124     </itemizedlist>
125
126     <sect2 id="section-data-probes">
127       <title>Data probes</title>
128       <para>
129         Data probes allow you to be notified when there is data passing
130         on a pad. When adding the probe, specify the GST_PAD_PROBE_TYPE_BUFFER
131         and/or GST_PAD_PROBE_TYPE_BUFFER_LIST. 
132       </para>
133       <para>
134         Data probes run in pipeline streaming thread context, so callbacks
135         should try to not block and generally not do any weird stuff, since
136         this could have a negative impact on pipeline performance or, in case
137         of bugs, cause deadlocks or crashes. More precisely, one should usually
138         not call any GUI-related functions from within a probe callback, nor try
139         to change the state of the pipeline.  An application may post custom
140         messages on the pipeline's bus though to communicate with the main
141         application thread and have it do things like stop the pipeline.
142       </para>
143       <para>
144         In any case, most common buffer operations
145         that elements can do in <function>_chain ()</function> functions, can
146         be done in probe callbacks as well. The example below gives a short
147         impression on how to use them.
148       </para>
149       <programlisting>
150 <!-- example-begin probe.c -->
151 <![CDATA[
152 #include <gst/gst.h>
153
154 static GstPadProbeReturn
155 cb_have_data (GstPad          *pad,
156               GstPadProbeInfo *info,
157               gpointer         user_data)
158 {
159   gint x, y;
160   GstMapInfo map;
161   guint16 *ptr, t;
162   GstBuffer *buffer;
163
164   buffer = GST_PAD_PROBE_INFO_BUFFER (info);
165
166   buffer = gst_buffer_make_writable (buffer);
167   
168   gst_buffer_map (buffer, &map, GST_MAP_WRITE);
169
170   ptr = (guint16 *) map.data;
171   /* invert data */
172   for (y = 0; y < 288; y++) {
173     for (x = 0; x < 384 / 2; x++) {
174       t = ptr[384 - 1 - x];
175       ptr[384 - 1 - x] = ptr[x];
176       ptr[x] = t;
177     }
178     ptr += 384;
179   }
180   gst_buffer_unmap (buffer, &map);
181
182   GST_PAD_PROBE_INFO_DATA (info) = buffer;
183
184   return GST_PAD_PROBE_OK;
185 }
186
187 gint
188 main (gint   argc,
189       gchar *argv[])
190 {
191   GMainLoop *loop;
192   GstElement *pipeline, *src, *sink, *filter, *csp;
193   GstCaps *filtercaps;
194   GstPad *pad;
195
196   /* init GStreamer */
197   gst_init (&argc, &argv);
198   loop = g_main_loop_new (NULL, FALSE);
199
200   /* build */
201   pipeline = gst_pipeline_new ("my-pipeline");
202   src = gst_element_factory_make ("videotestsrc", "src");
203   if (src == NULL)
204     g_error ("Could not create 'videotestsrc' element");
205
206   filter = gst_element_factory_make ("capsfilter", "filter");
207   g_assert (filter != NULL); /* should always exist */
208
209   csp = gst_element_factory_make ("videoconvert", "csp");
210   if (csp == NULL)
211     g_error ("Could not create 'videoconvert' element");
212
213   sink = gst_element_factory_make ("xvimagesink", "sink");
214   if (sink == NULL) {
215     sink = gst_element_factory_make ("ximagesink", "sink");
216     if (sink == NULL)
217       g_error ("Could not create neither 'xvimagesink' nor 'ximagesink' element");
218   }
219
220   gst_bin_add_many (GST_BIN (pipeline), src, filter, csp, sink, NULL);
221   gst_element_link_many (src, filter, csp, sink, NULL);
222   filtercaps = gst_caps_new_simple ("video/x-raw",
223                            "format", G_TYPE_STRING, "RGB16",
224                            "width", G_TYPE_INT, 384,
225                            "height", G_TYPE_INT, 288,
226                            "framerate", GST_TYPE_FRACTION, 25, 1,
227                            NULL);
228   g_object_set (G_OBJECT (filter), "caps", filtercaps, NULL);
229   gst_caps_unref (filtercaps);
230
231   pad = gst_element_get_static_pad (src, "src");
232   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BUFFER,
233       (GstPadProbeCallback) cb_have_data, NULL, NULL);
234   gst_object_unref (pad);
235
236   /* run */
237   gst_element_set_state (pipeline, GST_STATE_PLAYING);
238
239   /* wait until it's up and running or failed */
240   if (gst_element_get_state (pipeline, NULL, NULL, -1) == GST_STATE_CHANGE_FAILURE) {
241     g_error ("Failed to go into PLAYING state");
242   }
243
244   g_print ("Running ...\n");
245   g_main_loop_run (loop);
246
247   /* exit */
248   gst_element_set_state (pipeline, GST_STATE_NULL);
249   gst_object_unref (pipeline);
250
251   return 0;
252 }
253 ]]>
254 <!-- example-end probe.c -->
255       </programlisting>
256       <para>
257         Compare that output with the output of <quote>gst-launch-1.0
258         videotestsrc ! xvimagesink</quote>, just so you know what you're
259         looking for.
260       </para>
261       <para>
262         Strictly speaking, a pad probe callback is only allowed to modify the
263         buffer content if the buffer is writable.  Whether this is the case or
264         not depends a lot on the pipeline and the elements involved.  Often
265         enough, this is the case, but sometimes it is not, and if it is not
266         then unexpected modification of the data or metadata can introduce
267         bugs that are very hard to debug and track down. You can check if a
268         buffer is writable with <function>gst_buffer_is_writable ()</function>.
269         Since you can pass back a different buffer than the one passed in,
270         it is a good idea to make the buffer writable in the callback function
271         with <function>gst_buffer_make_writable ()</function>.
272       </para>
273       <para>
274         Pad probes are suited best for looking at data as it passes through
275         the pipeline. If you need to modify data, you should better write your
276         own GStreamer element. Base classes like GstAudioFilter, GstVideoFilter or
277         GstBaseTransform make this fairly easy.
278       </para>
279       <para>
280         If you just want to inspect buffers as they pass through the pipeline,
281         you don't even need to set up pad probes. You could also just insert
282         an identity element into the pipeline and connect to its "handoff"
283         signal. The identity element also provides a few useful debugging tools
284         like the "dump" property or the "last-message" property (the latter is
285         enabled by passing the '-v' switch to gst-launch and by setting the
286         silent property on the identity to FALSE).
287       </para>
288     </sect2>
289
290     <sect2 id="section-preroll-probes">
291       <title>Play a region of a media file</title>
292       <para>
293         In this example we will show you how to play back a region of
294         a media file. The goal is to only play the part of a file
295         from 2 seconds to 5 seconds and then EOS.
296       </para>
297       <para>
298         In a first step we will set a uridecodebin element to the PAUSED
299         state and make sure that we block all the source pads that are
300         created. When all the source pads are blocked, we have data on
301         all source pads and we say that the uridecodebin is prerolled.
302       </para>
303       <para>
304         In a prerolled pipeline we can ask for the duration of the media
305         and we can also perform seeks. We are interested in performing a
306         seek operation on the pipeline to select the range of media
307         that we are interested in.
308       </para>
309       <para>
310         After we configure the region we are interested in, we can link
311         the sink element, unblock the source pads and set the pipeline to
312         the playing state. You will see that exactly the requested
313         region is played by the sink before it goes to EOS.
314       </para>
315       <para>
316         What follows is an example application that loosly follows this
317         algorithm.
318       </para>
319       <programlisting>
320 <!-- example-begin blockprobe.c -->
321 <![CDATA[
322 #include <gst/gst.h>
323
324 static GMainLoop *loop;
325 static volatile gint counter;
326 static GstBus *bus;
327 static gboolean prerolled = FALSE;
328 static GstPad *sinkpad;
329
330 static void
331 dec_counter (GstElement * pipeline)
332 {
333   if (prerolled)
334     return;
335
336   if (g_atomic_int_dec_and_test (&counter)) {
337     /* all probes blocked and no-more-pads signaled, post
338      * message on the bus. */
339     prerolled = TRUE;
340
341     gst_bus_post (bus, gst_message_new_application (
342           GST_OBJECT_CAST (pipeline),
343           gst_structure_new_empty ("ExPrerolled")));
344   }
345 }
346
347 /* called when a source pad of uridecodebin is blocked */
348 static GstPadProbeReturn
349 cb_blocked (GstPad          *pad,
350             GstPadProbeInfo *info,
351             gpointer         user_data)
352 {
353   GstElement *pipeline = GST_ELEMENT (user_data);
354
355   if (prerolled)
356     return GST_PAD_PROBE_REMOVE;
357
358   dec_counter (pipeline);
359
360   return GST_PAD_PROBE_OK;
361 }
362
363 /* called when uridecodebin has a new pad */
364 static void
365 cb_pad_added (GstElement *element,
366               GstPad     *pad,
367               gpointer    user_data)
368 {
369   GstElement *pipeline = GST_ELEMENT (user_data);
370
371   if (prerolled)
372     return;
373
374   g_atomic_int_inc (&counter);
375
376   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
377       (GstPadProbeCallback) cb_blocked, pipeline, NULL);
378
379   /* try to link to the video pad */
380   gst_pad_link (pad, sinkpad);
381 }
382
383 /* called when uridecodebin has created all pads */
384 static void
385 cb_no_more_pads (GstElement *element,
386                  gpointer    user_data)
387 {
388   GstElement *pipeline = GST_ELEMENT (user_data);
389
390   if (prerolled)
391     return;
392
393   dec_counter (pipeline);
394 }
395
396 /* called when a new message is posted on the bus */
397 static void
398 cb_message (GstBus     *bus,
399             GstMessage *message,
400             gpointer    user_data)
401 {
402   GstElement *pipeline = GST_ELEMENT (user_data);
403
404   switch (GST_MESSAGE_TYPE (message)) {
405     case GST_MESSAGE_ERROR:
406       g_print ("we received an error!\n");
407       g_main_loop_quit (loop);
408       break;
409     case GST_MESSAGE_EOS:
410       g_print ("we reached EOS\n");
411       g_main_loop_quit (loop);
412       break;
413     case GST_MESSAGE_APPLICATION:
414     {
415       if (gst_message_has_name (message, "ExPrerolled")) {
416         /* it's our message */
417         g_print ("we are all prerolled, do seek\n");
418         gst_element_seek (pipeline,
419             1.0, GST_FORMAT_TIME,
420             GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
421             GST_SEEK_TYPE_SET, 2 * GST_SECOND,
422             GST_SEEK_TYPE_SET, 5 * GST_SECOND);
423
424         gst_element_set_state (pipeline, GST_STATE_PLAYING);
425       }
426       break;
427     }
428     default:
429       break;
430   }
431 }
432
433 gint
434 main (gint   argc,
435       gchar *argv[])
436 {
437   GstElement *pipeline, *src, *csp, *vs, *sink;
438
439   /* init GStreamer */
440   gst_init (&argc, &argv);
441   loop = g_main_loop_new (NULL, FALSE);
442
443   if (argc < 2) {
444     g_print ("usage: %s <uri>", argv[0]);
445     return -1;
446   }
447
448   /* build */
449   pipeline = gst_pipeline_new ("my-pipeline");
450
451   bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
452   gst_bus_add_signal_watch (bus);
453   g_signal_connect (bus, "message", (GCallback) cb_message,
454       pipeline);
455
456   src = gst_element_factory_make ("uridecodebin", "src");
457   if (src == NULL)
458     g_error ("Could not create 'uridecodebin' element");
459
460   g_object_set (src, "uri", argv[1], NULL);
461
462   csp = gst_element_factory_make ("videoconvert", "csp");
463   if (csp == NULL)
464     g_error ("Could not create 'videoconvert' element");
465
466   vs = gst_element_factory_make ("videoscale", "vs");
467   if (csp == NULL)
468     g_error ("Could not create 'videoscale' element");
469
470   sink = gst_element_factory_make ("autovideosink", "sink");
471   if (sink == NULL)
472     g_error ("Could not create 'autovideosink' element");
473
474   gst_bin_add_many (GST_BIN (pipeline), src, csp, vs, sink, NULL);
475
476   /* can't link src yet, it has no pads */
477   gst_element_link_many (csp, vs, sink, NULL);
478
479   sinkpad = gst_element_get_static_pad (csp, "sink");
480
481   /* for each pad block that is installed, we will increment
482    * the counter. for each pad block that is signaled, we
483    * decrement the counter. When the counter is 0 we post
484    * an app message to tell the app that all pads are
485    * blocked. Start with 1 that is decremented when no-more-pads
486    * is signaled to make sure that we only post the message
487    * after no-more-pads */
488   g_atomic_int_set (&counter, 1);
489
490   g_signal_connect (src, "pad-added",
491       (GCallback) cb_pad_added, pipeline);
492   g_signal_connect (src, "no-more-pads",
493       (GCallback) cb_no_more_pads, pipeline);
494
495   gst_element_set_state (pipeline, GST_STATE_PAUSED);
496
497   g_main_loop_run (loop);
498
499   gst_element_set_state (pipeline, GST_STATE_NULL);
500
501   gst_object_unref (sinkpad);
502   gst_object_unref (bus);
503   gst_object_unref (pipeline);
504   g_main_loop_unref (loop);
505
506   return 0;
507 }
508 ]]>
509 <!-- example-end blockprobe.c -->
510 </programlisting>
511       <para>
512         Note that we use a custom application message to signal the
513         main thread that the uridecidebin is prerolled. The main thread
514         will then issue a flushing seek to the requested region. The
515         flush will temporarily unblock the pad and reblock them when
516         new data arrives again. We detect this second block to remove
517         the probes. Then we set the pipeline to PLAYING and it should
518         play from 2 to 5 seconds, then EOS and exit the application.
519       </para>
520     </sect2>
521   </sect1>
522
523   <sect1 id="section-data-spoof">
524     <title>Manually adding or removing data from/to a pipeline</title>
525     <para>
526       Many people have expressed the wish to use their own sources to inject
527       data into a pipeline. Some people have also expressed the wish to grab
528       the output in a pipeline and take care of the actual output inside
529       their application. While either of these methods are strongly
530       discouraged, &GStreamer; offers support for this.
531       <emphasis>Beware! You need to know what you are doing.</emphasis> Since
532       you don't have any support from a base class you need to thoroughly
533       understand state changes and synchronization. If it doesn't work,
534       there are a million ways to shoot yourself in the foot.  It's always
535       better to simply write a plugin and have the base class manage it.
536       See the Plugin Writer's Guide for more information on this topic. Also
537       see the next section, which will explain how to embed plugins statically
538       in your application.
539     </para>
540     <para>
541       There's two possible elements that you can use for the above-mentioned
542       purposes. Those are called <quote>appsrc</quote> (an imaginary source)
543       and <quote>appsink</quote> (an imaginary sink). The same method applies
544       to each of those elements. Here, we will discuss how to use those
545       elements to insert (using appsrc) or grab (using appsink) data from a
546       pipeline, and how to set negotiation.
547     </para>
548     <para>
549       Both appsrc and appsink provide 2 sets of API. One API uses standard
550       GObject (action) signals and properties. The same API is also
551       available as a regular C api. The C api is more performant but
552       requires you to link to the app library in order to use the elements.
553     </para>
554
555     <sect2 id="section-spoof-appsrc">
556       <title>Inserting data with appsrc</title>
557       <para>
558         First we look at some examples for appsrc, which lets you insert data
559         into the pipeline from the application. Appsrc has some configuration
560         options that define how it will operate. You should decide about the
561         following configurations:
562       </para>
563       <itemizedlist>
564         <listitem>
565           <para>
566             Will the appsrc operate in push or pull mode. The stream-type
567             property can be used to control this. stream-type of
568             <quote>random-access</quote> will activate pull mode scheduling
569             while the other stream-types activate push mode.
570           </para>
571         </listitem>
572         <listitem>
573           <para>
574             The caps of the buffers that appsrc will push out. This needs to
575             be configured with the caps property. The caps must be set to a
576             fixed caps and will be used to negotiate a format downstream.
577           </para>
578         </listitem>
579         <listitem>
580           <para>
581             If the appsrc operates in live mode or not. This can be configured
582             with the is-live property. When operating in live-mode it is
583             important to configure the min-latency and max-latency in appsrc.
584             The min-latency should be set to the amount of time it takes between
585             capturing a buffer and when it is pushed inside appsrc.
586             In live mode, you should timestamp the buffers with the pipeline
587             running-time when the first byte of the buffer was captured before
588             feeding them to appsrc. You can let appsrc do the timestaping with
589             the do-timestamp property (but then the min-latency must be set
590             to 0 because it timestamps based on the running-time when the buffer
591             entered appsrc).
592           </para>
593         </listitem>
594         <listitem>
595           <para>
596             The format of the SEGMENT event that appsrc will push. The format
597             has implications for how the running-time of the buffers will
598             be calculated so you must be sure you understand this. For
599             live sources you probably want to set the format property to
600             GST_FORMAT_TIME. For non-live source it depends on the media type
601             that you are handling. If you plan to timestamp the buffers, you
602             should probably put a GST_FORMAT_TIME format, otherwise
603             GST_FORMAT_BYTES might be appropriate.
604           </para>
605         </listitem>
606         <listitem>
607           <para>
608             If appsrc operates in random-access mode, it is important to configure
609             the size property of appsrc with the number of bytes in the stream.
610             This will allow downstream elements to know the size of the media and
611             alows them to seek to the end of the stream when needed.
612           </para>
613         </listitem>
614       </itemizedlist>
615       <para>
616         The main way of handling data to appsrc is by using the function
617         <function>gst_app_src_push_buffer ()</function> or by emiting the
618         push-buffer action signal.  This will put the buffer onto a queue from
619         which appsrc will read from in its streaming thread. It is important
620         to note that data transport will not happen from the thread that
621         performed the push-buffer call.
622       </para>
623       <para>
624         The <quote>max-bytes</quote> property controls how much data can be
625         queued in appsrc before appsrc considers the queue full. A filled
626         internal queue will always signal the <quote>enough-data</quote>
627         signal, which signals the application that it should stop pushing
628         data into appsrc. The <quote>block</quote> property will cause appsrc to
629         block the push-buffer method until free data becomes available again.
630       </para>
631       <para>
632         When the internal queue is running out of data, the
633         <quote>need-data</quote> signal is emitted, which signals the application
634         that it should start pushing more data into appsrc.
635       </para>
636       <para>
637         In addition to the <quote>need-data</quote> and <quote>enough-data</quote>
638         signals, appsrc can emit the <quote>seek-data</quote> signal when the
639         <quote>stream-mode</quote> property is set to <quote>seekable</quote>
640         or <quote>random-access</quote>. The signal argument will contain the
641         new desired position in the stream expressed in the unit set with the
642         <quote>format</quote> property. After receiving the seek-data signal,
643         the application should push-buffers from the new position.
644       </para>
645       <para>
646         When the last byte is pushed into appsrc, you must call
647         <function>gst_app_src_end_of_stream ()</function> to make it send
648         an EOS downstream.
649       </para>
650       <para>
651         These signals allow the application to operate appsrc in push and
652         pull mode as will be explained next.
653       </para>
654
655       <sect3 id="section-spoof-appsrc-push">
656         <title>Using appsrc in push mode</title>
657         <para>
658           When appsrc is configured in push mode (stream-type is stream or
659           seekable), the application repeatedly calls the push-buffer method
660           with a new buffer. Optionally, the queue size in the appsrc can be
661           controlled with the enough-data and need-data signals by respectively
662           stopping/starting the push-buffer calls. The value of the
663           min-percent property defines how empty the internal appsrc queue
664           needs to be before the need-data signal will be fired. You can set
665           this to some value >0 to avoid completely draining the queue.
666         </para>
667         <para>
668           When the stream-type is set to seekable, don't forget to implement
669           a seek-data callback.
670         </para>
671         <para>
672           Use this model when implementing various network protocols or
673           hardware devices.
674         </para>
675       </sect3>
676
677       <sect3 id="section-spoof-appsrc-pull">
678         <title>Using appsrc in pull mode</title>
679         <para>
680           In the pull model, data is fed to appsrc from the need-data signal
681           handler. You should push exactly the amount of bytes requested in the
682           need-data signal. You are only allowed to push less bytes when you are
683           at the end of the stream.
684         </para>
685         <para>
686           Use this model for file access or other randomly accessable sources.
687         </para>
688       </sect3>
689
690       <sect3 id="section-spoof-appsrc-ex">
691         <title>Appsrc example</title>
692         <para>
693           This example application will generate black/white (it switches
694           every second) video to an Xv-window output by using appsrc as a
695           source with caps to force a format. We use a colorspace
696           conversion element to make sure that we feed the right format to
697           your X server. We configure a video stream with a variable framerate
698           (0/1) and we set the timestamps on the outgoing buffers in such
699           a way that we play 2 frames per second.
700         </para>
701         <para>
702           Note how we use the pull mode method of pushing new buffers into
703           appsrc although appsrc is running in push mode. 
704         </para>
705         <programlisting>
706 <!-- example-begin appsrc.c -->
707 <![CDATA[
708 #include <gst/gst.h>
709
710 static GMainLoop *loop;
711
712 static void
713 cb_need_data (GstElement *appsrc,
714               guint       unused_size,
715               gpointer    user_data)
716 {
717   static gboolean white = FALSE;
718   static GstClockTime timestamp = 0;
719   GstBuffer *buffer;
720   guint size;
721   GstFlowReturn ret;
722
723   size = 385 * 288 * 2;
724
725   buffer = gst_buffer_new_allocate (NULL, size, NULL);
726
727   /* this makes the image black/white */
728   gst_buffer_memset (buffer, 0, white ? 0xff : 0x0, size);
729   
730   white = !white;
731
732   GST_BUFFER_PTS (buffer) = timestamp;
733   GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale_int (1, GST_SECOND, 2);
734
735   timestamp += GST_BUFFER_DURATION (buffer);
736
737   g_signal_emit_by_name (appsrc, "push-buffer", buffer, &ret);
738
739   if (ret != GST_FLOW_OK) {
740     /* something wrong, stop pushing */
741     g_main_loop_quit (loop);
742   }
743 }
744
745 gint
746 main (gint   argc,
747       gchar *argv[])
748 {
749   GstElement *pipeline, *appsrc, *conv, *videosink;
750
751   /* init GStreamer */
752   gst_init (&argc, &argv);
753   loop = g_main_loop_new (NULL, FALSE);
754
755   /* setup pipeline */
756   pipeline = gst_pipeline_new ("pipeline");
757   appsrc = gst_element_factory_make ("appsrc", "source");
758   conv = gst_element_factory_make ("videoconvert", "conv");
759   videosink = gst_element_factory_make ("xvimagesink", "videosink");
760
761   /* setup */
762   g_object_set (G_OBJECT (appsrc), "caps",
763                 gst_caps_new_simple ("video/x-raw",
764                                      "format", G_TYPE_STRING, "RGB16",
765                                      "width", G_TYPE_INT, 384,
766                                      "height", G_TYPE_INT, 288,
767                                      "framerate", GST_TYPE_FRACTION, 0, 1,
768                                      NULL), NULL);
769   gst_bin_add_many (GST_BIN (pipeline), appsrc, conv, videosink, NULL);
770   gst_element_link_many (appsrc, conv, videosink, NULL);
771
772   /* setup appsrc */
773   g_object_set (G_OBJECT (appsrc),
774                 "stream-type", 0,
775                 "format", GST_FORMAT_TIME, NULL);
776   g_signal_connect (appsrc, "need-data", G_CALLBACK (cb_need_data), NULL);
777
778   /* play */
779   gst_element_set_state (pipeline, GST_STATE_PLAYING);
780   g_main_loop_run (loop);
781
782   /* clean up */
783   gst_element_set_state (pipeline, GST_STATE_NULL);
784   gst_object_unref (GST_OBJECT (pipeline));
785   g_main_loop_unref (loop);
786
787   return 0;
788   }
789 ]]>
790 <!-- example-end appsrc.c -->
791         </programlisting>
792       </sect3>
793     </sect2>
794
795     <sect2 id="section-spoof-appsink">
796       <title>Grabbing data with appsink</title>
797       <para>
798         Unlike appsrc, appsink is a little easier to use. It also supports
799         a pull and push based model of getting data from the pipeline.
800       </para>
801       <para>
802         The normal way of retrieving samples from appsink is by using the
803         <function>gst_app_sink_pull_sample()</function> and
804         <function>gst_app_sink_pull_preroll()</function> methods or by using
805         the <quote>pull-sample</quote> and <quote>pull-preroll</quote>
806         signals.  These methods block until a sample becomes available in the
807         sink or when the sink is shut down or reaches EOS.
808       </para>
809       <para>
810         Appsink will internally use a queue to collect buffers from the
811         streaming thread. If the application is not pulling samples fast
812         enough, this queue will consume a lot of memory over time. The
813         <quote>max-buffers</quote> property can be used to limit the queue
814         size. The <quote>drop</quote> property controls whether the
815         streaming thread blocks or if older buffers are dropped when the
816         maximum queue size is reached. Note that blocking the streaming thread
817         can negatively affect real-time performance and should be avoided.
818       </para>
819       <para>
820         If a blocking behaviour is not desirable, setting the 
821         <quote>emit-signals</quote> property to TRUE will make appsink emit
822         the <quote>new-sample</quote> and <quote>new-preroll</quote> signals
823         when a sample can be pulled without blocking.
824       </para>
825       <para>
826         The <quote>caps</quote> property on appsink can be used to control
827         the formats that appsink can receive. This property can contain
828         non-fixed caps, the format of the pulled samples can be obtained by
829         getting the sample caps.
830       </para>
831       <para>
832         If one of the pull-preroll or pull-sample methods return NULL, the
833         appsink is stopped or in the EOS state. You can check for the EOS state
834         with the <quote>eos</quote> property or with the
835         <function>gst_app_sink_is_eos()</function> method.
836       </para>
837       <para>
838         The eos signal can also be used to be informed when the EOS state is
839         reached to avoid polling.
840       </para>
841       <para>
842         Consider configuring the following properties in the appsink:
843       </para>
844       <itemizedlist>
845         <listitem>
846           <para>
847             The <quote>sync</quote> property if you want to have the sink
848             base class synchronize the buffer against the pipeline clock
849             before handing you the sample.
850           </para>
851         </listitem>
852         <listitem>
853           <para>
854             Enable Quality-of-Service with the <quote>qos</quote> property.
855             If you are dealing with raw video frames and let the base class
856             sycnhronize on the clock, it might be a good idea to also let
857             the base class send QOS events upstream.
858           </para>
859         </listitem>
860         <listitem>
861           <para>
862             The caps property that contains the accepted caps. Upstream elements
863             will try to convert the format so that it matches the configured
864             caps on appsink. You must still check the
865             <classname>GstSample</classname> to get the actual caps of the
866             buffer.
867           </para>
868         </listitem>
869       </itemizedlist>
870
871       <sect3 id="section-spoof-appsink-ex">
872         <title>Appsink example</title>
873         <para>
874           What follows is an example on how to capture a snapshot of a video
875           stream using appsink.
876         </para>
877         <programlisting>
878 <!-- example-begin appsink.c -->
879 <![CDATA[
880 #include <gst/gst.h>
881 #ifdef HAVE_GTK
882 #include <gtk/gtk.h>
883 #endif
884
885 #include <stdlib.h>
886
887 #define CAPS "video/x-raw,format=RGB,width=160,pixel-aspect-ratio=1/1"
888
889 int
890 main (int argc, char *argv[])
891 {
892   GstElement *pipeline, *sink;
893   gint width, height;
894   GstSample *sample;
895   gchar *descr;
896   GError *error = NULL;
897   gint64 duration, position;
898   GstStateChangeReturn ret;
899   gboolean res;
900   GstMapInfo map;
901
902   gst_init (&argc, &argv);
903
904   if (argc != 2) {
905     g_print ("usage: %s <uri>\n Writes snapshot.png in the current directory\n",
906         argv[0]);
907     exit (-1);
908   }
909
910   /* create a new pipeline */
911   descr =
912       g_strdup_printf ("uridecodebin uri=%s ! videoconvert ! videoscale ! "
913       " appsink name=sink caps=\"" CAPS "\"", argv[1]);
914   pipeline = gst_parse_launch (descr, &error);
915
916   if (error != NULL) {
917     g_print ("could not construct pipeline: %s\n", error->message);
918     g_error_free (error);
919     exit (-1);
920   }
921
922   /* get sink */
923   sink = gst_bin_get_by_name (GST_BIN (pipeline), "sink");
924
925   /* set to PAUSED to make the first frame arrive in the sink */
926   ret = gst_element_set_state (pipeline, GST_STATE_PAUSED);
927   switch (ret) {
928     case GST_STATE_CHANGE_FAILURE:
929       g_print ("failed to play the file\n");
930       exit (-1);
931     case GST_STATE_CHANGE_NO_PREROLL:
932       /* for live sources, we need to set the pipeline to PLAYING before we can
933        * receive a buffer. We don't do that yet */
934       g_print ("live sources not supported yet\n");
935       exit (-1);
936     default:
937       break;
938   }
939   /* This can block for up to 5 seconds. If your machine is really overloaded,
940    * it might time out before the pipeline prerolled and we generate an error. A
941    * better way is to run a mainloop and catch errors there. */
942   ret = gst_element_get_state (pipeline, NULL, NULL, 5 * GST_SECOND);
943   if (ret == GST_STATE_CHANGE_FAILURE) {
944     g_print ("failed to play the file\n");
945     exit (-1);
946   }
947
948   /* get the duration */
949   gst_element_query_duration (pipeline, GST_FORMAT_TIME, &duration);
950
951   if (duration != -1)
952     /* we have a duration, seek to 5% */
953     position = duration * 5 / 100;
954   else
955     /* no duration, seek to 1 second, this could EOS */
956     position = 1 * GST_SECOND;
957
958   /* seek to the a position in the file. Most files have a black first frame so
959    * by seeking to somewhere else we have a bigger chance of getting something
960    * more interesting. An optimisation would be to detect black images and then
961    * seek a little more */
962   gst_element_seek_simple (pipeline, GST_FORMAT_TIME,
963       GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_FLUSH, position);
964
965   /* get the preroll buffer from appsink, this block untils appsink really
966    * prerolls */
967   g_signal_emit_by_name (sink, "pull-preroll", &sample, NULL);
968
969   /* if we have a buffer now, convert it to a pixbuf. It's possible that we
970    * don't have a buffer because we went EOS right away or had an error. */
971   if (sample) {
972     GstBuffer *buffer;
973     GstCaps *caps;
974     GstStructure *s;
975
976     /* get the snapshot buffer format now. We set the caps on the appsink so
977      * that it can only be an rgb buffer. The only thing we have not specified
978      * on the caps is the height, which is dependant on the pixel-aspect-ratio
979      * of the source material */
980     caps = gst_sample_get_caps (sample);
981     if (!caps) {
982       g_print ("could not get snapshot format\n");
983       exit (-1);
984     }
985     s = gst_caps_get_structure (caps, 0);
986
987     /* we need to get the final caps on the buffer to get the size */
988     res = gst_structure_get_int (s, "width", &width);
989     res |= gst_structure_get_int (s, "height", &height);
990     if (!res) {
991       g_print ("could not get snapshot dimension\n");
992       exit (-1);
993     }
994
995     /* create pixmap from buffer and save, gstreamer video buffers have a stride
996      * that is rounded up to the nearest multiple of 4 */
997     buffer = gst_sample_get_buffer (sample);
998     gst_buffer_map (buffer, &map, GST_MAP_READ);
999 #ifdef HAVE_GTK
1000     pixbuf = gdk_pixbuf_new_from_data (map.data,
1001         GDK_COLORSPACE_RGB, FALSE, 8, width, height,
1002         GST_ROUND_UP_4 (width * 3), NULL, NULL);
1003
1004     /* save the pixbuf */
1005     gdk_pixbuf_save (pixbuf, "snapshot.png", "png", &error, NULL);
1006 #endif
1007     gst_buffer_unmap (buffer, &map);
1008     gst_sample_unref (sample);
1009   } else {
1010     g_print ("could not make snapshot\n");
1011   }
1012
1013   /* cleanup and exit */
1014   gst_element_set_state (pipeline, GST_STATE_NULL);
1015   gst_object_unref (pipeline);
1016
1017   exit (0);
1018 }
1019 ]]>
1020 <!-- example-end appsink.c -->
1021 </programlisting>
1022       </sect3>
1023     </sect2>
1024   </sect1>
1025
1026   <sect1 id="section-spoof-format">
1027     <title>Forcing a format</title>
1028     <para>
1029       Sometimes you'll want to set a specific format, for example a video
1030       size and format or an audio bitsize and number of channels. You can
1031       do this by forcing a specific <classname>GstCaps</classname> on
1032       the pipeline, which is possible by using
1033       <emphasis>filtered caps</emphasis>. You can set a filtered caps on
1034       a link by using the <quote>capsfilter</quote> element in between the
1035       two elements, and specifying a <classname>GstCaps</classname> as
1036       <quote>caps</quote> property on this element. It will then
1037       only allow types matching that specified capability set for
1038       negotiation.  See also <xref linkend="section-caps-filter"/>.
1039     </para>
1040
1041     <sect2 id="section-dynamic-format">
1042       <title>Changing format in a PLAYING pipeline</title>
1043       <para>
1044         It is also possible to dynamically change the format in a pipeline
1045         while PLAYING. This can simply be done by changing the caps 
1046         property on a capsfilter. The capsfilter will send a RECONFIGURE
1047         event upstream that will make the upstream element attempt to
1048         renegotiate a new format and allocator. This only works if
1049         the upstream element is not using fixed caps on the source pad.
1050       </para>
1051       <para>
1052         Below is an example of how you can change the caps of a pipeline
1053         while in the PLAYING state:
1054       </para>
1055       <programlisting>
1056 <!-- example-begin dynformat.c -->
1057 <![CDATA[
1058 #include <stdlib.h>
1059
1060 #include <gst/gst.h>
1061
1062 #define MAX_ROUND 100
1063
1064 int
1065 main (int argc, char **argv)
1066 {
1067   GstElement *pipe, *filter;
1068   GstCaps *caps;
1069   gint width, height;
1070   gint xdir, ydir;
1071   gint round;
1072   GstMessage *message;
1073
1074   gst_init (&argc, &argv);
1075
1076   pipe = gst_parse_launch_full ("videotestsrc ! capsfilter name=filter ! "
1077              "ximagesink", NULL, GST_PARSE_FLAG_NONE, NULL);
1078   g_assert (pipe != NULL);
1079
1080   filter = gst_bin_get_by_name (GST_BIN (pipe), "filter");
1081   g_assert (filter);
1082
1083   width = 320;
1084   height = 240;
1085   xdir = ydir = -10;
1086
1087   for (round = 0; round < MAX_ROUND; round++) {
1088     gchar *capsstr;
1089     g_print ("resize to %dx%d (%d/%d)   \r", width, height, round, MAX_ROUND);
1090
1091     /* we prefer our fixed width and height but allow other dimensions to pass
1092      * as well */
1093     capsstr = g_strdup_printf ("video/x-raw, width=(int)%d, height=(int)%d",
1094         width, height);
1095
1096     caps = gst_caps_from_string (capsstr);
1097     g_free (capsstr);
1098     g_object_set (filter, "caps", caps, NULL);
1099     gst_caps_unref (caps);
1100
1101     if (round == 0)
1102       gst_element_set_state (pipe, GST_STATE_PLAYING);
1103
1104     width += xdir;
1105     if (width >= 320)
1106       xdir = -10;
1107     else if (width < 200)
1108       xdir = 10;
1109
1110     height += ydir;
1111     if (height >= 240)
1112       ydir = -10;
1113     else if (height < 150)
1114       ydir = 10;
1115
1116     message =
1117         gst_bus_poll (GST_ELEMENT_BUS (pipe), GST_MESSAGE_ERROR,
1118         50 * GST_MSECOND);
1119     if (message) {
1120       g_print ("got error           \n");
1121
1122       gst_message_unref (message);
1123     }
1124   }
1125   g_print ("done                    \n");
1126
1127   gst_object_unref (filter);
1128   gst_element_set_state (pipe, GST_STATE_NULL);
1129   gst_object_unref (pipe);
1130
1131   return 0;
1132 }
1133 ]]>
1134 <!-- example-end dynformat.c -->
1135       </programlisting>
1136       <para>
1137         Note how we use <function>gst_bus_poll()</function> with a
1138         small timeout to get messages and also introduce a short
1139         sleep.
1140       </para>
1141       <para>
1142         It is possible to set multiple caps for the capsfilter separated
1143         with a ;. The capsfilter will try to renegotiate to the first
1144         possible format from the list.
1145       </para>
1146     </sect2>
1147   </sect1>
1148
1149   <sect1 id="section-dynamic-pipelines">
1150     <title>Dynamically changing the pipeline</title>
1151     <para>
1152       In this section we talk about some techniques for dynamically
1153       modifying the pipeline. We are talking specifically about changing
1154       the pipeline while it is in the PLAYING state without interrupting
1155       the flow.
1156     </para>
1157     <para>
1158       There are some important things to consider when building dynamic
1159       pipelines:
1160     </para>
1161     <itemizedlist>
1162       <listitem>
1163         <para>
1164           When removing elements from the pipeline, make sure that there
1165           is no dataflow on unlinked pads because that will cause a fatal
1166           pipeline error. Always block source pads (in push mode) or
1167           sink pads (in pull mode) before unlinking pads.
1168           See also <xref linkend="section-dynamic-changing"/>.
1169         </para>
1170       </listitem>
1171       <listitem>
1172         <para>
1173           When adding elements to a pipeline, make sure to put the element
1174           into the right state, usually the same state as the parent, before
1175           allowing dataflow the element. When an element is newly created,
1176           it is in the NULL state and will return an error when it
1177           receives data.
1178           See also <xref linkend="section-dynamic-changing"/>.
1179         </para>
1180       </listitem>
1181       <listitem>
1182         <para>
1183           When adding elements to a pipeline, &GStreamer; will by default
1184           set the clock and base-time on the element to the current values
1185           of the pipeline. This means that the element will be able to
1186           construct the same pipeline running-time as the other elements
1187           in the pipeline. This means that sinks will synchronize buffers
1188           like the other sinks in the pipeline and that sources produce
1189           buffers with a running-time that matches the other sources.
1190         </para>
1191       </listitem>
1192       <listitem>
1193         <para>
1194           When unlinking elements from an upstream chain, always make sure
1195           to flush any queued data in the element by sending an EOS event
1196           down the element sink pad(s) and by waiting that the EOS leaves
1197           the elements (with an event probe).
1198           See also <xref linkend="section-dynamic-changing"/>.
1199         </para>
1200       </listitem>
1201       <listitem>
1202         <para>
1203           A live source will produce buffers with a running-time of the
1204           current running-time in the pipeline.
1205         </para>
1206         <para>
1207           A pipeline without a live source produces buffers with a
1208           running-time starting from 0. Likewise, after a flushing seek,
1209           those pipelines reset the running-time back to 0.
1210         </para>
1211         <para>
1212           The running-time can be changed with
1213           <function>gst_pad_set_offset ()</function>. It is important to
1214           know the running-time of the elements in the pipeline in order
1215           to maintain synchronization.
1216         </para>
1217       </listitem>
1218       <listitem>
1219         <para>
1220           Adding elements might change the state of the pipeline. Adding a
1221           non-prerolled sink, for example, brings the pipeline back to the
1222           prerolling state. Removing a non-prerolled sink, for example, might
1223           change the pipeline to PAUSED and PLAYING state.
1224         </para>
1225         <para>
1226           Adding a live source cancels the preroll stage and put the pipeline
1227           to the playing state. Adding a live source or other live elements
1228           might also change the latency of a pipeline.
1229         </para>
1230         <para>
1231           Adding or removing elements to the pipeline might change the clock
1232           selection of the pipeline. If the newly added element provides a clock,
1233           it might be worth changing the clock in the pipeline to the new
1234           clock. If, on the other hand, the element that provides the clock
1235           for the pipeline is removed, a new clock has to be selected.
1236         </para>
1237       </listitem>
1238       <listitem>
1239         <para>
1240           Adding and removing elements might cause upstream or downstream
1241           elements to renegotiate caps and or allocators. You don't really
1242           need to do anything from the application, plugins largely
1243           adapt themself to the new pipeline topology in order to optimize
1244           their formats and allocation strategy.
1245         </para>
1246         <para>
1247           What is important is that when you add, remove or change elements
1248           in the pipeline, it is possible that the pipeline needs to
1249           negotiate a new format and this can fail. Usually you can fix this
1250           by inserting the right converter elements where needed.
1251           See also <xref linkend="section-dynamic-changing"/>.
1252         </para>
1253       </listitem>
1254     </itemizedlist>
1255
1256     <para>
1257       &GStreamer; offers support for doing about any dynamic pipeline
1258       modification but it requires you to know a bit of details before
1259       you can do this without causing pipeline errors. In the following
1260       sections we will demonstrate a couple of typical use-cases.
1261     </para>
1262
1263     <sect2 id="section-dynamic-changing">
1264       <title>Changing elements in a pipeline</title>
1265       <para>
1266         In the next example we look at the following chain of elements:
1267       </para>
1268       <programlisting>
1269             - ----.      .----------.      .---- -
1270          element1 |      | element2 |      | element3
1271                 src -> sink       src -> sink
1272             - ----'      '----------'      '---- -
1273       </programlisting>
1274       <para>
1275         We want to change element2 by element4 while the pipeline is in
1276         the PLAYING state. Let's say that element2 is a visualization and
1277         that you want to switch the visualization in the pipeline.
1278       </para>
1279       <para>
1280         We can't just unlink element2's sinkpad from element1's source
1281         pad because that would leave element1's source pad
1282         unlinked and would cause a streaming error in the pipeline when
1283         data is pushed on the source pad.
1284         The technique is to block the dataflow from element1's source pad
1285         before we change element2 by element4 and then resume dataflow
1286         as shown in the following steps:
1287       </para>
1288       <itemizedlist>
1289         <listitem>
1290           <para>
1291             Block element1's source pad with a blocking pad probe. When the
1292             pad is blocked, the probe callback will be called.
1293           </para>
1294         </listitem>
1295         <listitem>
1296           <para>
1297             Inside the block callback nothing is flowing between element1
1298             and element2 and nothing will flow until unblocked.
1299           </para>
1300         </listitem>
1301         <listitem>
1302           <para>
1303             Unlink element1 and element2.
1304           </para>
1305         </listitem>
1306         <listitem>
1307           <para>
1308             Make sure data is flushed out of element2. Some elements might
1309             internally keep some data, you need to make sure not to lose data
1310             by forcing it out of element2. You can do this by pushing EOS into
1311             element2, like this:
1312           </para>
1313           <itemizedlist>
1314             <listitem>
1315               <para>
1316                 Put an event probe on element2's source pad.
1317               </para>
1318             </listitem>
1319             <listitem>
1320               <para>
1321                 Send EOS to element2's sinkpad. This makes sure the all the
1322                 data inside element2 is forced out.
1323               </para>
1324             </listitem>
1325             <listitem>
1326               <para>
1327                 Wait for the EOS event to appear on element2's source pad.
1328                 When the EOS is received, drop it and remove the event
1329                 probe.
1330               </para>
1331             </listitem>
1332           </itemizedlist>
1333         </listitem>
1334         <listitem>
1335           <para>
1336             Unlink element2 and element3. You can now also remove element2
1337             from the pipeline and set the state to NULL.
1338           </para>
1339         </listitem>
1340         <listitem>
1341           <para>
1342             Add element4 to the pipeline, if not already added. Link element4
1343             and element3. Link element1 and element4.
1344           </para>
1345         </listitem>
1346         <listitem>
1347           <para>
1348             Make sure element4 is in the same state as the rest of the elements
1349             in the pipeline. It should be at least in the PAUSED state before
1350             it can receive buffers and events.
1351           </para>
1352         </listitem>
1353         <listitem>
1354           <para>
1355             Unblock element1's source pad probe. This will let new data into
1356             element4 and continue streaming.
1357           </para>
1358         </listitem>
1359       </itemizedlist>
1360       <para>
1361         The above algorithm works when the source pad is blocked, i.e. when
1362         there is dataflow in the pipeline. If there is no dataflow, there is
1363         also no point in changing the element (just yet) so this algorithm can
1364         be used in the PAUSED state as well.
1365       </para>
1366       <para>
1367         Let show you how this works with an example. This example changes the
1368         video effect on a simple pipeline every second.
1369       </para>
1370       <programlisting>
1371 <!-- example-begin effectswitch.c -->
1372 <![CDATA[
1373 #include <gst/gst.h>
1374
1375 static gchar *opt_effects = NULL;
1376
1377 #define DEFAULT_EFFECTS "identity,exclusion,navigationtest," \
1378     "agingtv,videoflip,vertigotv,gaussianblur,shagadelictv,edgetv"
1379
1380 static GstPad *blockpad;
1381 static GstElement *conv_before;
1382 static GstElement *conv_after;
1383 static GstElement *cur_effect;
1384 static GstElement *pipeline;
1385
1386 static GQueue effects = G_QUEUE_INIT;
1387
1388 static GstPadProbeReturn
1389 event_probe_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
1390 {
1391   GMainLoop *loop = user_data;
1392   GstElement *next;
1393
1394   if (GST_EVENT_TYPE (GST_PAD_PROBE_INFO_DATA (info)) != GST_EVENT_EOS)
1395     return GST_PAD_PROBE_OK;
1396
1397   gst_pad_remove_probe (pad, GST_PAD_PROBE_INFO_ID (info));
1398
1399   /* push current event back into the queue */
1400   g_queue_push_tail (&effects, gst_object_ref (cur_effect));
1401   /* take next effect from the queue */
1402   next = g_queue_pop_head (&effects);
1403   if (next == NULL) {
1404     GST_DEBUG_OBJECT (pad, "no more effects");
1405     g_main_loop_quit (loop);
1406     return GST_PAD_PROBE_DROP;
1407   }
1408
1409   g_print ("Switching from '%s' to '%s'..\n", GST_OBJECT_NAME (cur_effect),
1410       GST_OBJECT_NAME (next));
1411
1412   gst_element_set_state (cur_effect, GST_STATE_NULL);
1413
1414   /* remove unlinks automatically */
1415   GST_DEBUG_OBJECT (pipeline, "removing %" GST_PTR_FORMAT, cur_effect);
1416   gst_bin_remove (GST_BIN (pipeline), cur_effect);
1417
1418   GST_DEBUG_OBJECT (pipeline, "adding   %" GST_PTR_FORMAT, next);
1419   gst_bin_add (GST_BIN (pipeline), next);
1420
1421   GST_DEBUG_OBJECT (pipeline, "linking..");
1422   gst_element_link_many (conv_before, next, conv_after, NULL);
1423
1424   gst_element_set_state (next, GST_STATE_PLAYING);
1425
1426   cur_effect = next;
1427   GST_DEBUG_OBJECT (pipeline, "done");
1428
1429   return GST_PAD_PROBE_DROP;
1430 }
1431
1432 static GstPadProbeReturn
1433 pad_probe_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
1434 {
1435   GstPad *srcpad, *sinkpad;
1436
1437   GST_DEBUG_OBJECT (pad, "pad is blocked now");
1438
1439   /* remove the probe first */
1440   gst_pad_remove_probe (pad, GST_PAD_PROBE_INFO_ID (info));
1441
1442   /* install new probe for EOS */
1443   srcpad = gst_element_get_static_pad (cur_effect, "src");
1444   gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_BLOCK |
1445       GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, event_probe_cb, user_data, NULL);
1446   gst_object_unref (srcpad);
1447
1448   /* push EOS into the element, the probe will be fired when the
1449    * EOS leaves the effect and it has thus drained all of its data */
1450   sinkpad = gst_element_get_static_pad (cur_effect, "sink");
1451   gst_pad_send_event (sinkpad, gst_event_new_eos ());
1452   gst_object_unref (sinkpad);
1453
1454   return GST_PAD_PROBE_OK;
1455 }
1456
1457 static gboolean
1458 timeout_cb (gpointer user_data)
1459 {
1460   gst_pad_add_probe (blockpad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM,
1461       pad_probe_cb, user_data, NULL);
1462
1463   return TRUE;
1464 }
1465
1466 static gboolean
1467 bus_cb (GstBus * bus, GstMessage * msg, gpointer user_data)
1468 {
1469   GMainLoop *loop = user_data;
1470
1471   switch (GST_MESSAGE_TYPE (msg)) {
1472     case GST_MESSAGE_ERROR:{
1473       GError *err = NULL;
1474       gchar *dbg;
1475
1476       gst_message_parse_error (msg, &err, &dbg);
1477       gst_object_default_error (msg->src, err, dbg);
1478       g_error_free (err);
1479       g_free (dbg);
1480       g_main_loop_quit (loop);
1481       break;
1482     }
1483     default:
1484       break;
1485   }
1486   return TRUE;
1487 }
1488
1489 int
1490 main (int argc, char **argv)
1491 {
1492   GOptionEntry options[] = {
1493     {"effects", 'e', 0, G_OPTION_ARG_STRING, &opt_effects,
1494         "Effects to use (comma-separated list of element names)", NULL},
1495     {NULL}
1496   };
1497   GOptionContext *ctx;
1498   GError *err = NULL;
1499   GMainLoop *loop;
1500   GstElement *src, *q1, *q2, *effect, *filter1, *filter2, *sink;
1501   gchar **effect_names, **e;
1502
1503   ctx = g_option_context_new ("");
1504   g_option_context_add_main_entries (ctx, options, NULL);
1505   g_option_context_add_group (ctx, gst_init_get_option_group ());
1506   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
1507     g_print ("Error initializing: %s\n", err->message);
1508     return 1;
1509   }
1510   g_option_context_free (ctx);
1511
1512   if (opt_effects != NULL)
1513     effect_names = g_strsplit (opt_effects, ",", -1);
1514   else
1515     effect_names = g_strsplit (DEFAULT_EFFECTS, ",", -1);
1516
1517   for (e = effect_names; e != NULL && *e != NULL; ++e) {
1518     GstElement *el;
1519
1520     el = gst_element_factory_make (*e, NULL);
1521     if (el) {
1522       g_print ("Adding effect '%s'\n", *e);
1523       g_queue_push_tail (&effects, el);
1524     }
1525   }
1526
1527   pipeline = gst_pipeline_new ("pipeline");
1528
1529   src = gst_element_factory_make ("videotestsrc", NULL);
1530   g_object_set (src, "is-live", TRUE, NULL);
1531
1532   filter1 = gst_element_factory_make ("capsfilter", NULL);
1533   gst_util_set_object_arg (G_OBJECT (filter1), "caps",
1534       "video/x-raw, width=320, height=240, "
1535       "format={ I420, YV12, YUY2, UYVY, AYUV, Y41B, Y42B, "
1536       "YVYU, Y444, v210, v216, NV12, NV21, UYVP, A420, YUV9, YVU9, IYU1 }");
1537
1538   q1 = gst_element_factory_make ("queue", NULL);
1539
1540   blockpad = gst_element_get_static_pad (q1, "src");
1541
1542   conv_before = gst_element_factory_make ("videoconvert", NULL);
1543
1544   effect = g_queue_pop_head (&effects);
1545   cur_effect = effect;
1546
1547   conv_after = gst_element_factory_make ("videoconvert", NULL);
1548
1549   q2 = gst_element_factory_make ("queue", NULL);
1550
1551   filter2 = gst_element_factory_make ("capsfilter", NULL);
1552   gst_util_set_object_arg (G_OBJECT (filter2), "caps",
1553       "video/x-raw, width=320, height=240, "
1554       "format={ RGBx, BGRx, xRGB, xBGR, RGBA, BGRA, ARGB, ABGR, RGB, BGR }");
1555
1556   sink = gst_element_factory_make ("ximagesink", NULL);
1557
1558   gst_bin_add_many (GST_BIN (pipeline), src, filter1, q1, conv_before, effect,
1559       conv_after, q2, sink, NULL);
1560
1561   gst_element_link_many (src, filter1, q1, conv_before, effect, conv_after,
1562       q2, sink, NULL);
1563
1564   gst_element_set_state (pipeline, GST_STATE_PLAYING);
1565
1566   loop = g_main_loop_new (NULL, FALSE);
1567
1568   gst_bus_add_watch (GST_ELEMENT_BUS (pipeline), bus_cb, loop);
1569
1570   g_timeout_add_seconds (1, timeout_cb, loop);
1571
1572   g_main_loop_run (loop);
1573
1574   gst_element_set_state (pipeline, GST_STATE_NULL);
1575   gst_object_unref (pipeline);
1576
1577   return 0;
1578 }
1579 ]]>
1580 <!-- example-end effectswitch.c -->
1581       </programlisting>
1582       <para>
1583         Note how we added videoconvert elements before and after the effect.
1584         This is needed because some elements might operate in different
1585         colorspaces than other elements. By inserting the conversion elements
1586         you ensure that the right format can be negotiated at any time.
1587       </para>
1588     </sect2>
1589   </sect1>
1590
1591 </chapter>