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