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