Fix `transfer` gobject-introspection annotation typos
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / gst-libs / gst / rtp / gstrtpbasepayload.c
1 /* GStreamer
2  * Copyright (C) <2005> Wim Taymans <wim@fluendo.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more
13  */
14
15 /**
16  * SECTION:gstrtpbasepayload
17  * @title: GstRTPBasePayload
18  * @short_description: Base class for RTP payloader
19  *
20  * Provides a base class for RTP payloaders
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <string.h>
28
29 #include <gst/rtp/gstrtpbuffer.h>
30
31 #include "gstrtpbasepayload.h"
32 #include "gstrtpmeta.h"
33 #include "gstrtphdrext.h"
34
35 GST_DEBUG_CATEGORY_STATIC (rtpbasepayload_debug);
36 #define GST_CAT_DEFAULT (rtpbasepayload_debug)
37
38 struct _GstRTPBasePayloadPrivate
39 {
40   gboolean ts_offset_random;
41   gboolean seqnum_offset_random;
42   gboolean ssrc_random;
43   guint16 next_seqnum;
44   gboolean perfect_rtptime;
45   gint notified_first_timestamp;
46
47   gboolean pt_set;
48
49   gboolean source_info;
50   GstBuffer *input_meta_buffer;
51
52   guint64 base_offset;
53   gint64 base_rtime;
54   guint64 base_rtime_hz;
55   guint64 running_time;
56   gboolean scale_rtptime;
57   gboolean auto_hdr_ext;
58
59   gint64 prop_max_ptime;
60   gint64 caps_max_ptime;
61
62   gboolean onvif_no_rate_control;
63
64   gboolean negotiated;
65
66   gboolean delay_segment;
67   GstEvent *pending_segment;
68
69   GstCaps *subclass_srccaps;
70   GstCaps *sinkcaps;
71
72   /* array of GstRTPHeaderExtension's * */
73   GPtrArray *header_exts;
74 };
75
76 /* RTPBasePayload signals and args */
77 enum
78 {
79   SIGNAL_0,
80   SIGNAL_REQUEST_EXTENSION,
81   SIGNAL_ADD_EXTENSION,
82   SIGNAL_CLEAR_EXTENSIONS,
83   LAST_SIGNAL
84 };
85
86 static guint gst_rtp_base_payload_signals[LAST_SIGNAL] = { 0 };
87
88 /* FIXME 0.11, a better default is the Ethernet MTU of
89  * 1500 - sizeof(headers) as pointed out by marcelm in IRC:
90  * So an Ethernet MTU of 1500, minus 60 for the max IP, minus 8 for UDP, gives
91  * 1432 bytes or so.  And that should be adjusted downward further for other
92  * encapsulations like PPPoE, so 1400 at most.
93  */
94 #define DEFAULT_MTU                     1400
95 #define DEFAULT_PT                      96
96 #define DEFAULT_SSRC                    -1
97 #define DEFAULT_TIMESTAMP_OFFSET        -1
98 #define DEFAULT_SEQNUM_OFFSET           -1
99 #define DEFAULT_MAX_PTIME               -1
100 #define DEFAULT_MIN_PTIME               0
101 #define DEFAULT_PERFECT_RTPTIME         TRUE
102 #define DEFAULT_PTIME_MULTIPLE          0
103 #define DEFAULT_RUNNING_TIME            GST_CLOCK_TIME_NONE
104 #define DEFAULT_SOURCE_INFO             FALSE
105 #define DEFAULT_ONVIF_NO_RATE_CONTROL   FALSE
106 #define DEFAULT_SCALE_RTPTIME           TRUE
107 #define DEFAULT_AUTO_HEADER_EXTENSION   TRUE
108
109 #define RTP_HEADER_EXT_ONE_BYTE_MAX_SIZE 16
110 #define RTP_HEADER_EXT_TWO_BYTE_MAX_SIZE 256
111 #define RTP_HEADER_EXT_ONE_BYTE_MAX_ID 14
112 #define RTP_HEADER_EXT_TWO_BYTE_MAX_ID 255
113
114 enum
115 {
116   PROP_0,
117   PROP_MTU,
118   PROP_PT,
119   PROP_SSRC,
120   PROP_TIMESTAMP_OFFSET,
121   PROP_SEQNUM_OFFSET,
122   PROP_MAX_PTIME,
123   PROP_MIN_PTIME,
124   PROP_TIMESTAMP,
125   PROP_SEQNUM,
126   PROP_PERFECT_RTPTIME,
127   PROP_PTIME_MULTIPLE,
128   PROP_STATS,
129   PROP_SOURCE_INFO,
130   PROP_ONVIF_NO_RATE_CONTROL,
131   PROP_SCALE_RTPTIME,
132   PROP_AUTO_HEADER_EXTENSION,
133   PROP_LAST
134 };
135
136 static void gst_rtp_base_payload_class_init (GstRTPBasePayloadClass * klass);
137 static void gst_rtp_base_payload_init (GstRTPBasePayload * rtpbasepayload,
138     gpointer g_class);
139 static void gst_rtp_base_payload_finalize (GObject * object);
140
141 static GstCaps *gst_rtp_base_payload_getcaps_default (GstRTPBasePayload *
142     rtpbasepayload, GstPad * pad, GstCaps * filter);
143
144 static gboolean gst_rtp_base_payload_sink_event_default (GstRTPBasePayload *
145     rtpbasepayload, GstEvent * event);
146 static gboolean gst_rtp_base_payload_sink_event (GstPad * pad,
147     GstObject * parent, GstEvent * event);
148 static gboolean gst_rtp_base_payload_src_event_default (GstRTPBasePayload *
149     rtpbasepayload, GstEvent * event);
150 static gboolean gst_rtp_base_payload_src_event (GstPad * pad,
151     GstObject * parent, GstEvent * event);
152 static gboolean gst_rtp_base_payload_query_default (GstRTPBasePayload *
153     rtpbasepayload, GstPad * pad, GstQuery * query);
154 static gboolean gst_rtp_base_payload_query (GstPad * pad, GstObject * parent,
155     GstQuery * query);
156 static GstFlowReturn gst_rtp_base_payload_chain (GstPad * pad,
157     GstObject * parent, GstBuffer * buffer);
158
159 static void gst_rtp_base_payload_set_property (GObject * object, guint prop_id,
160     const GValue * value, GParamSpec * pspec);
161 static void gst_rtp_base_payload_get_property (GObject * object, guint prop_id,
162     GValue * value, GParamSpec * pspec);
163
164 static GstStateChangeReturn gst_rtp_base_payload_change_state (GstElement *
165     element, GstStateChange transition);
166
167 static gboolean gst_rtp_base_payload_negotiate (GstRTPBasePayload * payload);
168
169 static void gst_rtp_base_payload_add_extension (GstRTPBasePayload * payload,
170     GstRTPHeaderExtension * ext);
171 static void gst_rtp_base_payload_clear_extensions (GstRTPBasePayload * payload);
172
173 static GstElementClass *parent_class = NULL;
174 static gint private_offset = 0;
175
176 GType
177 gst_rtp_base_payload_get_type (void)
178 {
179   static GType rtpbasepayload_type = 0;
180
181   if (g_once_init_enter ((gsize *) & rtpbasepayload_type)) {
182     static const GTypeInfo rtpbasepayload_info = {
183       sizeof (GstRTPBasePayloadClass),
184       NULL,
185       NULL,
186       (GClassInitFunc) gst_rtp_base_payload_class_init,
187       NULL,
188       NULL,
189       sizeof (GstRTPBasePayload),
190       0,
191       (GInstanceInitFunc) gst_rtp_base_payload_init,
192     };
193     GType _type;
194
195     _type = g_type_register_static (GST_TYPE_ELEMENT, "GstRTPBasePayload",
196         &rtpbasepayload_info, G_TYPE_FLAG_ABSTRACT);
197
198     private_offset =
199         g_type_add_instance_private (_type, sizeof (GstRTPBasePayloadPrivate));
200
201     g_once_init_leave ((gsize *) & rtpbasepayload_type, _type);
202   }
203   return rtpbasepayload_type;
204 }
205
206 static inline GstRTPBasePayloadPrivate *
207 gst_rtp_base_payload_get_instance_private (GstRTPBasePayload * self)
208 {
209   return (G_STRUCT_MEMBER_P (self, private_offset));
210 }
211
212 static GstRTPHeaderExtension *
213 gst_rtp_base_payload_request_extension_default (GstRTPBasePayload * payload,
214     guint ext_id, const gchar * uri)
215 {
216   GstRTPHeaderExtension *ext = NULL;
217
218   if (!payload->priv->auto_hdr_ext)
219     return NULL;
220
221   ext = gst_rtp_header_extension_create_from_uri (uri);
222   if (ext) {
223     GST_DEBUG_OBJECT (payload,
224         "Automatically enabled extension %s for uri \'%s\'",
225         GST_ELEMENT_NAME (ext), uri);
226
227     gst_rtp_header_extension_set_id (ext, ext_id);
228   } else {
229     GST_DEBUG_OBJECT (payload,
230         "Didn't find any extension implementing uri \'%s\'", uri);
231   }
232
233   return ext;
234 }
235
236 static gboolean
237 extension_accumulator (GSignalInvocationHint * ihint,
238     GValue * return_accu, const GValue * handler_return, gpointer data)
239 {
240   gpointer ext;
241
242   /* Call default handler if user callback didn't create the extension */
243   ext = g_value_get_object (handler_return);
244   if (!ext)
245     return TRUE;
246
247   g_value_set_object (return_accu, ext);
248   return FALSE;
249 }
250
251 static void
252 gst_rtp_base_payload_class_init (GstRTPBasePayloadClass * klass)
253 {
254   GObjectClass *gobject_class;
255   GstElementClass *gstelement_class;
256
257   gobject_class = (GObjectClass *) klass;
258   gstelement_class = (GstElementClass *) klass;
259
260   if (private_offset != 0)
261     g_type_class_adjust_private_offset (klass, &private_offset);
262
263   parent_class = g_type_class_peek_parent (klass);
264
265   gobject_class->finalize = gst_rtp_base_payload_finalize;
266
267   gobject_class->set_property = gst_rtp_base_payload_set_property;
268   gobject_class->get_property = gst_rtp_base_payload_get_property;
269
270   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MTU,
271       g_param_spec_uint ("mtu", "MTU",
272           "Maximum size of one packet",
273           28, G_MAXUINT, DEFAULT_MTU,
274           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
275   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PT,
276       g_param_spec_uint ("pt", "payload type",
277           "The payload type of the packets", 0, 0x7f, DEFAULT_PT,
278           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
279   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SSRC,
280       g_param_spec_uint ("ssrc", "SSRC",
281           "The SSRC of the packets (default == random)", 0, G_MAXUINT32,
282           DEFAULT_SSRC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
283   g_object_class_install_property (G_OBJECT_CLASS (klass),
284       PROP_TIMESTAMP_OFFSET, g_param_spec_uint ("timestamp-offset",
285           "Timestamp Offset",
286           "Offset to add to all outgoing timestamps (default = random)", 0,
287           G_MAXUINT32, DEFAULT_TIMESTAMP_OFFSET,
288           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
289   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SEQNUM_OFFSET,
290       g_param_spec_int ("seqnum-offset", "Sequence number Offset",
291           "Offset to add to all outgoing seqnum (-1 = random)", -1, G_MAXUINT16,
292           DEFAULT_SEQNUM_OFFSET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
293   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MAX_PTIME,
294       g_param_spec_int64 ("max-ptime", "Max packet time",
295           "Maximum duration of the packet data in ns (-1 = unlimited up to MTU)",
296           -1, G_MAXINT64, DEFAULT_MAX_PTIME,
297           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
298   /**
299    * GstRTPBasePayload:min-ptime:
300    *
301    * Minimum duration of the packet data in ns (can't go above MTU)
302    **/
303   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MIN_PTIME,
304       g_param_spec_int64 ("min-ptime", "Min packet time",
305           "Minimum duration of the packet data in ns (can't go above MTU)",
306           0, G_MAXINT64, DEFAULT_MIN_PTIME,
307           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
308
309   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TIMESTAMP,
310       g_param_spec_uint ("timestamp", "Timestamp",
311           "The RTP timestamp of the last processed packet",
312           0, G_MAXUINT32, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
313   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SEQNUM,
314       g_param_spec_uint ("seqnum", "Sequence number",
315           "The RTP sequence number of the last processed packet",
316           0, G_MAXUINT16, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
317
318   /**
319    * GstRTPBasePayload:perfect-rtptime:
320    *
321    * Try to use the offset fields to generate perfect RTP timestamps. When this
322    * option is disabled, RTP timestamps are generated from GST_BUFFER_PTS of
323    * each payloaded buffer. The PTSes of buffers may not necessarily increment
324    * with the amount of data in each input buffer, consider e.g. the case where
325    * the buffer arrives from a network which means that the PTS is unrelated to
326    * the amount of data. Because the RTP timestamps are generated from
327    * GST_BUFFER_PTS this can result in RTP timestamps that also don't increment
328    * with the amount of data in the payloaded packet. To circumvent this it is
329    * possible to set the perfect rtptime option enabled. When this option is
330    * enabled the payloader will increment the RTP timestamps based on
331    * GST_BUFFER_OFFSET which relates to the amount of data in each packet
332    * rather than the GST_BUFFER_PTS of each buffer and therefore the RTP
333    * timestamps will more closely correlate with the amount of data in each
334    * buffer. Currently GstRTPBasePayload is limited to handling perfect RTP
335    * timestamps for audio streams.
336    */
337   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PERFECT_RTPTIME,
338       g_param_spec_boolean ("perfect-rtptime", "Perfect RTP Time",
339           "Generate perfect RTP timestamps when possible",
340           DEFAULT_PERFECT_RTPTIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341   /**
342    * GstRTPBasePayload:ptime-multiple:
343    *
344    * Force buffers to be multiples of this duration in ns (0 disables)
345    **/
346   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PTIME_MULTIPLE,
347       g_param_spec_int64 ("ptime-multiple", "Packet time multiple",
348           "Force buffers to be multiples of this duration in ns (0 disables)",
349           0, G_MAXINT64, DEFAULT_PTIME_MULTIPLE,
350           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
351
352   /**
353    * GstRTPBasePayload:stats:
354    *
355    * Various payloader statistics retrieved atomically (and are therefore
356    * synchroized with each other), these can be used e.g. to generate an
357    * RTP-Info header. This property return a GstStructure named
358    * application/x-rtp-payload-stats containing the following fields relating to
359    * the last processed buffer and current state of the stream being payloaded:
360    *
361    *   * `clock-rate` :#G_TYPE_UINT, clock-rate of the stream
362    *   * `running-time` :#G_TYPE_UINT64, running time
363    *   * `seqnum` :#G_TYPE_UINT, sequence number, same as #GstRTPBasePayload:seqnum
364    *   * `timestamp` :#G_TYPE_UINT, RTP timestamp, same as #GstRTPBasePayload:timestamp
365    *   * `ssrc` :#G_TYPE_UINT, The SSRC in use
366    *   * `pt` :#G_TYPE_UINT, The Payload type in use, same as #GstRTPBasePayload:pt
367    *   * `seqnum-offset` :#G_TYPE_UINT, The current offset added to the seqnum
368    *   * `timestamp-offset` :#G_TYPE_UINT, The current offset added to the timestamp
369    **/
370   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_STATS,
371       g_param_spec_boxed ("stats", "Statistics", "Various statistics",
372           GST_TYPE_STRUCTURE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
373
374   /**
375    * GstRTPBasePayload:source-info:
376    *
377    * Enable writing the CSRC field in allocated RTP header based on RTP source
378    * information found in the input buffer's #GstRTPSourceMeta.
379    *
380    * Since: 1.16
381    **/
382   g_object_class_install_property (gobject_class, PROP_SOURCE_INFO,
383       g_param_spec_boolean ("source-info", "RTP source information",
384           "Write CSRC based on buffer meta RTP source information",
385           DEFAULT_SOURCE_INFO, G_PARAM_READWRITE));
386
387   /**
388    * GstRTPBasePayload:onvif-no-rate-control:
389    *
390    * Make the payloader timestamp packets according to the Rate-Control=no
391    * behaviour specified in the ONVIF replay spec.
392    *
393    * Since: 1.16
394    */
395   g_object_class_install_property (G_OBJECT_CLASS (klass),
396       PROP_ONVIF_NO_RATE_CONTROL, g_param_spec_boolean ("onvif-no-rate-control",
397           "ONVIF no rate control",
398           "Enable ONVIF Rate-Control=no timestamping mode",
399           DEFAULT_ONVIF_NO_RATE_CONTROL,
400           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
401
402   /**
403    * GstRTPBasePayload:scale-rtptime:
404    *
405    * Make the RTP packets' timestamps be scaled with the segment's rate
406    * (corresponding to RTSP speed parameter). Disabling this property means
407    * the timestamps will not be affected by the set delivery speed (RTSP speed).
408    * 
409    * Example: A server wants to allow streaming a recorded video in double 
410    * speed but still have the timestamps correspond to the position in the 
411    * video. This is achieved by the client setting RTSP Speed to 2 while the 
412    * server has this property disabled.
413    * 
414    * Since: 1.18
415    */
416   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SCALE_RTPTIME,
417       g_param_spec_boolean ("scale-rtptime", "Scale RTP time",
418           "Whether the RTP timestamp should be scaled with the rate (speed)",
419           DEFAULT_SCALE_RTPTIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
420
421   /**
422    * GstRTPBasePayload:auto-header-extension:
423    *
424    * If enabled, the payloader will automatically try to enable all the
425    * RTP header extensions provided in the src caps, saving the application
426    * the need to handle these extensions manually using the
427    * GstRTPBasePayload::request-extension: signal.
428    *
429    * Since: 1.20
430    */
431   g_object_class_install_property (G_OBJECT_CLASS (klass),
432       PROP_AUTO_HEADER_EXTENSION, g_param_spec_boolean ("auto-header-extension",
433           "Automatic RTP header extension",
434           "Whether RTP header extensions should be automatically enabled, if an implementation is available",
435           DEFAULT_AUTO_HEADER_EXTENSION,
436           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
437
438   /**
439    * GstRTPBasePayload::add-extension:
440    * @object: the #GstRTPBasePayload
441    * @ext: (transfer full): the #GstRTPHeaderExtension
442    *
443    * Add @ext as an extension for writing part of an RTP header extension onto
444    * outgoing RTP packets.
445    *
446    * Since: 1.20
447    */
448   gst_rtp_base_payload_signals[SIGNAL_ADD_EXTENSION] =
449       g_signal_new_class_handler ("add-extension", G_TYPE_FROM_CLASS (klass),
450       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
451       G_CALLBACK (gst_rtp_base_payload_add_extension), NULL, NULL, NULL,
452       G_TYPE_NONE, 1, GST_TYPE_RTP_HEADER_EXTENSION);
453
454   /**
455    * GstRTPBasePayload::request-extension:
456    * @object: the #GstRTPBasePayload
457    * @ext_id: the extension id being requested
458    * @ext_uri: the extension URI being requested
459    *
460    * The returned @ext must be configured with the correct @ext_id and with the
461    * necessary attributes as required by the extension implementation.
462    *
463    * Returns: (transfer full): the #GstRTPHeaderExtension for @ext_id, or %NULL
464    *
465    * Since: 1.20
466    */
467   gst_rtp_base_payload_signals[SIGNAL_REQUEST_EXTENSION] =
468       g_signal_new_class_handler ("request-extension",
469       G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
470       G_CALLBACK (gst_rtp_base_payload_request_extension_default),
471       extension_accumulator, NULL, NULL,
472       GST_TYPE_RTP_HEADER_EXTENSION, 2, G_TYPE_UINT, G_TYPE_STRING);
473
474   /**
475    * GstRTPBasePayload::clear-extensions:
476    * @object: the #GstRTPBasePayload
477    *
478    * Clear all RTP header extensions used by this payloader.
479    *
480    * Since: 1.20
481    */
482   gst_rtp_base_payload_signals[SIGNAL_CLEAR_EXTENSIONS] =
483       g_signal_new_class_handler ("clear-extensions", G_TYPE_FROM_CLASS (klass),
484       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
485       G_CALLBACK (gst_rtp_base_payload_clear_extensions), NULL, NULL, NULL,
486       G_TYPE_NONE, 0);
487
488   gstelement_class->change_state = gst_rtp_base_payload_change_state;
489
490   klass->get_caps = gst_rtp_base_payload_getcaps_default;
491   klass->sink_event = gst_rtp_base_payload_sink_event_default;
492   klass->src_event = gst_rtp_base_payload_src_event_default;
493   klass->query = gst_rtp_base_payload_query_default;
494
495   GST_DEBUG_CATEGORY_INIT (rtpbasepayload_debug, "rtpbasepayload", 0,
496       "Base class for RTP Payloaders");
497 }
498
499 static void
500 gst_rtp_base_payload_init (GstRTPBasePayload * rtpbasepayload, gpointer g_class)
501 {
502   GstPadTemplate *templ;
503   GstRTPBasePayloadPrivate *priv;
504
505   rtpbasepayload->priv = priv =
506       gst_rtp_base_payload_get_instance_private (rtpbasepayload);
507
508   templ =
509       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "src");
510   g_return_if_fail (templ != NULL);
511
512   rtpbasepayload->srcpad = gst_pad_new_from_template (templ, "src");
513   gst_pad_set_event_function (rtpbasepayload->srcpad,
514       gst_rtp_base_payload_src_event);
515   gst_element_add_pad (GST_ELEMENT (rtpbasepayload), rtpbasepayload->srcpad);
516
517   templ =
518       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "sink");
519   g_return_if_fail (templ != NULL);
520
521   rtpbasepayload->sinkpad = gst_pad_new_from_template (templ, "sink");
522   gst_pad_set_chain_function (rtpbasepayload->sinkpad,
523       gst_rtp_base_payload_chain);
524   gst_pad_set_event_function (rtpbasepayload->sinkpad,
525       gst_rtp_base_payload_sink_event);
526   gst_pad_set_query_function (rtpbasepayload->sinkpad,
527       gst_rtp_base_payload_query);
528   gst_element_add_pad (GST_ELEMENT (rtpbasepayload), rtpbasepayload->sinkpad);
529
530   rtpbasepayload->mtu = DEFAULT_MTU;
531   rtpbasepayload->pt = DEFAULT_PT;
532   rtpbasepayload->seqnum_offset = DEFAULT_SEQNUM_OFFSET;
533   rtpbasepayload->ssrc = DEFAULT_SSRC;
534   rtpbasepayload->ts_offset = DEFAULT_TIMESTAMP_OFFSET;
535   priv->running_time = DEFAULT_RUNNING_TIME;
536   priv->seqnum_offset_random = (rtpbasepayload->seqnum_offset == -1);
537   priv->ts_offset_random = (rtpbasepayload->ts_offset == -1);
538   priv->ssrc_random = (rtpbasepayload->ssrc == -1);
539   priv->pt_set = FALSE;
540   priv->source_info = DEFAULT_SOURCE_INFO;
541
542   rtpbasepayload->max_ptime = DEFAULT_MAX_PTIME;
543   rtpbasepayload->min_ptime = DEFAULT_MIN_PTIME;
544   rtpbasepayload->priv->perfect_rtptime = DEFAULT_PERFECT_RTPTIME;
545   rtpbasepayload->ptime_multiple = DEFAULT_PTIME_MULTIPLE;
546   rtpbasepayload->priv->base_offset = GST_BUFFER_OFFSET_NONE;
547   rtpbasepayload->priv->base_rtime_hz = GST_BUFFER_OFFSET_NONE;
548   rtpbasepayload->priv->onvif_no_rate_control = DEFAULT_ONVIF_NO_RATE_CONTROL;
549   rtpbasepayload->priv->scale_rtptime = DEFAULT_SCALE_RTPTIME;
550   rtpbasepayload->priv->auto_hdr_ext = DEFAULT_AUTO_HEADER_EXTENSION;
551
552   rtpbasepayload->media = NULL;
553   rtpbasepayload->encoding_name = NULL;
554
555   rtpbasepayload->clock_rate = 0;
556
557   rtpbasepayload->priv->caps_max_ptime = DEFAULT_MAX_PTIME;
558   rtpbasepayload->priv->prop_max_ptime = DEFAULT_MAX_PTIME;
559   rtpbasepayload->priv->header_exts =
560       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
561 }
562
563 static void
564 gst_rtp_base_payload_finalize (GObject * object)
565 {
566   GstRTPBasePayload *rtpbasepayload;
567
568   rtpbasepayload = GST_RTP_BASE_PAYLOAD (object);
569
570   g_free (rtpbasepayload->media);
571   rtpbasepayload->media = NULL;
572   g_free (rtpbasepayload->encoding_name);
573   rtpbasepayload->encoding_name = NULL;
574
575   gst_caps_replace (&rtpbasepayload->priv->subclass_srccaps, NULL);
576   gst_caps_replace (&rtpbasepayload->priv->sinkcaps, NULL);
577
578   g_ptr_array_unref (rtpbasepayload->priv->header_exts);
579   rtpbasepayload->priv->header_exts = NULL;
580
581   G_OBJECT_CLASS (parent_class)->finalize (object);
582 }
583
584 static GstCaps *
585 gst_rtp_base_payload_getcaps_default (GstRTPBasePayload * rtpbasepayload,
586     GstPad * pad, GstCaps * filter)
587 {
588   GstCaps *caps;
589
590   caps = GST_PAD_TEMPLATE_CAPS (GST_PAD_PAD_TEMPLATE (pad));
591   GST_DEBUG_OBJECT (pad,
592       "using pad template %p with caps %p %" GST_PTR_FORMAT,
593       GST_PAD_PAD_TEMPLATE (pad), caps, caps);
594
595   if (filter)
596     caps = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
597   else
598     caps = gst_caps_ref (caps);
599
600   return caps;
601 }
602
603 static gboolean
604 gst_rtp_base_payload_sink_event_default (GstRTPBasePayload * rtpbasepayload,
605     GstEvent * event)
606 {
607   GstObject *parent = GST_OBJECT_CAST (rtpbasepayload);
608   gboolean res = FALSE;
609
610   switch (GST_EVENT_TYPE (event)) {
611     case GST_EVENT_FLUSH_START:
612       res = gst_pad_event_default (rtpbasepayload->sinkpad, parent, event);
613       break;
614     case GST_EVENT_FLUSH_STOP:
615       res = gst_pad_event_default (rtpbasepayload->sinkpad, parent, event);
616       gst_segment_init (&rtpbasepayload->segment, GST_FORMAT_UNDEFINED);
617       gst_event_replace (&rtpbasepayload->priv->pending_segment, NULL);
618       break;
619     case GST_EVENT_CAPS:
620     {
621       GstRTPBasePayloadClass *rtpbasepayload_class;
622       GstCaps *caps;
623
624       gst_event_parse_caps (event, &caps);
625       GST_DEBUG_OBJECT (rtpbasepayload, "setting caps %" GST_PTR_FORMAT, caps);
626
627       gst_caps_replace (&rtpbasepayload->priv->sinkcaps, caps);
628
629       rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
630       if (rtpbasepayload_class->set_caps)
631         res = rtpbasepayload_class->set_caps (rtpbasepayload, caps);
632       else
633         res = gst_rtp_base_payload_negotiate (rtpbasepayload);
634
635       rtpbasepayload->priv->negotiated = res;
636
637       gst_event_unref (event);
638       break;
639     }
640     case GST_EVENT_SEGMENT:
641     {
642       GstSegment *segment;
643
644       segment = &rtpbasepayload->segment;
645       gst_event_copy_segment (event, segment);
646
647       rtpbasepayload->priv->base_offset = GST_BUFFER_OFFSET_NONE;
648
649       GST_DEBUG_OBJECT (rtpbasepayload,
650           "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
651       if (rtpbasepayload->priv->delay_segment) {
652         gst_event_replace (&rtpbasepayload->priv->pending_segment, event);
653         gst_event_unref (event);
654         res = TRUE;
655       } else {
656         res = gst_pad_event_default (rtpbasepayload->sinkpad, parent, event);
657       }
658       break;
659     }
660     case GST_EVENT_GAP:
661     {
662       if (G_UNLIKELY (rtpbasepayload->priv->pending_segment)) {
663         gst_pad_push_event (rtpbasepayload->srcpad,
664             rtpbasepayload->priv->pending_segment);
665         rtpbasepayload->priv->pending_segment = FALSE;
666         rtpbasepayload->priv->delay_segment = FALSE;
667       }
668       res = gst_pad_event_default (rtpbasepayload->sinkpad, parent, event);
669       break;
670     }
671     default:
672       res = gst_pad_event_default (rtpbasepayload->sinkpad, parent, event);
673       break;
674   }
675   return res;
676 }
677
678 static gboolean
679 gst_rtp_base_payload_sink_event (GstPad * pad, GstObject * parent,
680     GstEvent * event)
681 {
682   GstRTPBasePayload *rtpbasepayload;
683   GstRTPBasePayloadClass *rtpbasepayload_class;
684   gboolean res = FALSE;
685
686   rtpbasepayload = GST_RTP_BASE_PAYLOAD (parent);
687   rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
688
689   if (rtpbasepayload_class->sink_event)
690     res = rtpbasepayload_class->sink_event (rtpbasepayload, event);
691   else
692     gst_event_unref (event);
693
694   return res;
695 }
696
697 static gboolean
698 gst_rtp_base_payload_src_event_default (GstRTPBasePayload * rtpbasepayload,
699     GstEvent * event)
700 {
701   GstObject *parent = GST_OBJECT_CAST (rtpbasepayload);
702   gboolean res = TRUE, forward = TRUE;
703
704   switch (GST_EVENT_TYPE (event)) {
705     case GST_EVENT_CUSTOM_UPSTREAM:
706     {
707       const GstStructure *s = gst_event_get_structure (event);
708
709       if (gst_structure_has_name (s, "GstRTPCollision")) {
710         guint ssrc = 0;
711
712         if (!gst_structure_get_uint (s, "ssrc", &ssrc))
713           ssrc = -1;
714
715         GST_DEBUG_OBJECT (rtpbasepayload, "collided ssrc: %" G_GUINT32_FORMAT,
716             ssrc);
717
718         /* choose another ssrc for our stream */
719         if (ssrc == rtpbasepayload->current_ssrc) {
720           GstCaps *caps;
721           guint suggested_ssrc = 0;
722
723           if (gst_structure_get_uint (s, "suggested-ssrc", &suggested_ssrc))
724             rtpbasepayload->current_ssrc = suggested_ssrc;
725
726           while (ssrc == rtpbasepayload->current_ssrc)
727             rtpbasepayload->current_ssrc = g_random_int ();
728
729           caps = gst_pad_get_current_caps (rtpbasepayload->srcpad);
730           if (caps) {
731             caps = gst_caps_make_writable (caps);
732             gst_caps_set_simple (caps,
733                 "ssrc", G_TYPE_UINT, rtpbasepayload->current_ssrc, NULL);
734             res = gst_pad_set_caps (rtpbasepayload->srcpad, caps);
735             gst_caps_unref (caps);
736           }
737
738           /* the event was for us */
739           forward = FALSE;
740         }
741       }
742       break;
743     }
744     default:
745       break;
746   }
747
748   if (forward)
749     res = gst_pad_event_default (rtpbasepayload->srcpad, parent, event);
750   else
751     gst_event_unref (event);
752
753   return res;
754 }
755
756 static gboolean
757 gst_rtp_base_payload_src_event (GstPad * pad, GstObject * parent,
758     GstEvent * event)
759 {
760   GstRTPBasePayload *rtpbasepayload;
761   GstRTPBasePayloadClass *rtpbasepayload_class;
762   gboolean res = FALSE;
763
764   rtpbasepayload = GST_RTP_BASE_PAYLOAD (parent);
765   rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
766
767   if (rtpbasepayload_class->src_event)
768     res = rtpbasepayload_class->src_event (rtpbasepayload, event);
769   else
770     gst_event_unref (event);
771
772   return res;
773 }
774
775
776 static gboolean
777 gst_rtp_base_payload_query_default (GstRTPBasePayload * rtpbasepayload,
778     GstPad * pad, GstQuery * query)
779 {
780   gboolean res = FALSE;
781
782   switch (GST_QUERY_TYPE (query)) {
783     case GST_QUERY_CAPS:
784     {
785       GstRTPBasePayloadClass *rtpbasepayload_class;
786       GstCaps *filter, *caps;
787
788       gst_query_parse_caps (query, &filter);
789       GST_DEBUG_OBJECT (rtpbasepayload, "getting caps with filter %"
790           GST_PTR_FORMAT, filter);
791
792       rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
793       if (rtpbasepayload_class->get_caps) {
794         caps = rtpbasepayload_class->get_caps (rtpbasepayload, pad, filter);
795         gst_query_set_caps_result (query, caps);
796         gst_caps_unref (caps);
797         res = TRUE;
798       }
799       break;
800     }
801     default:
802       res =
803           gst_pad_query_default (pad, GST_OBJECT_CAST (rtpbasepayload), query);
804       break;
805   }
806   return res;
807 }
808
809 static gboolean
810 gst_rtp_base_payload_query (GstPad * pad, GstObject * parent, GstQuery * query)
811 {
812   GstRTPBasePayload *rtpbasepayload;
813   GstRTPBasePayloadClass *rtpbasepayload_class;
814   gboolean res = FALSE;
815
816   rtpbasepayload = GST_RTP_BASE_PAYLOAD (parent);
817   rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
818
819   if (rtpbasepayload_class->query)
820     res = rtpbasepayload_class->query (rtpbasepayload, pad, query);
821
822   return res;
823 }
824
825 static GstFlowReturn
826 gst_rtp_base_payload_chain (GstPad * pad, GstObject * parent,
827     GstBuffer * buffer)
828 {
829   GstRTPBasePayload *rtpbasepayload;
830   GstRTPBasePayloadClass *rtpbasepayload_class;
831   GstFlowReturn ret;
832
833   rtpbasepayload = GST_RTP_BASE_PAYLOAD (parent);
834   rtpbasepayload_class = GST_RTP_BASE_PAYLOAD_GET_CLASS (rtpbasepayload);
835
836   if (!rtpbasepayload_class->handle_buffer)
837     goto no_function;
838
839   if (!rtpbasepayload->priv->negotiated)
840     goto not_negotiated;
841
842   if (rtpbasepayload->priv->source_info
843       || rtpbasepayload->priv->header_exts->len > 0) {
844     /* Save a copy of meta (instead of taking an extra reference before
845      * handle_buffer) to make the meta available when allocating a output
846      * buffer. */
847     rtpbasepayload->priv->input_meta_buffer = gst_buffer_new ();
848     gst_buffer_copy_into (rtpbasepayload->priv->input_meta_buffer, buffer,
849         GST_BUFFER_COPY_METADATA, 0, -1);
850   }
851
852   if (gst_pad_check_reconfigure (GST_RTP_BASE_PAYLOAD_SRCPAD (rtpbasepayload))) {
853     if (!gst_rtp_base_payload_negotiate (rtpbasepayload)) {
854       gst_pad_mark_reconfigure (GST_RTP_BASE_PAYLOAD_SRCPAD (rtpbasepayload));
855       if (GST_PAD_IS_FLUSHING (GST_RTP_BASE_PAYLOAD_SRCPAD (rtpbasepayload))) {
856         goto flushing;
857       } else {
858         goto negotiate_failed;
859       }
860     }
861   }
862
863   ret = rtpbasepayload_class->handle_buffer (rtpbasepayload, buffer);
864
865   gst_buffer_replace (&rtpbasepayload->priv->input_meta_buffer, NULL);
866
867   return ret;
868
869   /* ERRORS */
870 no_function:
871   {
872     GST_ELEMENT_ERROR (rtpbasepayload, STREAM, NOT_IMPLEMENTED, (NULL),
873         ("subclass did not implement handle_buffer function"));
874     gst_buffer_unref (buffer);
875     return GST_FLOW_ERROR;
876   }
877 not_negotiated:
878   {
879     GST_ELEMENT_ERROR (rtpbasepayload, CORE, NEGOTIATION, (NULL),
880         ("No input format was negotiated, i.e. no caps event was received. "
881             "Perhaps you need a parser or typefind element before the payloader"));
882     gst_buffer_unref (buffer);
883     return GST_FLOW_NOT_NEGOTIATED;
884   }
885 negotiate_failed:
886   {
887     GST_DEBUG_OBJECT (rtpbasepayload, "Not negotiated");
888     gst_buffer_unref (buffer);
889     return GST_FLOW_NOT_NEGOTIATED;
890   }
891 flushing:
892   {
893     GST_DEBUG_OBJECT (rtpbasepayload, "we are flushing");
894     gst_buffer_unref (buffer);
895     return GST_FLOW_FLUSHING;
896   }
897 }
898
899 /**
900  * gst_rtp_base_payload_set_options:
901  * @payload: a #GstRTPBasePayload
902  * @media: the media type (typically "audio" or "video")
903  * @dynamic: if the payload type is dynamic
904  * @encoding_name: the encoding name
905  * @clock_rate: the clock rate of the media
906  *
907  * Set the rtp options of the payloader. These options will be set in the caps
908  * of the payloader. Subclasses must call this method before calling
909  * gst_rtp_base_payload_push() or gst_rtp_base_payload_set_outcaps().
910  */
911 void
912 gst_rtp_base_payload_set_options (GstRTPBasePayload * payload,
913     const gchar * media, gboolean dynamic, const gchar * encoding_name,
914     guint32 clock_rate)
915 {
916   g_return_if_fail (payload != NULL);
917   g_return_if_fail (clock_rate != 0);
918
919   g_free (payload->media);
920   payload->media = g_strdup (media);
921   payload->dynamic = dynamic;
922   g_free (payload->encoding_name);
923   payload->encoding_name = g_strdup (encoding_name);
924   payload->clock_rate = clock_rate;
925 }
926
927 static gboolean
928 copy_fixed (GQuark field_id, const GValue * value, GstStructure * dest)
929 {
930   if (gst_value_is_fixed (value)) {
931     gst_structure_id_set_value (dest, field_id, value);
932   }
933   return TRUE;
934 }
935
936 static void
937 update_max_ptime (GstRTPBasePayload * rtpbasepayload)
938 {
939   if (rtpbasepayload->priv->caps_max_ptime != -1 &&
940       rtpbasepayload->priv->prop_max_ptime != -1)
941     rtpbasepayload->max_ptime = MIN (rtpbasepayload->priv->caps_max_ptime,
942         rtpbasepayload->priv->prop_max_ptime);
943   else if (rtpbasepayload->priv->caps_max_ptime != -1)
944     rtpbasepayload->max_ptime = rtpbasepayload->priv->caps_max_ptime;
945   else if (rtpbasepayload->priv->prop_max_ptime != -1)
946     rtpbasepayload->max_ptime = rtpbasepayload->priv->prop_max_ptime;
947   else
948     rtpbasepayload->max_ptime = DEFAULT_MAX_PTIME;
949 }
950
951 static gboolean
952 _set_caps (GQuark field_id, const GValue * value, GstCaps * caps)
953 {
954   gst_caps_set_value (caps, g_quark_to_string (field_id), value);
955
956   return TRUE;
957 }
958
959 /**
960  * gst_rtp_base_payload_set_outcaps_structure:
961  * @payload: a #GstRTPBasePayload
962  * @s: (nullable): a #GstStructure with the caps fields
963  *
964  * Configure the output caps with the optional fields.
965  *
966  * Returns: %TRUE if the caps could be set.
967  *
968  * Since: 1.20
969  */
970 gboolean
971 gst_rtp_base_payload_set_outcaps_structure (GstRTPBasePayload * payload,
972     GstStructure * s)
973 {
974   GstCaps *srccaps;
975
976   /* fill in the defaults, their properties cannot be negotiated. */
977   srccaps = gst_caps_new_simple ("application/x-rtp",
978       "media", G_TYPE_STRING, payload->media,
979       "clock-rate", G_TYPE_INT, payload->clock_rate,
980       "encoding-name", G_TYPE_STRING, payload->encoding_name, NULL);
981
982   GST_DEBUG_OBJECT (payload, "defaults: %" GST_PTR_FORMAT, srccaps);
983
984   if (s && gst_structure_n_fields (s) > 0) {
985     gst_structure_foreach (s, (GstStructureForeachFunc) _set_caps, srccaps);
986
987     GST_DEBUG_OBJECT (payload, "custom added: %" GST_PTR_FORMAT, srccaps);
988   }
989
990   gst_caps_replace (&payload->priv->subclass_srccaps, srccaps);
991   gst_caps_unref (srccaps);
992
993   return gst_rtp_base_payload_negotiate (payload);
994 }
995
996 /**
997  * gst_rtp_base_payload_set_outcaps:
998  * @payload: a #GstRTPBasePayload
999  * @fieldname: the first field name or %NULL
1000  * @...: field values
1001  *
1002  * Configure the output caps with the optional parameters.
1003  *
1004  * Variable arguments should be in the form field name, field type
1005  * (as a GType), value(s).  The last variable argument should be NULL.
1006  *
1007  * Returns: %TRUE if the caps could be set.
1008  */
1009 gboolean
1010 gst_rtp_base_payload_set_outcaps (GstRTPBasePayload * payload,
1011     const gchar * fieldname, ...)
1012 {
1013   gboolean result;
1014   GstStructure *s = NULL;
1015
1016   if (fieldname) {
1017     va_list varargs;
1018
1019     s = gst_structure_new_empty ("unused");
1020
1021     /* override with custom properties */
1022     va_start (varargs, fieldname);
1023     gst_structure_set_valist (s, fieldname, varargs);
1024     va_end (varargs);
1025   }
1026
1027   result = gst_rtp_base_payload_set_outcaps_structure (payload, s);
1028
1029   gst_clear_structure (&s);
1030
1031   return result;
1032 }
1033
1034 static void
1035 add_and_ref_item (GstRTPHeaderExtension * ext, GPtrArray * ret)
1036 {
1037   g_ptr_array_add (ret, gst_object_ref (ext));
1038 }
1039
1040 static void
1041 remove_item_from (GstRTPHeaderExtension * ext, GPtrArray * ret)
1042 {
1043   g_ptr_array_remove_fast (ret, ext);
1044 }
1045
1046 static void
1047 add_item_to (GstRTPHeaderExtension * ext, GPtrArray * ret)
1048 {
1049   g_ptr_array_add (ret, ext);
1050 }
1051
1052 static void
1053 add_header_ext_to_caps (GstRTPHeaderExtension * ext, GstCaps * caps)
1054 {
1055   if (!gst_rtp_header_extension_set_caps_from_attributes (ext, caps)) {
1056     GST_WARNING ("Failed to set caps from rtp header extension");
1057   }
1058 }
1059
1060 static gboolean
1061 gst_rtp_base_payload_negotiate (GstRTPBasePayload * payload)
1062 {
1063   GstCaps *templ, *peercaps, *srccaps;
1064   GstStructure *s, *d;
1065   gboolean res = TRUE;
1066
1067   payload->priv->caps_max_ptime = DEFAULT_MAX_PTIME;
1068   payload->ptime = 0;
1069
1070   gst_pad_check_reconfigure (payload->srcpad);
1071
1072   templ = gst_pad_get_pad_template_caps (payload->srcpad);
1073
1074   if (payload->priv->subclass_srccaps) {
1075     GstCaps *tmp = gst_caps_intersect (payload->priv->subclass_srccaps,
1076         templ);
1077     gst_caps_unref (templ);
1078     templ = tmp;
1079   }
1080
1081   peercaps = gst_pad_peer_query_caps (payload->srcpad, templ);
1082
1083   if (peercaps == NULL) {
1084     /* no peer caps, just add the other properties */
1085
1086     srccaps = gst_caps_copy (templ);
1087     gst_caps_set_simple (srccaps,
1088         "payload", G_TYPE_INT, GST_RTP_BASE_PAYLOAD_PT (payload),
1089         "ssrc", G_TYPE_UINT, payload->current_ssrc,
1090         "timestamp-offset", G_TYPE_UINT, payload->ts_base,
1091         "seqnum-offset", G_TYPE_UINT, payload->seqnum_base, NULL);
1092
1093     GST_DEBUG_OBJECT (payload, "no peer caps: %" GST_PTR_FORMAT, srccaps);
1094   } else {
1095     GstCaps *temp;
1096     const GValue *value;
1097     gboolean have_pt = FALSE;
1098     gboolean have_ts_offset = FALSE;
1099     gboolean have_seqnum_offset = FALSE;
1100     guint max_ptime, ptime;
1101
1102     /* peer provides caps we can use to fixate. They are already intersected
1103      * with our srccaps, just make them writable */
1104     temp = gst_caps_make_writable (peercaps);
1105     peercaps = NULL;
1106
1107     if (gst_caps_is_empty (temp)) {
1108       gst_caps_unref (temp);
1109       gst_caps_unref (templ);
1110       res = FALSE;
1111       goto out;
1112     }
1113
1114     /* We prefer the pt, timestamp-offset, seqnum-offset from the
1115      * property (if set), or any previously configured value over what
1116      * downstream prefers. Only if downstream can't accept that, or the
1117      * properties were not set, we fall back to choosing downstream's
1118      * preferred value
1119      *
1120      * For ssrc we prefer any value downstream suggests, otherwise
1121      * the property value or as a last resort a random value.
1122      * This difference for ssrc is implemented for retaining backwards
1123      * compatibility with changing rtpsession's internal-ssrc property.
1124      *
1125      * FIXME 2.0: All these properties should go away and be negotiated
1126      * via caps only!
1127      */
1128
1129     /* try to use the previously set pt, or the one from the property */
1130     if (payload->priv->pt_set || gst_pad_has_current_caps (payload->srcpad)) {
1131       GstCaps *probe_caps = gst_caps_copy (templ);
1132       GstCaps *intersection;
1133
1134       gst_caps_set_simple (probe_caps, "payload", G_TYPE_INT,
1135           GST_RTP_BASE_PAYLOAD_PT (payload), NULL);
1136       intersection = gst_caps_intersect (probe_caps, temp);
1137
1138       if (!gst_caps_is_empty (intersection)) {
1139         GST_LOG_OBJECT (payload, "Using selected pt %d",
1140             GST_RTP_BASE_PAYLOAD_PT (payload));
1141         have_pt = TRUE;
1142         gst_caps_unref (temp);
1143         temp = intersection;
1144       } else {
1145         GST_WARNING_OBJECT (payload, "Can't use selected pt %d",
1146             GST_RTP_BASE_PAYLOAD_PT (payload));
1147         gst_caps_unref (intersection);
1148       }
1149       gst_caps_unref (probe_caps);
1150     }
1151
1152     /* If we got no pt above, select one now */
1153     if (!have_pt) {
1154       gint pt;
1155
1156       /* get first structure */
1157       s = gst_caps_get_structure (temp, 0);
1158
1159       if (gst_structure_get_int (s, "payload", &pt)) {
1160         /* use peer pt */
1161         GST_RTP_BASE_PAYLOAD_PT (payload) = pt;
1162         GST_LOG_OBJECT (payload, "using peer pt %d", pt);
1163       } else {
1164         if (gst_structure_has_field (s, "payload")) {
1165           /* can only fixate if there is a field */
1166           gst_structure_fixate_field_nearest_int (s, "payload",
1167               GST_RTP_BASE_PAYLOAD_PT (payload));
1168           gst_structure_get_int (s, "payload", &pt);
1169           GST_RTP_BASE_PAYLOAD_PT (payload) = pt;
1170           GST_LOG_OBJECT (payload, "using peer pt %d", pt);
1171         } else {
1172           /* no pt field, use the internal pt */
1173           pt = GST_RTP_BASE_PAYLOAD_PT (payload);
1174           gst_structure_set (s, "payload", G_TYPE_INT, pt, NULL);
1175           GST_LOG_OBJECT (payload, "using internal pt %d", pt);
1176         }
1177       }
1178       s = NULL;
1179     }
1180
1181     /* If we got no ssrc above, select one now */
1182     /* get first structure */
1183     s = gst_caps_get_structure (temp, 0);
1184
1185     if (gst_structure_has_field_typed (s, "ssrc", G_TYPE_UINT)) {
1186       value = gst_structure_get_value (s, "ssrc");
1187       payload->current_ssrc = g_value_get_uint (value);
1188       GST_LOG_OBJECT (payload, "using peer ssrc %08x", payload->current_ssrc);
1189     } else {
1190       /* FIXME, fixate_nearest_uint would be even better but we
1191        * don't support uint ranges so how likely is it that anybody
1192        * uses a list of possible ssrcs */
1193       gst_structure_set (s, "ssrc", G_TYPE_UINT, payload->current_ssrc, NULL);
1194       GST_LOG_OBJECT (payload, "using internal ssrc %08x",
1195           payload->current_ssrc);
1196     }
1197     s = NULL;
1198
1199     /* try to select the previously used timestamp-offset, or the one from the property */
1200     if (!payload->priv->ts_offset_random
1201         || gst_pad_has_current_caps (payload->srcpad)) {
1202       GstCaps *probe_caps = gst_caps_copy (templ);
1203       GstCaps *intersection;
1204
1205       gst_caps_set_simple (probe_caps, "timestamp-offset", G_TYPE_UINT,
1206           payload->ts_base, NULL);
1207       intersection = gst_caps_intersect (probe_caps, temp);
1208
1209       if (!gst_caps_is_empty (intersection)) {
1210         GST_LOG_OBJECT (payload, "Using selected timestamp-offset %u",
1211             payload->ts_base);
1212         gst_caps_unref (temp);
1213         temp = intersection;
1214         have_ts_offset = TRUE;
1215       } else {
1216         GST_WARNING_OBJECT (payload, "Can't use selected timestamp-offset %u",
1217             payload->ts_base);
1218         gst_caps_unref (intersection);
1219       }
1220       gst_caps_unref (probe_caps);
1221     }
1222
1223     /* If we got no timestamp-offset above, select one now */
1224     if (!have_ts_offset) {
1225       /* get first structure */
1226       s = gst_caps_get_structure (temp, 0);
1227
1228       if (gst_structure_has_field_typed (s, "timestamp-offset", G_TYPE_UINT)) {
1229         value = gst_structure_get_value (s, "timestamp-offset");
1230         payload->ts_base = g_value_get_uint (value);
1231         GST_LOG_OBJECT (payload, "using peer timestamp-offset %u",
1232             payload->ts_base);
1233       } else {
1234         /* FIXME, fixate_nearest_uint would be even better but we
1235          * don't support uint ranges so how likely is it that anybody
1236          * uses a list of possible timestamp-offsets */
1237         gst_structure_set (s, "timestamp-offset", G_TYPE_UINT, payload->ts_base,
1238             NULL);
1239         GST_LOG_OBJECT (payload, "using internal timestamp-offset %u",
1240             payload->ts_base);
1241       }
1242       s = NULL;
1243     }
1244
1245     /* try to select the previously used seqnum-offset, or the one from the property */
1246     if (!payload->priv->seqnum_offset_random
1247         || gst_pad_has_current_caps (payload->srcpad)) {
1248       GstCaps *probe_caps = gst_caps_copy (templ);
1249       GstCaps *intersection;
1250
1251       gst_caps_set_simple (probe_caps, "seqnum-offset", G_TYPE_UINT,
1252           payload->seqnum_base, NULL);
1253       intersection = gst_caps_intersect (probe_caps, temp);
1254
1255       if (!gst_caps_is_empty (intersection)) {
1256         GST_LOG_OBJECT (payload, "Using selected seqnum-offset %u",
1257             payload->seqnum_base);
1258         gst_caps_unref (temp);
1259         temp = intersection;
1260         have_seqnum_offset = TRUE;
1261       } else {
1262         GST_WARNING_OBJECT (payload, "Can't use selected seqnum-offset %u",
1263             payload->seqnum_base);
1264         gst_caps_unref (intersection);
1265       }
1266       gst_caps_unref (probe_caps);
1267     }
1268
1269     /* If we got no seqnum-offset above, select one now */
1270     if (!have_seqnum_offset) {
1271       /* get first structure */
1272       s = gst_caps_get_structure (temp, 0);
1273
1274       if (gst_structure_has_field_typed (s, "seqnum-offset", G_TYPE_UINT)) {
1275         value = gst_structure_get_value (s, "seqnum-offset");
1276         payload->seqnum_base = g_value_get_uint (value);
1277         GST_LOG_OBJECT (payload, "using peer seqnum-offset %u",
1278             payload->seqnum_base);
1279         payload->priv->next_seqnum = payload->seqnum_base;
1280         payload->seqnum = payload->seqnum_base;
1281         payload->priv->seqnum_offset_random = FALSE;
1282       } else {
1283         /* FIXME, fixate_nearest_uint would be even better but we
1284          * don't support uint ranges so how likely is it that anybody
1285          * uses a list of possible seqnum-offsets */
1286         gst_structure_set (s, "seqnum-offset", G_TYPE_UINT,
1287             payload->seqnum_base, NULL);
1288         GST_LOG_OBJECT (payload, "using internal seqnum-offset %u",
1289             payload->seqnum_base);
1290       }
1291
1292       s = NULL;
1293     }
1294
1295     /* now fixate, start by taking the first caps */
1296     temp = gst_caps_truncate (temp);
1297
1298     /* get first structure */
1299     s = gst_caps_get_structure (temp, 0);
1300
1301     if (gst_structure_get_uint (s, "maxptime", &max_ptime))
1302       payload->priv->caps_max_ptime = max_ptime * GST_MSECOND;
1303
1304     if (gst_structure_get_uint (s, "ptime", &ptime))
1305       payload->ptime = ptime * GST_MSECOND;
1306
1307     /* make the target caps by copying over all the fixed fields, removing the
1308      * unfixed fields. */
1309     srccaps = gst_caps_new_empty_simple (gst_structure_get_name (s));
1310     d = gst_caps_get_structure (srccaps, 0);
1311
1312     gst_structure_foreach (s, (GstStructureForeachFunc) copy_fixed, d);
1313
1314     gst_caps_unref (temp);
1315
1316     GST_DEBUG_OBJECT (payload, "with peer caps: %" GST_PTR_FORMAT, srccaps);
1317   }
1318
1319   if (payload->priv->sinkcaps != NULL) {
1320     s = gst_caps_get_structure (payload->priv->sinkcaps, 0);
1321     if (g_str_has_prefix (gst_structure_get_name (s), "video")) {
1322       gboolean has_framerate;
1323       gint num, denom;
1324
1325       GST_DEBUG_OBJECT (payload, "video caps: %" GST_PTR_FORMAT,
1326           payload->priv->sinkcaps);
1327
1328       has_framerate = gst_structure_get_fraction (s, "framerate", &num, &denom);
1329       if (has_framerate && num == 0 && denom == 1) {
1330         has_framerate =
1331             gst_structure_get_fraction (s, "max-framerate", &num, &denom);
1332       }
1333
1334       if (has_framerate) {
1335         gchar str[G_ASCII_DTOSTR_BUF_SIZE];
1336         gdouble framerate;
1337
1338         gst_util_fraction_to_double (num, denom, &framerate);
1339         g_ascii_dtostr (str, G_ASCII_DTOSTR_BUF_SIZE, framerate);
1340         d = gst_caps_get_structure (srccaps, 0);
1341         gst_structure_set (d, "a-framerate", G_TYPE_STRING, str, NULL);
1342       }
1343
1344       GST_DEBUG_OBJECT (payload, "with video caps: %" GST_PTR_FORMAT, srccaps);
1345     }
1346   }
1347
1348   update_max_ptime (payload);
1349
1350   {
1351     /* try to find header extension implementations for the list in the
1352      * caps */
1353     GstStructure *s = gst_caps_get_structure (srccaps, 0);
1354     guint i, j, n_fields = gst_structure_n_fields (s);
1355     GPtrArray *header_exts = g_ptr_array_new_with_free_func (gst_object_unref);
1356     GPtrArray *to_add = g_ptr_array_new ();
1357     GPtrArray *to_remove = g_ptr_array_new ();
1358
1359     GST_OBJECT_LOCK (payload);
1360     g_ptr_array_foreach (payload->priv->header_exts,
1361         (GFunc) add_and_ref_item, header_exts);
1362     GST_OBJECT_UNLOCK (payload);
1363
1364     for (i = 0; i < n_fields; i++) {
1365       const gchar *field_name = gst_structure_nth_field_name (s, i);
1366       if (g_str_has_prefix (field_name, "extmap-")) {
1367         const GValue *val;
1368         const gchar *uri = NULL;
1369         gchar *nptr;
1370         guint ext_id;
1371         GstRTPHeaderExtension *ext = NULL;
1372
1373         errno = 0;
1374         ext_id = g_ascii_strtoull (&field_name[strlen ("extmap-")], &nptr, 10);
1375         if (errno != 0 || (ext_id == 0 && field_name == nptr)) {
1376           GST_WARNING_OBJECT (payload, "could not parse id from %s",
1377               field_name);
1378           res = FALSE;
1379           goto ext_out;
1380         }
1381
1382         val = gst_structure_get_value (s, field_name);
1383         if (G_VALUE_HOLDS_STRING (val)) {
1384           uri = g_value_get_string (val);
1385         } else if (GST_VALUE_HOLDS_ARRAY (val)) {
1386           /* the uri is the second value in the array */
1387           const GValue *str = gst_value_array_get_value (val, 1);
1388           if (G_VALUE_HOLDS_STRING (str)) {
1389             uri = g_value_get_string (str);
1390           }
1391         }
1392
1393         if (!uri) {
1394           GST_WARNING_OBJECT (payload, "could not get extmap uri for "
1395               "field %s", field_name);
1396           res = FALSE;
1397           goto ext_out;
1398         }
1399
1400         /* try to find if this extension mapping already exists */
1401         for (j = 0; j < header_exts->len; j++) {
1402           ext = g_ptr_array_index (header_exts, j);
1403           if (gst_rtp_header_extension_get_id (ext) == ext_id) {
1404             if (g_strcmp0 (uri, gst_rtp_header_extension_get_uri (ext)) == 0) {
1405               /* still matching, we're good, set attributes from caps in case
1406                * the caps have been updated */
1407               if (!gst_rtp_header_extension_set_attributes_from_caps (ext,
1408                       srccaps)) {
1409                 GST_WARNING_OBJECT (payload,
1410                     "Failed to configure rtp header " "extension %"
1411                     GST_PTR_FORMAT " attributes from caps %" GST_PTR_FORMAT,
1412                     ext, srccaps);
1413                 res = FALSE;
1414                 goto ext_out;
1415               }
1416               break;
1417             } else {
1418               GST_DEBUG_OBJECT (payload, "extension id %u"
1419                   "was replaced with a different extension uri "
1420                   "original:\'%s' vs \'%s\'", ext_id,
1421                   gst_rtp_header_extension_get_uri (ext), uri);
1422               g_ptr_array_add (to_remove, ext);
1423               ext = NULL;
1424               break;
1425             }
1426           } else {
1427             ext = NULL;
1428           }
1429         }
1430
1431         /* if no extension, attempt to request one */
1432         if (!ext) {
1433           GST_DEBUG_OBJECT (payload, "requesting extension for id %u"
1434               " and uri %s", ext_id, uri);
1435           g_signal_emit (payload,
1436               gst_rtp_base_payload_signals[SIGNAL_REQUEST_EXTENSION], 0,
1437               ext_id, uri, &ext);
1438           GST_DEBUG_OBJECT (payload, "request returned extension %p \'%s\' "
1439               "for id %u and uri %s", ext,
1440               ext ? GST_OBJECT_NAME (ext) : "", ext_id, uri);
1441
1442           /* We require caller to set the appropriate extension if it's required */
1443           if (ext && gst_rtp_header_extension_get_id (ext) != ext_id) {
1444             g_warning ("\'request-extension\' signal provided an rtp header "
1445                 "extension for uri \'%s\' that does not match the requested "
1446                 "extension id %u", uri, ext_id);
1447             gst_clear_object (&ext);
1448           }
1449
1450           if (ext && !gst_rtp_header_extension_set_attributes_from_caps (ext,
1451                   srccaps)) {
1452             GST_WARNING_OBJECT (payload,
1453                 "Failed to configure rtp header " "extension %"
1454                 GST_PTR_FORMAT " attributes from caps %" GST_PTR_FORMAT,
1455                 ext, srccaps);
1456             res = FALSE;
1457             g_clear_object (&ext);
1458             goto ext_out;
1459           }
1460
1461           if (ext) {
1462             g_ptr_array_add (to_add, ext);
1463           }
1464         }
1465       }
1466     }
1467
1468     GST_OBJECT_LOCK (payload);
1469     g_ptr_array_foreach (to_remove, (GFunc) remove_item_from,
1470         payload->priv->header_exts);
1471     g_ptr_array_foreach (to_add, (GFunc) add_item_to,
1472         payload->priv->header_exts);
1473     /* let extensions update their internal state from sinkcaps */
1474     if (payload->priv->sinkcaps) {
1475       gint i;
1476
1477       for (i = 0; i < payload->priv->header_exts->len; i++) {
1478         GstRTPHeaderExtension *ext;
1479
1480         ext = g_ptr_array_index (payload->priv->header_exts, i);
1481         if (!gst_rtp_header_extension_set_non_rtp_sink_caps (ext,
1482                 payload->priv->sinkcaps)) {
1483           GST_WARNING_OBJECT (payload,
1484               "Failed to update rtp header extension (%s) from sink caps",
1485               GST_OBJECT_NAME (ext));
1486           res = FALSE;
1487           GST_OBJECT_UNLOCK (payload);
1488           goto ext_out;
1489         }
1490       }
1491     }
1492     /* add extension information to srccaps */
1493     g_ptr_array_foreach (payload->priv->header_exts,
1494         (GFunc) add_header_ext_to_caps, srccaps);
1495     GST_OBJECT_UNLOCK (payload);
1496
1497   ext_out:
1498     g_ptr_array_unref (to_add);
1499     g_ptr_array_unref (to_remove);
1500     g_ptr_array_unref (header_exts);
1501   }
1502
1503   GST_DEBUG_OBJECT (payload, "configuring caps %" GST_PTR_FORMAT, srccaps);
1504
1505   if (res)
1506     res = gst_pad_set_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), srccaps);
1507   gst_caps_unref (srccaps);
1508   gst_caps_unref (templ);
1509
1510 out:
1511
1512   if (!res)
1513     gst_pad_mark_reconfigure (GST_RTP_BASE_PAYLOAD_SRCPAD (payload));
1514
1515   return res;
1516 }
1517
1518 /**
1519  * gst_rtp_base_payload_is_filled:
1520  * @payload: a #GstRTPBasePayload
1521  * @size: the size of the packet
1522  * @duration: the duration of the packet
1523  *
1524  * Check if the packet with @size and @duration would exceed the configured
1525  * maximum size.
1526  *
1527  * Returns: %TRUE if the packet of @size and @duration would exceed the
1528  * configured MTU or max_ptime.
1529  */
1530 gboolean
1531 gst_rtp_base_payload_is_filled (GstRTPBasePayload * payload,
1532     guint size, GstClockTime duration)
1533 {
1534   if (size > payload->mtu)
1535     return TRUE;
1536
1537   if (payload->max_ptime != -1 && duration >= payload->max_ptime)
1538     return TRUE;
1539
1540   return FALSE;
1541 }
1542
1543 typedef struct
1544 {
1545   GstRTPBasePayload *payload;
1546   guint32 ssrc;
1547   guint16 seqnum;
1548   guint8 pt;
1549   GstClockTime dts;
1550   GstClockTime pts;
1551   guint64 offset;
1552   guint32 rtptime;
1553 } HeaderData;
1554
1555 static gboolean
1556 find_timestamp (GstBuffer ** buffer, guint idx, gpointer user_data)
1557 {
1558   HeaderData *data = user_data;
1559   data->dts = GST_BUFFER_DTS (*buffer);
1560   data->pts = GST_BUFFER_PTS (*buffer);
1561   data->offset = GST_BUFFER_OFFSET (*buffer);
1562
1563   /* stop when we find a timestamp. We take whatever offset is associated with
1564    * the timestamp (if any) to do perfect timestamps when we need to. */
1565   if (data->pts != -1)
1566     return FALSE;
1567   else
1568     return TRUE;
1569 }
1570
1571 static void
1572 gst_rtp_base_payload_add_extension (GstRTPBasePayload * payload,
1573     GstRTPHeaderExtension * ext)
1574 {
1575   g_return_if_fail (GST_IS_RTP_HEADER_EXTENSION (ext));
1576   g_return_if_fail (gst_rtp_header_extension_get_id (ext) > 0);
1577
1578   /* XXX: check for duplicate ids? */
1579   GST_OBJECT_LOCK (payload);
1580   g_ptr_array_add (payload->priv->header_exts, gst_object_ref (ext));
1581   gst_pad_mark_reconfigure (GST_RTP_BASE_PAYLOAD_SRCPAD (payload));
1582   GST_OBJECT_UNLOCK (payload);
1583 }
1584
1585 static void
1586 gst_rtp_base_payload_clear_extensions (GstRTPBasePayload * payload)
1587 {
1588   GST_OBJECT_LOCK (payload);
1589   g_ptr_array_set_size (payload->priv->header_exts, 0);
1590   GST_OBJECT_UNLOCK (payload);
1591 }
1592
1593 typedef struct
1594 {
1595   GstRTPBasePayload *payload;
1596   GstRTPHeaderExtensionFlags flags;
1597   GstBuffer *output;
1598   guint8 *data;
1599   gsize allocated_size;
1600   gsize written_size;
1601   gsize hdr_unit_size;
1602   gboolean abort;
1603 } HeaderExt;
1604
1605 static void
1606 determine_header_extension_flags_size (GstRTPHeaderExtension * ext,
1607     gpointer user_data)
1608 {
1609   HeaderExt *hdr = user_data;
1610   guint ext_id;
1611   gsize max_size;
1612
1613   hdr->flags &= gst_rtp_header_extension_get_supported_flags (ext);
1614   max_size =
1615       gst_rtp_header_extension_get_max_size (ext,
1616       hdr->payload->priv->input_meta_buffer);
1617
1618   if (max_size > RTP_HEADER_EXT_ONE_BYTE_MAX_SIZE)
1619     hdr->flags &= ~GST_RTP_HEADER_EXTENSION_ONE_BYTE;
1620   if (max_size > RTP_HEADER_EXT_TWO_BYTE_MAX_SIZE)
1621     hdr->flags &= ~GST_RTP_HEADER_EXTENSION_TWO_BYTE;
1622
1623   ext_id = gst_rtp_header_extension_get_id (ext);
1624   if (ext_id > RTP_HEADER_EXT_ONE_BYTE_MAX_ID)
1625     hdr->flags &= ~GST_RTP_HEADER_EXTENSION_ONE_BYTE;
1626   if (ext_id > RTP_HEADER_EXT_TWO_BYTE_MAX_ID)
1627     hdr->flags &= ~GST_RTP_HEADER_EXTENSION_TWO_BYTE;
1628
1629   hdr->allocated_size += max_size;
1630 }
1631
1632 static void
1633 write_header_extension (GstRTPHeaderExtension * ext, gpointer user_data)
1634 {
1635   HeaderExt *hdr = user_data;
1636   gsize remaining =
1637       hdr->allocated_size - hdr->written_size - hdr->hdr_unit_size;
1638   gsize offset = hdr->written_size + hdr->hdr_unit_size;
1639   gssize written;
1640   guint ext_id;
1641
1642   if (hdr->abort)
1643     return;
1644
1645   written = gst_rtp_header_extension_write (ext,
1646       hdr->payload->priv->input_meta_buffer, hdr->flags, hdr->output,
1647       &hdr->data[offset], remaining);
1648
1649   GST_TRACE_OBJECT (hdr->payload, "extension %" GST_PTR_FORMAT " wrote %"
1650       G_GSIZE_FORMAT, ext, written);
1651
1652   if (written == 0) {
1653     /* extension wrote no data */
1654     return;
1655   } else if (written < 0) {
1656     GST_WARNING_OBJECT (hdr->payload, "%s failed to write extension data",
1657         GST_OBJECT_NAME (ext));
1658     goto error;
1659   } else if (written > remaining) {
1660     /* wrote too much! */
1661     g_error ("Overflow detected writing rtp header extensions. One of the "
1662         "instances likely did not report a large enough maximum size. "
1663         "Memory corruption has occured. Aborting");
1664     goto error;
1665   }
1666
1667   ext_id = gst_rtp_header_extension_get_id (ext);
1668
1669   /* move to the beginning of the extension header */
1670   offset -= hdr->hdr_unit_size;
1671
1672   /* write extension header */
1673   if (hdr->flags & GST_RTP_HEADER_EXTENSION_ONE_BYTE) {
1674     if (written > RTP_HEADER_EXT_ONE_BYTE_MAX_SIZE) {
1675       g_critical ("Amount of data written by %s is larger than allowed with "
1676           "a one byte header.", GST_OBJECT_NAME (ext));
1677       goto error;
1678     }
1679
1680     hdr->data[offset] = ((ext_id & 0x0F) << 4) | ((written - 1) & 0x0F);
1681   } else if (hdr->flags & GST_RTP_HEADER_EXTENSION_TWO_BYTE) {
1682     if (written > RTP_HEADER_EXT_TWO_BYTE_MAX_SIZE) {
1683       g_critical ("Amount of data written by %s is larger than allowed with "
1684           "a two byte header.", GST_OBJECT_NAME (ext));
1685       goto error;
1686     }
1687
1688     hdr->data[offset] = ext_id & 0xFF;
1689     hdr->data[offset + 1] = written & 0xFF;
1690   } else {
1691     g_critical ("Don't know how to write extension data with flags 0x%x!",
1692         hdr->flags);
1693     goto error;
1694   }
1695
1696   hdr->written_size += written + hdr->hdr_unit_size;
1697
1698   return;
1699
1700 error:
1701   hdr->abort = TRUE;
1702   return;
1703 }
1704
1705 static gboolean
1706 set_headers (GstBuffer ** buffer, guint idx, gpointer user_data)
1707 {
1708   HeaderData *data = user_data;
1709   HeaderExt hdrext = { NULL, };
1710   GstRTPBuffer rtp = { NULL, };
1711
1712   if (!gst_rtp_buffer_map (*buffer, GST_MAP_READWRITE, &rtp))
1713     goto map_failed;
1714
1715   gst_rtp_buffer_set_ssrc (&rtp, data->ssrc);
1716   gst_rtp_buffer_set_payload_type (&rtp, data->pt);
1717   gst_rtp_buffer_set_seq (&rtp, data->seqnum);
1718   gst_rtp_buffer_set_timestamp (&rtp, data->rtptime);
1719
1720   GST_OBJECT_LOCK (data->payload);
1721   if (data->payload->priv->header_exts->len > 0) {
1722     guint wordlen;
1723     gsize extlen;
1724     guint16 bit_pattern;
1725
1726     /* write header extensions */
1727     hdrext.payload = data->payload;
1728     hdrext.output = *buffer;
1729     /* XXX: pre-calculate these flags and sizes? */
1730     hdrext.flags =
1731         GST_RTP_HEADER_EXTENSION_ONE_BYTE | GST_RTP_HEADER_EXTENSION_TWO_BYTE;
1732     g_ptr_array_foreach (data->payload->priv->header_exts,
1733         (GFunc) determine_header_extension_flags_size, &hdrext);
1734     hdrext.hdr_unit_size = 0;
1735     if (hdrext.flags & GST_RTP_HEADER_EXTENSION_ONE_BYTE) {
1736       /* prefer the one byte header */
1737       hdrext.hdr_unit_size = 1;
1738       /* TODO: support mixed size writing modes, i.e. RFC8285 */
1739       hdrext.flags &= ~GST_RTP_HEADER_EXTENSION_TWO_BYTE;
1740       bit_pattern = 0xBEDE;
1741     } else if (hdrext.flags & GST_RTP_HEADER_EXTENSION_TWO_BYTE) {
1742       hdrext.hdr_unit_size = 2;
1743       bit_pattern = 0x1000;
1744     } else {
1745       goto unsupported_flags;
1746     }
1747
1748     extlen =
1749         hdrext.hdr_unit_size * data->payload->priv->header_exts->len +
1750         hdrext.allocated_size;
1751     wordlen = extlen / 4 + ((extlen % 4) ? 1 : 0);
1752
1753     /* XXX: do we need to add to any existing extension data instead of
1754      * overwriting everything? */
1755     gst_rtp_buffer_set_extension_data (&rtp, bit_pattern, wordlen);
1756     gst_rtp_buffer_get_extension_data (&rtp, NULL, (gpointer) & hdrext.data,
1757         &wordlen);
1758
1759     /* from 32-bit words to bytes */
1760     hdrext.allocated_size = wordlen * 4;
1761
1762     g_ptr_array_foreach (data->payload->priv->header_exts,
1763         (GFunc) write_header_extension, &hdrext);
1764
1765     if (hdrext.written_size > 0) {
1766       wordlen = hdrext.written_size / 4 + ((hdrext.written_size % 4) ? 1 : 0);
1767
1768       /* zero-fill the hdrext padding bytes */
1769       memset (&hdrext.data[hdrext.written_size], 0,
1770           wordlen * 4 - hdrext.written_size);
1771
1772       gst_rtp_buffer_set_extension_data (&rtp, bit_pattern, wordlen);
1773     } else {
1774       gst_rtp_buffer_remove_extension_data (&rtp);
1775     }
1776   }
1777   GST_OBJECT_UNLOCK (data->payload);
1778   gst_rtp_buffer_unmap (&rtp);
1779
1780   /* increment the seqnum for each buffer */
1781   data->seqnum++;
1782
1783   return TRUE;
1784   /* ERRORS */
1785 map_failed:
1786   {
1787     GST_ERROR ("failed to map buffer %p", *buffer);
1788     return FALSE;
1789   }
1790
1791 unsupported_flags:
1792   {
1793     GST_OBJECT_UNLOCK (data->payload);
1794     gst_rtp_buffer_unmap (&rtp);
1795     GST_ERROR ("Cannot add rtp header extensions with mixed header types");
1796     return FALSE;
1797   }
1798 }
1799
1800 static gboolean
1801 foreach_metadata_drop (GstBuffer * buffer, GstMeta ** meta, gpointer user_data)
1802 {
1803   GType drop_api_type = (GType) user_data;
1804   const GstMetaInfo *info = (*meta)->info;
1805
1806   if (info->api == drop_api_type)
1807     *meta = NULL;
1808
1809   return TRUE;
1810 }
1811
1812 static gboolean
1813 filter_meta (GstBuffer ** buffer, guint idx, gpointer user_data)
1814 {
1815   return gst_buffer_foreach_meta (*buffer, foreach_metadata_drop,
1816       (gpointer) GST_RTP_SOURCE_META_API_TYPE);
1817 }
1818
1819 /* Updates the SSRC, payload type, seqnum and timestamp of the RTP buffer
1820  * before the buffer is pushed. */
1821 static GstFlowReturn
1822 gst_rtp_base_payload_prepare_push (GstRTPBasePayload * payload,
1823     gpointer obj, gboolean is_list)
1824 {
1825   GstRTPBasePayloadPrivate *priv;
1826   HeaderData data;
1827
1828   if (payload->clock_rate == 0)
1829     goto no_rate;
1830
1831   priv = payload->priv;
1832
1833   /* update first, so that the property is set to the last
1834    * seqnum pushed */
1835   payload->seqnum = priv->next_seqnum;
1836
1837   /* fill in the fields we want to set on all headers */
1838   data.payload = payload;
1839   data.seqnum = payload->seqnum;
1840   data.ssrc = payload->current_ssrc;
1841   data.pt = payload->pt;
1842
1843   /* find the first buffer with a timestamp */
1844   if (is_list) {
1845     data.dts = -1;
1846     data.pts = -1;
1847     data.offset = GST_BUFFER_OFFSET_NONE;
1848     gst_buffer_list_foreach (GST_BUFFER_LIST_CAST (obj), find_timestamp, &data);
1849   } else {
1850     data.dts = GST_BUFFER_DTS (GST_BUFFER_CAST (obj));
1851     data.pts = GST_BUFFER_PTS (GST_BUFFER_CAST (obj));
1852     data.offset = GST_BUFFER_OFFSET (GST_BUFFER_CAST (obj));
1853   }
1854
1855   /* convert to RTP time */
1856   if (priv->perfect_rtptime && data.offset != GST_BUFFER_OFFSET_NONE &&
1857       priv->base_offset != GST_BUFFER_OFFSET_NONE) {
1858     /* generate perfect RTP time by adding together the base timestamp, the
1859      * running time of the first buffer and difference between the offset of the
1860      * first buffer and the offset of the current buffer. */
1861     guint64 offset = data.offset - priv->base_offset;
1862     data.rtptime = payload->ts_base + priv->base_rtime_hz + offset;
1863
1864     GST_LOG_OBJECT (payload,
1865         "Using offset %" G_GUINT64_FORMAT " for RTP timestamp", data.offset);
1866
1867     /* store buffer's running time */
1868     GST_LOG_OBJECT (payload,
1869         "setting running-time to %" G_GUINT64_FORMAT,
1870         data.offset - priv->base_offset);
1871     priv->running_time = priv->base_rtime + data.offset - priv->base_offset;
1872   } else if (GST_CLOCK_TIME_IS_VALID (data.pts)) {
1873     guint64 rtime_ns;
1874     guint64 rtime_hz;
1875
1876     /* no offset, use the gstreamer pts */
1877     if (priv->onvif_no_rate_control || !priv->scale_rtptime)
1878       rtime_ns = gst_segment_to_stream_time (&payload->segment,
1879           GST_FORMAT_TIME, data.pts);
1880     else
1881       rtime_ns =
1882           gst_segment_to_running_time (&payload->segment, GST_FORMAT_TIME,
1883           data.pts);
1884
1885     if (!GST_CLOCK_TIME_IS_VALID (rtime_ns)) {
1886       GST_LOG_OBJECT (payload, "Clipped pts, using base RTP timestamp");
1887       rtime_hz = 0;
1888     } else {
1889       GST_LOG_OBJECT (payload,
1890           "Using running_time %" GST_TIME_FORMAT " for RTP timestamp",
1891           GST_TIME_ARGS (rtime_ns));
1892       rtime_hz =
1893           gst_util_uint64_scale_int (rtime_ns, payload->clock_rate, GST_SECOND);
1894       priv->base_offset = data.offset;
1895       priv->base_rtime_hz = rtime_hz;
1896     }
1897
1898     /* add running_time in clock-rate units to the base timestamp */
1899     data.rtptime = payload->ts_base + rtime_hz;
1900
1901     /* store buffer's running time */
1902     if (priv->perfect_rtptime) {
1903       GST_LOG_OBJECT (payload,
1904           "setting running-time to %" G_GUINT64_FORMAT, rtime_hz);
1905       priv->running_time = rtime_hz;
1906     } else {
1907       GST_LOG_OBJECT (payload,
1908           "setting running-time to %" GST_TIME_FORMAT,
1909           GST_TIME_ARGS (rtime_ns));
1910       priv->running_time = rtime_ns;
1911     }
1912   } else {
1913     GST_LOG_OBJECT (payload,
1914         "Using previous RTP timestamp %" G_GUINT32_FORMAT, payload->timestamp);
1915     /* no timestamp to convert, take previous timestamp */
1916     data.rtptime = payload->timestamp;
1917   }
1918
1919   /* set ssrc, payload type, seq number, caps and rtptime */
1920   /* remove unwanted meta */
1921   if (is_list) {
1922     gst_buffer_list_foreach (GST_BUFFER_LIST_CAST (obj), set_headers, &data);
1923     gst_buffer_list_foreach (GST_BUFFER_LIST_CAST (obj), filter_meta, NULL);
1924     /* sequence number has increased more if this was a buffer list */
1925     payload->seqnum = data.seqnum - 1;
1926   } else {
1927     GstBuffer *buf = GST_BUFFER_CAST (obj);
1928     set_headers (&buf, 0, &data);
1929     filter_meta (&buf, 0, NULL);
1930   }
1931
1932   priv->next_seqnum = data.seqnum;
1933   payload->timestamp = data.rtptime;
1934
1935   GST_LOG_OBJECT (payload, "Preparing to push %s with size %"
1936       G_GSIZE_FORMAT ", seq=%d, rtptime=%u, pts %" GST_TIME_FORMAT,
1937       (is_list) ? "list" : "packet",
1938       (is_list) ? gst_buffer_list_length (GST_BUFFER_LIST_CAST (obj)) :
1939       gst_buffer_get_size (GST_BUFFER (obj)),
1940       payload->seqnum, data.rtptime, GST_TIME_ARGS (data.pts));
1941
1942   if (g_atomic_int_compare_and_exchange (&payload->priv->
1943           notified_first_timestamp, 1, 0)) {
1944     g_object_notify (G_OBJECT (payload), "timestamp");
1945     g_object_notify (G_OBJECT (payload), "seqnum");
1946   }
1947
1948   return GST_FLOW_OK;
1949
1950   /* ERRORS */
1951 no_rate:
1952   {
1953     GST_ELEMENT_ERROR (payload, STREAM, NOT_IMPLEMENTED, (NULL),
1954         ("subclass did not specify clock-rate"));
1955     return GST_FLOW_ERROR;
1956   }
1957 }
1958
1959 /**
1960  * gst_rtp_base_payload_push_list:
1961  * @payload: a #GstRTPBasePayload
1962  * @list: (transfer full): a #GstBufferList
1963  *
1964  * Push @list to the peer element of the payloader. The SSRC, payload type,
1965  * seqnum and timestamp of the RTP buffer will be updated first.
1966  *
1967  * This function takes ownership of @list.
1968  *
1969  * Returns: a #GstFlowReturn.
1970  */
1971 GstFlowReturn
1972 gst_rtp_base_payload_push_list (GstRTPBasePayload * payload,
1973     GstBufferList * list)
1974 {
1975   GstFlowReturn res;
1976
1977   res = gst_rtp_base_payload_prepare_push (payload, list, TRUE);
1978
1979   if (G_LIKELY (res == GST_FLOW_OK)) {
1980     if (G_UNLIKELY (payload->priv->pending_segment)) {
1981       gst_pad_push_event (payload->srcpad, payload->priv->pending_segment);
1982       payload->priv->pending_segment = FALSE;
1983       payload->priv->delay_segment = FALSE;
1984     }
1985     res = gst_pad_push_list (payload->srcpad, list);
1986   } else {
1987     gst_buffer_list_unref (list);
1988   }
1989
1990   return res;
1991 }
1992
1993 /**
1994  * gst_rtp_base_payload_push:
1995  * @payload: a #GstRTPBasePayload
1996  * @buffer: (transfer full): a #GstBuffer
1997  *
1998  * Push @buffer to the peer element of the payloader. The SSRC, payload type,
1999  * seqnum and timestamp of the RTP buffer will be updated first.
2000  *
2001  * This function takes ownership of @buffer.
2002  *
2003  * Returns: a #GstFlowReturn.
2004  */
2005 GstFlowReturn
2006 gst_rtp_base_payload_push (GstRTPBasePayload * payload, GstBuffer * buffer)
2007 {
2008   GstFlowReturn res;
2009
2010   res = gst_rtp_base_payload_prepare_push (payload, buffer, FALSE);
2011
2012   if (G_LIKELY (res == GST_FLOW_OK)) {
2013     if (G_UNLIKELY (payload->priv->pending_segment)) {
2014       gst_pad_push_event (payload->srcpad, payload->priv->pending_segment);
2015       payload->priv->pending_segment = FALSE;
2016       payload->priv->delay_segment = FALSE;
2017     }
2018     res = gst_pad_push (payload->srcpad, buffer);
2019   } else {
2020     gst_buffer_unref (buffer);
2021   }
2022
2023   return res;
2024 }
2025
2026 /**
2027  * gst_rtp_base_payload_allocate_output_buffer:
2028  * @payload: a #GstRTPBasePayload
2029  * @payload_len: the length of the payload
2030  * @pad_len: the amount of padding
2031  * @csrc_count: the minimum number of CSRC entries
2032  *
2033  * Allocate a new #GstBuffer with enough data to hold an RTP packet with
2034  * minimum @csrc_count CSRCs, a payload length of @payload_len and padding of
2035  * @pad_len. If @payload has #GstRTPBasePayload:source-info %TRUE additional
2036  * CSRCs may be allocated and filled with RTP source information.
2037  *
2038  * Returns: A newly allocated buffer that can hold an RTP packet with given
2039  * parameters.
2040  *
2041  * Since: 1.16
2042  */
2043 GstBuffer *
2044 gst_rtp_base_payload_allocate_output_buffer (GstRTPBasePayload * payload,
2045     guint payload_len, guint8 pad_len, guint8 csrc_count)
2046 {
2047   GstBuffer *buffer = NULL;
2048
2049   if (payload->priv->input_meta_buffer != NULL) {
2050     GstRTPSourceMeta *meta =
2051         gst_buffer_get_rtp_source_meta (payload->priv->input_meta_buffer);
2052     if (meta != NULL) {
2053       guint total_csrc_count, idx, i;
2054       GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
2055
2056       total_csrc_count = csrc_count + meta->csrc_count +
2057           (meta->ssrc_valid ? 1 : 0);
2058       total_csrc_count = MIN (total_csrc_count, 15);
2059       buffer = gst_rtp_buffer_new_allocate (payload_len, pad_len,
2060           total_csrc_count);
2061
2062       gst_rtp_buffer_map (buffer, GST_MAP_READWRITE, &rtp);
2063
2064       /* Skip CSRC fields requested by derived class and fill CSRCs from meta.
2065        * Finally append the SSRC as a new CSRC. */
2066       idx = csrc_count;
2067       for (i = 0; i < meta->csrc_count && idx < 15; i++, idx++)
2068         gst_rtp_buffer_set_csrc (&rtp, idx, meta->csrc[i]);
2069       if (meta->ssrc_valid && idx < 15)
2070         gst_rtp_buffer_set_csrc (&rtp, idx, meta->ssrc);
2071
2072       gst_rtp_buffer_unmap (&rtp);
2073     }
2074   }
2075
2076   if (buffer == NULL)
2077     buffer = gst_rtp_buffer_new_allocate (payload_len, pad_len, csrc_count);
2078
2079   return buffer;
2080 }
2081
2082 static GstStructure *
2083 gst_rtp_base_payload_create_stats (GstRTPBasePayload * rtpbasepayload)
2084 {
2085   GstRTPBasePayloadPrivate *priv;
2086   GstStructure *s;
2087
2088   priv = rtpbasepayload->priv;
2089
2090   s = gst_structure_new ("application/x-rtp-payload-stats",
2091       "clock-rate", G_TYPE_UINT, (guint) rtpbasepayload->clock_rate,
2092       "running-time", G_TYPE_UINT64, priv->running_time,
2093       "seqnum", G_TYPE_UINT, (guint) rtpbasepayload->seqnum,
2094       "timestamp", G_TYPE_UINT, (guint) rtpbasepayload->timestamp,
2095       "ssrc", G_TYPE_UINT, rtpbasepayload->current_ssrc,
2096       "pt", G_TYPE_UINT, rtpbasepayload->pt,
2097       "seqnum-offset", G_TYPE_UINT, (guint) rtpbasepayload->seqnum_base,
2098       "timestamp-offset", G_TYPE_UINT, (guint) rtpbasepayload->ts_base, NULL);
2099
2100   return s;
2101 }
2102
2103 static void
2104 gst_rtp_base_payload_set_property (GObject * object, guint prop_id,
2105     const GValue * value, GParamSpec * pspec)
2106 {
2107   GstRTPBasePayload *rtpbasepayload;
2108   GstRTPBasePayloadPrivate *priv;
2109   gint64 val;
2110
2111   rtpbasepayload = GST_RTP_BASE_PAYLOAD (object);
2112   priv = rtpbasepayload->priv;
2113
2114   switch (prop_id) {
2115     case PROP_MTU:
2116       rtpbasepayload->mtu = g_value_get_uint (value);
2117       break;
2118     case PROP_PT:
2119       rtpbasepayload->pt = g_value_get_uint (value);
2120       priv->pt_set = TRUE;
2121       break;
2122     case PROP_SSRC:
2123       val = g_value_get_uint (value);
2124       rtpbasepayload->ssrc = val;
2125       priv->ssrc_random = FALSE;
2126       break;
2127     case PROP_TIMESTAMP_OFFSET:
2128       val = g_value_get_uint (value);
2129       rtpbasepayload->ts_offset = val;
2130       priv->ts_offset_random = FALSE;
2131       break;
2132     case PROP_SEQNUM_OFFSET:
2133       val = g_value_get_int (value);
2134       rtpbasepayload->seqnum_offset = val;
2135       priv->seqnum_offset_random = (val == -1);
2136       GST_DEBUG_OBJECT (rtpbasepayload, "seqnum offset 0x%04x, random %d",
2137           rtpbasepayload->seqnum_offset, priv->seqnum_offset_random);
2138       break;
2139     case PROP_MAX_PTIME:
2140       rtpbasepayload->priv->prop_max_ptime = g_value_get_int64 (value);
2141       update_max_ptime (rtpbasepayload);
2142       break;
2143     case PROP_MIN_PTIME:
2144       rtpbasepayload->min_ptime = g_value_get_int64 (value);
2145       break;
2146     case PROP_PERFECT_RTPTIME:
2147       priv->perfect_rtptime = g_value_get_boolean (value);
2148       break;
2149     case PROP_PTIME_MULTIPLE:
2150       rtpbasepayload->ptime_multiple = g_value_get_int64 (value);
2151       break;
2152     case PROP_SOURCE_INFO:
2153       gst_rtp_base_payload_set_source_info_enabled (rtpbasepayload,
2154           g_value_get_boolean (value));
2155       break;
2156     case PROP_ONVIF_NO_RATE_CONTROL:
2157       priv->onvif_no_rate_control = g_value_get_boolean (value);
2158       break;
2159     case PROP_SCALE_RTPTIME:
2160       priv->scale_rtptime = g_value_get_boolean (value);
2161       break;
2162     case PROP_AUTO_HEADER_EXTENSION:
2163       priv->auto_hdr_ext = g_value_get_boolean (value);
2164       break;
2165     default:
2166       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2167       break;
2168   }
2169 }
2170
2171 static void
2172 gst_rtp_base_payload_get_property (GObject * object, guint prop_id,
2173     GValue * value, GParamSpec * pspec)
2174 {
2175   GstRTPBasePayload *rtpbasepayload;
2176   GstRTPBasePayloadPrivate *priv;
2177
2178   rtpbasepayload = GST_RTP_BASE_PAYLOAD (object);
2179   priv = rtpbasepayload->priv;
2180
2181   switch (prop_id) {
2182     case PROP_MTU:
2183       g_value_set_uint (value, rtpbasepayload->mtu);
2184       break;
2185     case PROP_PT:
2186       g_value_set_uint (value, rtpbasepayload->pt);
2187       break;
2188     case PROP_SSRC:
2189       if (priv->ssrc_random)
2190         g_value_set_uint (value, -1);
2191       else
2192         g_value_set_uint (value, rtpbasepayload->ssrc);
2193       break;
2194     case PROP_TIMESTAMP_OFFSET:
2195       if (priv->ts_offset_random)
2196         g_value_set_uint (value, -1);
2197       else
2198         g_value_set_uint (value, (guint32) rtpbasepayload->ts_offset);
2199       break;
2200     case PROP_SEQNUM_OFFSET:
2201       if (priv->seqnum_offset_random)
2202         g_value_set_int (value, -1);
2203       else
2204         g_value_set_int (value, (guint16) rtpbasepayload->seqnum_offset);
2205       break;
2206     case PROP_MAX_PTIME:
2207       g_value_set_int64 (value, rtpbasepayload->max_ptime);
2208       break;
2209     case PROP_MIN_PTIME:
2210       g_value_set_int64 (value, rtpbasepayload->min_ptime);
2211       break;
2212     case PROP_TIMESTAMP:
2213       g_value_set_uint (value, rtpbasepayload->timestamp);
2214       break;
2215     case PROP_SEQNUM:
2216       g_value_set_uint (value, rtpbasepayload->seqnum);
2217       break;
2218     case PROP_PERFECT_RTPTIME:
2219       g_value_set_boolean (value, priv->perfect_rtptime);
2220       break;
2221     case PROP_PTIME_MULTIPLE:
2222       g_value_set_int64 (value, rtpbasepayload->ptime_multiple);
2223       break;
2224     case PROP_STATS:
2225       g_value_take_boxed (value,
2226           gst_rtp_base_payload_create_stats (rtpbasepayload));
2227       break;
2228     case PROP_SOURCE_INFO:
2229       g_value_set_boolean (value,
2230           gst_rtp_base_payload_is_source_info_enabled (rtpbasepayload));
2231       break;
2232     case PROP_ONVIF_NO_RATE_CONTROL:
2233       g_value_set_boolean (value, priv->onvif_no_rate_control);
2234       break;
2235     case PROP_SCALE_RTPTIME:
2236       g_value_set_boolean (value, priv->scale_rtptime);
2237       break;
2238     case PROP_AUTO_HEADER_EXTENSION:
2239       g_value_set_boolean (value, priv->auto_hdr_ext);
2240       break;
2241     default:
2242       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2243       break;
2244   }
2245 }
2246
2247 static GstStateChangeReturn
2248 gst_rtp_base_payload_change_state (GstElement * element,
2249     GstStateChange transition)
2250 {
2251   GstRTPBasePayload *rtpbasepayload;
2252   GstRTPBasePayloadPrivate *priv;
2253   GstStateChangeReturn ret;
2254
2255   rtpbasepayload = GST_RTP_BASE_PAYLOAD (element);
2256   priv = rtpbasepayload->priv;
2257
2258   switch (transition) {
2259     case GST_STATE_CHANGE_NULL_TO_READY:
2260       break;
2261     case GST_STATE_CHANGE_READY_TO_PAUSED:
2262       gst_segment_init (&rtpbasepayload->segment, GST_FORMAT_UNDEFINED);
2263       rtpbasepayload->priv->delay_segment = TRUE;
2264       gst_event_replace (&rtpbasepayload->priv->pending_segment, NULL);
2265
2266       if (priv->seqnum_offset_random)
2267         rtpbasepayload->seqnum_base = g_random_int_range (0, G_MAXINT16);
2268       else
2269         rtpbasepayload->seqnum_base = rtpbasepayload->seqnum_offset;
2270       priv->next_seqnum = rtpbasepayload->seqnum_base;
2271       rtpbasepayload->seqnum = rtpbasepayload->seqnum_base;
2272
2273       if (priv->ssrc_random)
2274         rtpbasepayload->current_ssrc = g_random_int ();
2275       else
2276         rtpbasepayload->current_ssrc = rtpbasepayload->ssrc;
2277
2278       if (priv->ts_offset_random)
2279         rtpbasepayload->ts_base = g_random_int ();
2280       else
2281         rtpbasepayload->ts_base = rtpbasepayload->ts_offset;
2282       rtpbasepayload->timestamp = rtpbasepayload->ts_base;
2283       priv->running_time = DEFAULT_RUNNING_TIME;
2284       g_atomic_int_set (&rtpbasepayload->priv->notified_first_timestamp, 1);
2285       priv->base_offset = GST_BUFFER_OFFSET_NONE;
2286       priv->negotiated = FALSE;
2287       gst_caps_replace (&rtpbasepayload->priv->subclass_srccaps, NULL);
2288       gst_caps_replace (&rtpbasepayload->priv->sinkcaps, NULL);
2289       break;
2290     default:
2291       break;
2292   }
2293
2294   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2295
2296   switch (transition) {
2297     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2298       g_atomic_int_set (&rtpbasepayload->priv->notified_first_timestamp, 1);
2299       break;
2300     case GST_STATE_CHANGE_PAUSED_TO_READY:
2301       gst_event_replace (&rtpbasepayload->priv->pending_segment, NULL);
2302       break;
2303     default:
2304       break;
2305   }
2306   return ret;
2307 }
2308
2309 /**
2310  * gst_rtp_base_payload_set_source_info_enabled:
2311  * @payload: a #GstRTPBasePayload
2312  * @enable: whether to add contributing sources to RTP packets
2313  *
2314  * Enable or disable adding contributing sources to RTP packets from
2315  * #GstRTPSourceMeta.
2316  *
2317  * Since: 1.16
2318  **/
2319 void
2320 gst_rtp_base_payload_set_source_info_enabled (GstRTPBasePayload * payload,
2321     gboolean enable)
2322 {
2323   payload->priv->source_info = enable;
2324 }
2325
2326 /**
2327  * gst_rtp_base_payload_is_source_info_enabled:
2328  * @payload: a #GstRTPBasePayload
2329  *
2330  * Queries whether the payloader will add contributing sources (CSRCs) to the
2331  * RTP header from #GstRTPSourceMeta.
2332  *
2333  * Returns: %TRUE if source-info is enabled.
2334  *
2335  * Since: 1.16
2336  **/
2337 gboolean
2338 gst_rtp_base_payload_is_source_info_enabled (GstRTPBasePayload * payload)
2339 {
2340   return payload->priv->source_info;
2341 }
2342
2343
2344 /**
2345  * gst_rtp_base_payload_get_source_count:
2346  * @payload: a #GstRTPBasePayload
2347  * @buffer: (transfer none): a #GstBuffer, typically the buffer to payload
2348  *
2349  * Count the total number of RTP sources found in the meta of @buffer, which
2350  * will be automically added by gst_rtp_base_payload_allocate_output_buffer().
2351  * If #GstRTPBasePayload:source-info is %FALSE the count will be 0.
2352  *
2353  * Returns: The number of sources.
2354  *
2355  * Since: 1.16
2356  **/
2357 guint
2358 gst_rtp_base_payload_get_source_count (GstRTPBasePayload * payload,
2359     GstBuffer * buffer)
2360 {
2361   guint count = 0;
2362
2363   g_return_val_if_fail (buffer != NULL, 0);
2364
2365   if (gst_rtp_base_payload_is_source_info_enabled (payload)) {
2366     GstRTPSourceMeta *meta = gst_buffer_get_rtp_source_meta (buffer);
2367     if (meta != NULL)
2368       count = gst_rtp_source_meta_get_source_count (meta);
2369   }
2370
2371   return count;
2372 }