9ec99933c07d385a14f49cc40181a16e2548c1f6
[platform/upstream/gstreamer.git] / docs / pwg / advanced-negotiation.xml
1 <chapter id="chapter-negotiation" xreflabel="Caps negotiation">
2   <title>Caps negotiation</title>
3   <para>
4     Caps negotiation is the act of finding a media format (GstCaps) between
5     elements that they can handle. This process in &GStreamer; can in most
6     cases find an optimal solution for the complete pipeline. In this section
7     we explain how this works.
8   </para>
9
10   <sect1 id="section-nego-basics">
11     <title>Caps negotiation basics</title>
12     <para>
13       In &GStreamer;, negotiation of the media format always follows the
14       following simple rules:
15     </para>
16     <itemizedlist>
17       <listitem>
18         <para>
19           A downstream element suggest a format on its sinkpad and places the
20           suggestion in the result of the CAPS query performed on the sinkpad.
21           See also <xref linkend="section-nego-getcaps"/>.
22         </para>
23       </listitem>
24       <listitem>
25         <para>
26           An upstream element decides on a format. It sends the selected media
27           format downstream on its source pad with a CAPS event. Downstream
28           elements reconfigure themselves to handle the media type in the CAPS
29           event on the sinkpad.
30         </para>
31       </listitem>
32       <listitem>
33         <para>
34           A downstream element can inform upstream that it would like to
35           suggest a new format by sending a RECONFIGURE event upstream. The
36           RECONFIGURE event simply instructs an upstream element to restart
37           the negotiation phase. Because the element that sent out the
38           RECONFIGURE event is now suggesting another format, the format
39           in the pipeline might change.
40         </para>
41       </listitem>
42     </itemizedlist>
43     <para>
44       In addition to the CAPS and RECONFIGURE event and the CAPS query, there
45       is an ACCEPT_CAPS query to quickly check if a certain caps can
46       be accepted by an element.
47     </para>
48     <para>
49       All negotiation follows these simple rules. Let's take a look at some
50       typical uses cases and how negotiation happens.
51     </para>
52   </sect1>
53
54   <sect1 id="section-nego-usecases">
55     <title>Caps negotiation use cases</title>
56     <para>
57       In what follows we will look at some use cases for push-mode scheduling.
58       The pull-mode scheduling negotiation phase is discussed in
59       <xref linkend="section-nego-pullmode"/> and is actually similar as we
60       will see. 
61     </para>
62     <para>
63       Since the sink pads only suggest formats and the source pads need to
64       decide, the most complicated work is done in the source pads.
65       We can identify 3 caps negotiation use cases for the source pads:
66     </para>
67     <itemizedlist>
68       <listitem>
69         <para>
70           Fixed negotiation. An element can output one format only.
71           See <xref linkend="section-nego-fixed"/>.
72         </para>
73       </listitem>
74       <listitem>
75         <para>
76           Transform negotiation. There is a (fixed) transform between the
77           input and output format of the element, usually based on some
78           element property. The caps that the element will produce depend
79           on the upstream caps and the caps that the element can accept
80           depend on the downstream caps.
81           See <xref linkend="section-nego-transform"/>.
82         </para>
83       </listitem>
84       <listitem>
85         <para>
86           Dynamic negotiation. An element can output many formats.
87           See <xref linkend="section-nego-dynamic"/>.
88         </para>
89       </listitem>
90     </itemizedlist>
91
92     <sect2 id="section-nego-fixed">
93       <title>Fixed negotiation</title>
94       <para>
95         In this case, the source pad can only produce a fixed format. Usually
96         this format is encoded inside the media. No downstream element can
97         ask for a different format, the only way that the source pad will
98         renegotiate is when the element decides to change the caps itself.
99       </para>
100       <para>
101         Elements that could implement fixed caps (on their source pads) are,
102         in general, all elements that are not renegotiable. Examples include:
103       </para>
104       <itemizedlist>
105         <listitem>
106           <para>
107             A typefinder, since the type found is part of the actual data stream
108             and can thus not be re-negotiated. The typefinder will look at the
109             stream of bytes, figure out the type, send a CAPS event with the
110             caps and then push buffers of the type.
111           </para>
112         </listitem>
113         <listitem>
114           <para>
115             Pretty much all demuxers, since the contained elementary data
116             streams are defined in the file headers, and thus not
117             renegotiable.
118           </para>
119         </listitem>
120         <listitem>
121           <para>
122             Some decoders, where the format is embedded in the data stream
123             and not part of the peercaps <emphasis>and</emphasis> where the
124             decoder itself is not reconfigurable, too.
125           </para>
126         </listitem>
127         <listitem>
128           <para>
129             Some sources that produce a fixed format.
130           </para>
131         </listitem>
132       </itemizedlist>
133       <para>
134         <function>gst_pad_use_fixed_caps()</function> is used on the source
135         pad with fixed caps. As long as the pad is not negotiated, the default
136         CAPS query will return the caps presented in the padtemplate. As soon
137         as the pad is negotiated, the CAPS query will return the negotiated
138         caps (and nothing else). These are the relevant code snippets for fixed
139         caps source pads.
140       </para>
141       <programlisting>
142 <![CDATA[
143 [..]
144   pad = gst_pad_new_from_static_template (..);
145   gst_pad_use_fixed_caps (pad);
146 [..]
147 ]]>
148       </programlisting>
149       <para>
150         The fixed caps can then be set on the pad by calling
151         <function>gst_pad_set_caps ()</function>.
152       </para>
153       <programlisting>
154 <![CDATA[
155 [..]
156     caps = gst_caps_new_simple ("audio/x-raw",
157         "format", G_TYPE_STRING, GST_AUDIO_NE(F32),
158         "rate", G_TYPE_INT, <samplerate>,
159         "channels", G_TYPE_INT, <num-channels>, NULL);
160     if (!gst_pad_set_caps (pad, caps)) {
161       GST_ELEMENT_ERROR (element, CORE, NEGOTIATION, (NULL),
162           ("Some debug information here"));
163       return GST_FLOW_ERROR;
164     }
165 [..]
166 ]]>
167       </programlisting>
168       <para>
169         These types of elements also don't have a relation between the input
170         format and the output format, the input caps simply don't contain the
171         information needed to produce the output caps.
172       </para>
173       <para>
174         All other elements that need to be configured for the format should
175         implement full caps negotiation, which will be explained in the next
176         few sections.
177       </para>
178     </sect2>
179
180     <sect2 id="section-nego-transform">
181       <title>Transform negotiation</title>
182       <para>
183         In this negotiation technique, there is a fixed transform between
184         the element input caps and the output caps. This transformation
185         could be parameterized by element properties but not by the
186         content of the stream (see <xref linkend="section-nego-fixed"/>
187         for that use-case).
188       </para>
189       <para>
190         The caps that the element can accept depend on the (fixed
191         transformation) downstream caps. The caps that the element can
192         produce depend on the (fixed transformation of) the upstream
193         caps.
194       </para>
195       <para>
196         This type of element can usually set caps on its source pad from
197         the <function>_event()</function> function on the sink pad when
198         it received the CAPS event. This means that the caps transform
199         function transforms a fixed caps into another fixed caps.
200         Examples of elements include:
201       </para>
202       <itemizedlist>
203         <listitem>
204           <para>
205             Videobox. It adds configurable border around a video frame
206             depending on object properties.
207           </para>
208         </listitem>
209         <listitem>
210           <para>
211             Identity elements. All elements that don't change the format
212             of the data, only the content. Video and audio effects are an
213             example. Other examples include elements that inspect the
214             stream.
215           </para>
216         </listitem>
217         <listitem>
218           <para>
219             Some decoders and encoders, where the output format is defined
220             by input format, like mulawdec and mulawenc. These decoders
221             usually have no headers that define the content of the stream.
222             They are usually more like conversion elements.
223           </para>
224         </listitem>
225       </itemizedlist>
226       <para>
227         Below is an example of a negotiation steps of a typical transform 
228         element. In the sink pad CAPS event handler, we compute the caps
229         for the source pad and set those.
230       </para>
231       <programlisting>
232 <![CDATA[
233   [...]
234
235 static gboolean
236 gst_my_filter_setcaps (GstMyFilter *filter,
237                        GstCaps *caps)
238 {
239   GstStructure *structure;
240   int rate, channels;
241   gboolean ret;
242   GstCaps *outcaps;
243
244   structure = gst_caps_get_structure (caps, 0);
245   ret = gst_structure_get_int (structure, "rate", &rate);
246   ret = ret && gst_structure_get_int (structure, "channels", &channels);
247   if (!ret)
248     return FALSE;
249
250   outcaps = gst_caps_new_simple ("audio/x-raw",
251       "format", G_TYPE_STRING, GST_AUDIO_NE(S16),
252       "rate", G_TYPE_INT, samplerate,
253       "channels", G_TYPE_INT, channels, NULL);
254   ret = gst_pad_set_caps (filter->srcpad, outcaps);
255   gst_caps_unref (outcaps);
256
257   return ret;
258 }
259
260 static gboolean
261 gst_my_filter_sink_event (GstPad    *pad,
262                           GstObject *parent,
263                           GstEvent  *event)
264 {
265   gboolean ret;
266   GstMyFilter *filter = GST_MY_FILTER (parent);
267
268   switch (GST_EVENT_TYPE (event)) {
269     case GST_EVENT_CAPS:
270     {
271       GstCaps *caps;
272
273       gst_event_parse_caps (event, &caps);
274       ret = gst_my_filter_setcaps (filter, caps);
275       break;
276     }
277     default:
278       ret = gst_pad_event_default (pad, parent, event);
279       break;
280   }
281   return ret;
282 }
283
284   [...]
285 ]]>
286       </programlisting>
287     </sect2>
288
289     <sect2 id="section-nego-dynamic">
290       <title>Dynamic negotiation</title>
291       <para>
292         A last negotiation method is the most complex and powerful dynamic
293         negotiation.
294       </para>
295       <para>
296         Like with the transform negotiation in 
297         <xref linkend="section-nego-transform"/>, dynamic negotiation will
298         perform a transformation on the downstream/upstream caps. Unlike the
299         transform negotiation, this transform will convert fixed caps to
300         unfixed caps. This means that the sink pad input caps can be converted
301         into unfixed (multiple) formats. The source pad will have to choose a
302         format from all the possibilities. It would usually like to choose a
303         format that requires the least amount of effort to produce but it does
304         not have to be. The selection of the format should also depend on the
305         caps that can be accepted downstream (see a QUERY_CAPS function in
306         <xref linkend="section-nego-getcaps"/>).
307       </para>
308       <para>
309         A typical flow goes like this:
310       </para>
311       <itemizedlist>
312         <listitem>
313           <para>
314             Caps are received on the sink pad of the element.
315           </para>
316         </listitem>
317         <listitem>
318           <para>
319             If the element prefers to operate in passthrough mode, check
320             if downstream accepts the caps with the ACCEPT_CAPS query. If it
321             does, we can complete negotiation and we can operate in
322             passthrough mode.
323           </para>
324         </listitem>
325         <listitem>
326           <para>
327             Calculate the possible caps for the source pad.
328           </para>
329         </listitem>
330         <listitem>
331           <para>
332             Query the downstream peer pad for the list of possible
333             caps.
334           </para>
335         </listitem>
336         <listitem>
337           <para>
338             Select from the downstream list the first caps that you can
339             transform to and set this as the output caps. You might have to
340             fixate the caps to some reasonable defaults to construct
341             fixed caps.
342           </para>
343         </listitem>
344       </itemizedlist>
345       <para>
346         Examples of this type of elements include:
347       </para>
348       <itemizedlist>
349         <listitem>
350           <para>
351             Converter elements such as videoconvert, audioconvert, audioresample,
352             videoscale, ...
353           </para>
354         </listitem>
355         <listitem>
356           <para>
357             Source elements such as audiotestsrc, videotestsrc, v4l2src,
358             pulsesrc, ...
359           </para>
360         </listitem>
361       </itemizedlist>
362       <para>
363         Let's look at the example of an element that can convert between
364         samplerates, so where input and output samplerate don't have to be
365         the same:
366       </para>
367       <programlisting>
368 <![CDATA[
369 static gboolean
370 gst_my_filter_setcaps (GstMyFilter *filter,
371                        GstCaps *caps)
372 {
373   if (gst_pad_set_caps (filter->sinkpad, caps)) {
374     filter->passthrough = TRUE;
375   } else {
376     GstCaps *othercaps, *newcaps;
377     GstStructure *s = gst_caps_get_structure (caps, 0), *others;
378
379     /* no passthrough, setup internal conversion */
380     gst_structure_get_int (s, "channels", &filter->channels);
381     othercaps = gst_pad_get_allowed_caps (filter->srcpad);
382     others = gst_caps_get_structure (othercaps, 0);
383     gst_structure_set (others,
384       "channels", G_TYPE_INT, filter->channels, NULL);
385
386     /* now, the samplerate value can optionally have multiple values, so
387      * we "fixate" it, which means that one fixed value is chosen */
388     newcaps = gst_caps_copy_nth (othercaps, 0);
389     gst_caps_unref (othercaps);
390     gst_pad_fixate_caps (filter->srcpad, newcaps);
391     if (!gst_pad_set_caps (filter->srcpad, newcaps))
392       return FALSE;
393
394     /* we are now set up, configure internally */
395     filter->passthrough = FALSE;
396     gst_structure_get_int (s, "rate", &filter->from_samplerate);
397     others = gst_caps_get_structure (newcaps, 0);
398     gst_structure_get_int (others, "rate", &filter->to_samplerate);
399   }
400
401   return TRUE;
402 }
403
404 static gboolean
405 gst_my_filter_sink_event (GstPad    *pad,
406                           GstObject *parent,
407                           GstEvent  *event)
408 {
409   gboolean ret;
410   GstMyFilter *filter = GST_MY_FILTER (parent);
411
412   switch (GST_EVENT_TYPE (event)) {
413     case GST_EVENT_CAPS:
414     {
415       GstCaps *caps;
416
417       gst_event_parse_caps (event, &caps);
418       ret = gst_my_filter_setcaps (filter, caps);
419       break;
420     }
421     default:
422       ret = gst_pad_event_default (pad, parent, event);
423       break;
424   }
425   return ret;
426 }
427
428 static GstFlowReturn
429 gst_my_filter_chain (GstPad    *pad,
430                      GstObject *parent,
431                      GstBuffer *buf)
432 {
433   GstMyFilter *filter = GST_MY_FILTER (parent);
434   GstBuffer *out;
435
436   /* push on if in passthrough mode */
437   if (filter->passthrough)
438     return gst_pad_push (filter->srcpad, buf);
439
440   /* convert, push */
441   out = gst_my_filter_convert (filter, buf);
442   gst_buffer_unref (buf);
443
444   return gst_pad_push (filter->srcpad, out);
445 }
446 ]]>
447       </programlisting>
448     </sect2>
449   </sect1>
450
451   <sect1 id="section-nego-upstream" xreflabel="Upstream caps (re)negotiation">
452     <title>Upstream caps (re)negotiation</title>
453     <para>
454       Upstream negotiation's primary use is to renegotiate (part of) an
455       already-negotiated pipeline to a new format. Some practical examples
456       include to select a different video size because the size of the video
457       window changed, and the video output itself is not capable of rescaling,
458       or because the audio channel configuration changed.
459     </para>
460     <para>
461       Upstream caps renegotiation is requested by sending a GST_EVENT_RECONFIGURE
462       event upstream. The idea is that it will instruct the upstream element
463       to reconfigure its caps by doing a new query for the allowed caps and then
464       choosing a new caps. The element that sends out the RECONFIGURE event
465       would influence the selection of the new caps by returning the new
466       prefered caps from its GST_QUERY_CAPS query function. The RECONFIGURE
467       event will set the GST_PAD_FLAG_NEED_RECONFIGURE on all pads that it
468       travels over.
469     </para>
470     <para>
471       It is important to note here that different elements actually have
472       different responsibilities here:
473     </para>
474     <itemizedlist>
475       <listitem>
476         <para>
477           Elements that want to propose a new format upstream need to first
478           check if the new caps are acceptable upstream with an ACCEPT_CAPS
479           query. Then they would send a RECONFIGURE event and be prepared to
480           answer the CAPS query with the new prefered format. It should be
481           noted that when there is no upstream element that can (or wants)
482           to renegotiate, the element needs to deal with the currently
483           configured format.
484         </para>
485       </listitem>
486       <listitem>
487         <para>
488           Elements that operate in transform negotiation according to
489           <xref linkend="section-nego-transform"/> pass the RECONFIGURE
490           event upstream. Because these elements simply do a fixed transform
491           based on the upstream caps, they need to send the event upstream
492           so that it can select a new format.
493         </para>
494       </listitem>
495       <listitem>
496         <para>
497           Elements that operate in fixed negotiation 
498           (<xref linkend="section-nego-fixed"/>) drop the RECONFIGURE event.
499           These elements can't reconfigure and their output caps don't depend
500           on the upstream caps so the event can be dropped.
501         </para>
502       </listitem>
503       <listitem>
504         <para>
505           Elements that can be reconfigured on the source pad (source pads
506           implementing dynamic negotiation in
507           <xref linkend="section-nego-dynamic"/>) should check its
508           NEED_RECONFIGURE flag with
509           <function>gst_pad_check_reconfigure ()</function> and it should
510           start renegotiation when the function returns TRUE.
511         </para>
512       </listitem>
513     </itemizedlist>
514   </sect1>
515
516   <sect1 id="section-nego-getcaps" xreflabel="Implementing a CAPS query function">
517     <title>Implementing a CAPS query function</title>
518     <para>
519       A <function>_query ()</function>-function with the GST_QUERY_CAPS query
520       type is called when a peer element would like to know which formats
521       this pad supports, and in what order of preference. The return value
522       should be all formats that this elements supports, taking into account
523       limitations of peer elements further downstream or upstream, sorted by
524       order of preference, highest preference first.
525     </para>
526     <para>
527     </para>
528     <programlisting>
529 <![CDATA[
530 static gboolean
531 gst_my_filter_query (GstPad *pad, GstObject * parent, GstQuery * query)
532 {
533   gboolean ret;
534   GstMyFilter *filter = GST_MY_FILTER (parent);
535
536   switch (GST_QUERY_TYPE (query)) {
537     case GST_QUERY_CAPS
538     {
539       GstPad *otherpad;
540       GstCaps *temp, *caps, *filt, *tcaps;
541       gint i;
542
543       otherpad = (pad == filter->srcpad) ? filter->sinkpad :
544                                            filter->srcpad;
545       caps = gst_pad_get_allowed_caps (otherpad);
546
547       gst_query_parse_caps (query, &filt);
548
549       /* We support *any* samplerate, indifferent from the samplerate
550        * supported by the linked elements on both sides. */
551       for (i = 0; i < gst_caps_get_size (caps); i++) {
552         GstStructure *structure = gst_caps_get_structure (caps, i);
553
554         gst_structure_remove_field (structure, "rate");
555       }
556
557       /* make sure we only return results that intersect our
558        * padtemplate */
559       tcaps = gst_pad_get_pad_template_caps (pad);
560       if (tcaps) {
561         temp = gst_caps_intersect (caps, tcaps);
562         gst_caps_unref (caps);
563         gst_caps_unref (tcaps);
564         caps = temp;
565       }
566       /* filter against the query filter when needed */
567       if (filt) {
568         temp = gst_caps_intersect (caps, filt);
569         gst_caps_unref (caps);
570         caps = temp;
571       }
572       gst_query_set_caps_result (query, caps);
573       gst_caps_unref (caps);
574       ret = TRUE;
575       break;
576     }
577     default:
578       ret = gst_pad_query_default (pad, parent, query);
579       break;
580   }
581   return ret;
582 }
583 ]]>
584     </programlisting>
585   </sect1>
586
587   <sect1 id="section-nego-pullmode">
588     <title>Pull-mode Caps negotiation</title>
589     <para>
590       WRITEME, the mechanism of pull-mode negotiation is not yet fully
591       understood.
592     </para>
593
594     <para>
595       Using all the knowledge you've acquired by reading this chapter, you
596       should be able to write an element that does correct caps negotiation.
597       If in doubt, look at other elements of the same type in our git
598       repository to get an idea of how they do what you want to do.
599     </para>
600   </sect1>
601 </chapter>