rtpbasedepayload: handle caps change partway through buffer list
[platform/upstream/gstreamer.git] / gst-libs / gst / rtp / gstrtpbasedepayload.c
1 /* GStreamer
2  * Copyright (C) <2005> Philippe Khalaf <burger@speedy.org>
3  * Copyright (C) <2005> Nokia Corporation <kai.vehmanen@nokia.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * SECTION:gstrtpbasedepayload
23  * @title: GstRTPBaseDepayload
24  * @short_description: Base class for RTP depayloader
25  *
26  * Provides a base class for RTP depayloaders
27  */
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include "gstrtpbasedepayload.h"
33 #include "gstrtpmeta.h"
34 #include "gstrtphdrext.h"
35
36 GST_DEBUG_CATEGORY_STATIC (rtpbasedepayload_debug);
37 #define GST_CAT_DEFAULT (rtpbasedepayload_debug)
38
39 struct _GstRTPBaseDepayloadPrivate
40 {
41   GstClockTime npt_start;
42   GstClockTime npt_stop;
43   gdouble play_speed;
44   gdouble play_scale;
45   guint clock_base;
46   gboolean onvif_mode;
47
48   gboolean discont;
49   GstClockTime pts;
50   GstClockTime dts;
51   GstClockTime duration;
52
53   guint32 last_ssrc;
54   guint32 last_seqnum;
55   guint32 last_rtptime;
56   guint32 next_seqnum;
57   gint max_reorder;
58   gboolean auto_hdr_ext;
59
60   gboolean negotiated;
61
62   GstCaps *last_caps;
63   GstEvent *segment_event;
64   guint32 segment_seqnum;       /* Note: this is a GstEvent seqnum */
65
66   gboolean source_info;
67   GstBuffer *input_buffer;
68
69   GstFlowReturn process_flow_ret;
70
71   /* array of GstRTPHeaderExtension's * */
72   GPtrArray *header_exts;
73 };
74
75 /* Filter signals and args */
76 enum
77 {
78   SIGNAL_0,
79   SIGNAL_REQUEST_EXTENSION,
80   SIGNAL_ADD_EXTENSION,
81   SIGNAL_CLEAR_EXTENSIONS,
82   LAST_SIGNAL
83 };
84
85 static guint gst_rtp_base_depayload_signals[LAST_SIGNAL] = { 0 };
86
87 #define DEFAULT_SOURCE_INFO FALSE
88 #define DEFAULT_MAX_REORDER 100
89 #define DEFAULT_AUTO_HEADER_EXTENSION TRUE
90
91 enum
92 {
93   PROP_0,
94   PROP_STATS,
95   PROP_SOURCE_INFO,
96   PROP_MAX_REORDER,
97   PROP_AUTO_HEADER_EXTENSION,
98   PROP_LAST
99 };
100
101 static void gst_rtp_base_depayload_finalize (GObject * object);
102 static void gst_rtp_base_depayload_set_property (GObject * object,
103     guint prop_id, const GValue * value, GParamSpec * pspec);
104 static void gst_rtp_base_depayload_get_property (GObject * object,
105     guint prop_id, GValue * value, GParamSpec * pspec);
106
107 static GstFlowReturn gst_rtp_base_depayload_chain (GstPad * pad,
108     GstObject * parent, GstBuffer * in);
109 static GstFlowReturn gst_rtp_base_depayload_chain_list (GstPad * pad,
110     GstObject * parent, GstBufferList * list);
111 static gboolean gst_rtp_base_depayload_handle_sink_event (GstPad * pad,
112     GstObject * parent, GstEvent * event);
113
114 static GstStateChangeReturn gst_rtp_base_depayload_change_state (GstElement *
115     element, GstStateChange transition);
116
117 static gboolean gst_rtp_base_depayload_packet_lost (GstRTPBaseDepayload *
118     filter, GstEvent * event);
119 static gboolean gst_rtp_base_depayload_handle_event (GstRTPBaseDepayload *
120     filter, GstEvent * event);
121
122 static GstElementClass *parent_class = NULL;
123 static gint private_offset = 0;
124
125 static void gst_rtp_base_depayload_class_init (GstRTPBaseDepayloadClass *
126     klass);
127 static void gst_rtp_base_depayload_init (GstRTPBaseDepayload * rtpbasepayload,
128     GstRTPBaseDepayloadClass * klass);
129 static GstEvent *create_segment_event (GstRTPBaseDepayload * filter,
130     guint rtptime, GstClockTime position);
131
132 static void gst_rtp_base_depayload_add_extension (GstRTPBaseDepayload *
133     rtpbasepayload, GstRTPHeaderExtension * ext);
134 static void gst_rtp_base_depayload_clear_extensions (GstRTPBaseDepayload *
135     rtpbasepayload);
136
137 GType
138 gst_rtp_base_depayload_get_type (void)
139 {
140   static GType rtp_base_depayload_type = 0;
141
142   if (g_once_init_enter ((gsize *) & rtp_base_depayload_type)) {
143     static const GTypeInfo rtp_base_depayload_info = {
144       sizeof (GstRTPBaseDepayloadClass),
145       NULL,
146       NULL,
147       (GClassInitFunc) gst_rtp_base_depayload_class_init,
148       NULL,
149       NULL,
150       sizeof (GstRTPBaseDepayload),
151       0,
152       (GInstanceInitFunc) gst_rtp_base_depayload_init,
153     };
154     GType _type;
155
156     _type = g_type_register_static (GST_TYPE_ELEMENT, "GstRTPBaseDepayload",
157         &rtp_base_depayload_info, G_TYPE_FLAG_ABSTRACT);
158
159     private_offset =
160         g_type_add_instance_private (_type,
161         sizeof (GstRTPBaseDepayloadPrivate));
162
163     g_once_init_leave ((gsize *) & rtp_base_depayload_type, _type);
164   }
165   return rtp_base_depayload_type;
166 }
167
168 static inline GstRTPBaseDepayloadPrivate *
169 gst_rtp_base_depayload_get_instance_private (GstRTPBaseDepayload * self)
170 {
171   return (G_STRUCT_MEMBER_P (self, private_offset));
172 }
173
174 static GstRTPHeaderExtension *
175 gst_rtp_base_depayload_request_extension_default (GstRTPBaseDepayload *
176     depayload, guint ext_id, const gchar * uri)
177 {
178   GstRTPHeaderExtension *ext = NULL;
179
180   if (!depayload->priv->auto_hdr_ext)
181     return NULL;
182
183   ext = gst_rtp_header_extension_create_from_uri (uri);
184   if (ext) {
185     GST_DEBUG_OBJECT (depayload,
186         "Automatically enabled extension %s for uri \'%s\'",
187         GST_ELEMENT_NAME (ext), uri);
188
189     gst_rtp_header_extension_set_id (ext, ext_id);
190   } else {
191     GST_DEBUG_OBJECT (depayload,
192         "Didn't find any extension implementing uri \'%s\'", uri);
193   }
194
195   return ext;
196 }
197
198 static gboolean
199 extension_accumulator (GSignalInvocationHint * ihint,
200     GValue * return_accu, const GValue * handler_return, gpointer data)
201 {
202   gpointer ext;
203
204   /* Call default handler if user callback didn't create the extension */
205   ext = g_value_get_object (handler_return);
206   if (!ext)
207     return TRUE;
208
209   g_value_set_object (return_accu, ext);
210   return FALSE;
211 }
212
213 static void
214 gst_rtp_base_depayload_class_init (GstRTPBaseDepayloadClass * klass)
215 {
216   GObjectClass *gobject_class;
217   GstElementClass *gstelement_class;
218
219   gobject_class = G_OBJECT_CLASS (klass);
220   gstelement_class = (GstElementClass *) klass;
221   parent_class = g_type_class_peek_parent (klass);
222
223   if (private_offset != 0)
224     g_type_class_adjust_private_offset (klass, &private_offset);
225
226   gobject_class->finalize = gst_rtp_base_depayload_finalize;
227   gobject_class->set_property = gst_rtp_base_depayload_set_property;
228   gobject_class->get_property = gst_rtp_base_depayload_get_property;
229
230
231   /**
232    * GstRTPBaseDepayload:stats:
233    *
234    * Various depayloader statistics retrieved atomically (and are therefore
235    * synchroized with each other). This property return a GstStructure named
236    * application/x-rtp-depayload-stats containing the following fields relating to
237    * the last processed buffer and current state of the stream being depayloaded:
238    *
239    *   * `clock-rate`: #G_TYPE_UINT, clock-rate of the stream
240    *   * `npt-start`: #G_TYPE_UINT64, time of playback start
241    *   * `npt-stop`: #G_TYPE_UINT64, time of playback stop
242    *   * `play-speed`: #G_TYPE_DOUBLE, the playback speed
243    *   * `play-scale`: #G_TYPE_DOUBLE, the playback scale
244    *   * `running-time-dts`: #G_TYPE_UINT64, the last running-time of the
245    *      last DTS
246    *   * `running-time-pts`: #G_TYPE_UINT64, the last running-time of the
247    *      last PTS
248    *   * `seqnum`: #G_TYPE_UINT, the last seen seqnum
249    *   * `timestamp`: #G_TYPE_UINT, the last seen RTP timestamp
250    **/
251   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_STATS,
252       g_param_spec_boxed ("stats", "Statistics", "Various statistics",
253           GST_TYPE_STRUCTURE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
254
255   /**
256    * GstRTPBaseDepayload:source-info:
257    *
258    * Add RTP source information found in RTP header as meta to output buffer.
259    *
260    * Since: 1.16
261    **/
262   g_object_class_install_property (gobject_class, PROP_SOURCE_INFO,
263       g_param_spec_boolean ("source-info", "RTP source information",
264           "Add RTP source information as buffer meta",
265           DEFAULT_SOURCE_INFO, G_PARAM_READWRITE));
266
267   /**
268    * GstRTPBaseDepayload:max-reorder:
269    *
270    * Max seqnum reorder before the sender is assumed to have restarted.
271    *
272    * When max-reorder is set to 0 all reordered/duplicate packets are
273    * considered coming from a restarted sender.
274    *
275    * Since: 1.18
276    **/
277   g_object_class_install_property (gobject_class, PROP_MAX_REORDER,
278       g_param_spec_int ("max-reorder", "Max Reorder",
279           "Max seqnum reorder before assuming sender has restarted",
280           0, G_MAXINT, DEFAULT_MAX_REORDER, G_PARAM_READWRITE));
281
282   /**
283    * GstRTPBaseDepayload:auto-header-extension:
284    *
285    * If enabled, the depayloader will automatically try to enable all the
286    * RTP header extensions provided in the sink caps, saving the application
287    * the need to handle these extensions manually using the
288    * GstRTPBaseDepayload::request-extension: signal.
289    *
290    * Since: 1.20
291    */
292   g_object_class_install_property (G_OBJECT_CLASS (klass),
293       PROP_AUTO_HEADER_EXTENSION, g_param_spec_boolean ("auto-header-extension",
294           "Automatic RTP header extension",
295           "Whether RTP header extensions should be automatically enabled, if an implementation is available",
296           DEFAULT_AUTO_HEADER_EXTENSION,
297           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
298
299   /**
300    * GstRTPBaseDepayload::request-extension:
301    * @object: the #GstRTPBaseDepayload
302    * @ext_id: the extension id being requested
303    * @ext_uri: (nullable): the extension URI being requested
304    *
305    * The returned @ext must be configured with the correct @ext_id and with the
306    * necessary attributes as required by the extension implementation.
307    *
308    * Returns: (transfer full): the #GstRTPHeaderExtension for @ext_id, or %NULL
309    *
310    * Since: 1.20
311    */
312   gst_rtp_base_depayload_signals[SIGNAL_REQUEST_EXTENSION] =
313       g_signal_new_class_handler ("request-extension",
314       G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
315       G_CALLBACK (gst_rtp_base_depayload_request_extension_default),
316       extension_accumulator, NULL, NULL,
317       GST_TYPE_RTP_HEADER_EXTENSION, 2, G_TYPE_UINT, G_TYPE_STRING);
318
319   /**
320    * GstRTPBaseDepayload::add-extension:
321    * @object: the #GstRTPBaseDepayload
322    * @ext: (transfer full): the #GstRTPHeaderExtension
323    *
324    * Add @ext as an extension for reading part of an RTP header extension from
325    * incoming RTP packets.
326    *
327    * Since: 1.20
328    */
329   gst_rtp_base_depayload_signals[SIGNAL_ADD_EXTENSION] =
330       g_signal_new_class_handler ("add-extension", G_TYPE_FROM_CLASS (klass),
331       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
332       G_CALLBACK (gst_rtp_base_depayload_add_extension), NULL, NULL, NULL,
333       G_TYPE_NONE, 1, GST_TYPE_RTP_HEADER_EXTENSION);
334
335   /**
336    * GstRTPBaseDepayload::clear-extensions:
337    * @object: the #GstRTPBaseDepayload
338    *
339    * Clear all RTP header extensions used by this depayloader.
340    *
341    * Since: 1.20
342    */
343   gst_rtp_base_depayload_signals[SIGNAL_CLEAR_EXTENSIONS] =
344       g_signal_new_class_handler ("clear-extensions", G_TYPE_FROM_CLASS (klass),
345       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
346       G_CALLBACK (gst_rtp_base_depayload_clear_extensions), NULL, NULL, NULL,
347       G_TYPE_NONE, 0);
348
349   gstelement_class->change_state = gst_rtp_base_depayload_change_state;
350
351   klass->packet_lost = gst_rtp_base_depayload_packet_lost;
352   klass->handle_event = gst_rtp_base_depayload_handle_event;
353
354   GST_DEBUG_CATEGORY_INIT (rtpbasedepayload_debug, "rtpbasedepayload", 0,
355       "Base class for RTP Depayloaders");
356 }
357
358 static void
359 gst_rtp_base_depayload_init (GstRTPBaseDepayload * filter,
360     GstRTPBaseDepayloadClass * klass)
361 {
362   GstPadTemplate *pad_template;
363   GstRTPBaseDepayloadPrivate *priv;
364
365   priv = gst_rtp_base_depayload_get_instance_private (filter);
366
367   filter->priv = priv;
368
369   GST_DEBUG_OBJECT (filter, "init");
370
371   pad_template =
372       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
373   g_return_if_fail (pad_template != NULL);
374   filter->sinkpad = gst_pad_new_from_template (pad_template, "sink");
375   gst_pad_set_chain_function (filter->sinkpad, gst_rtp_base_depayload_chain);
376   gst_pad_set_chain_list_function (filter->sinkpad,
377       gst_rtp_base_depayload_chain_list);
378   gst_pad_set_event_function (filter->sinkpad,
379       gst_rtp_base_depayload_handle_sink_event);
380   gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
381
382   pad_template =
383       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
384   g_return_if_fail (pad_template != NULL);
385   filter->srcpad = gst_pad_new_from_template (pad_template, "src");
386   gst_pad_use_fixed_caps (filter->srcpad);
387   gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
388
389   priv->npt_start = 0;
390   priv->npt_stop = -1;
391   priv->play_speed = 1.0;
392   priv->play_scale = 1.0;
393   priv->clock_base = -1;
394   priv->onvif_mode = FALSE;
395   priv->dts = -1;
396   priv->pts = -1;
397   priv->duration = -1;
398   priv->source_info = DEFAULT_SOURCE_INFO;
399   priv->max_reorder = DEFAULT_MAX_REORDER;
400   priv->auto_hdr_ext = DEFAULT_AUTO_HEADER_EXTENSION;
401
402   gst_segment_init (&filter->segment, GST_FORMAT_UNDEFINED);
403
404   priv->header_exts =
405       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_object_unref);
406 }
407
408 static void
409 gst_rtp_base_depayload_finalize (GObject * object)
410 {
411   GstRTPBaseDepayload *rtpbasedepayload = GST_RTP_BASE_DEPAYLOAD (object);
412
413   g_ptr_array_unref (rtpbasedepayload->priv->header_exts);
414   rtpbasedepayload->priv->header_exts = NULL;
415
416   G_OBJECT_CLASS (parent_class)->finalize (object);
417 }
418
419 static void
420 add_and_ref_item (GstRTPHeaderExtension * ext, GPtrArray * ret)
421 {
422   g_ptr_array_add (ret, gst_object_ref (ext));
423 }
424
425 static void
426 remove_item_from (GstRTPHeaderExtension * ext, GPtrArray * ret)
427 {
428   g_ptr_array_remove_fast (ret, ext);
429 }
430
431 static void
432 add_item_to (GstRTPHeaderExtension * ext, GPtrArray * ret)
433 {
434   g_ptr_array_add (ret, ext);
435 }
436
437 static gboolean
438 gst_rtp_base_depayload_setcaps (GstRTPBaseDepayload * filter, GstCaps * caps)
439 {
440   GstRTPBaseDepayloadClass *bclass;
441   GstRTPBaseDepayloadPrivate *priv;
442   gboolean res = TRUE;
443   GstStructure *caps_struct;
444   const GValue *value;
445
446   priv = filter->priv;
447
448   bclass = GST_RTP_BASE_DEPAYLOAD_GET_CLASS (filter);
449
450   GST_DEBUG_OBJECT (filter, "Set caps %" GST_PTR_FORMAT, caps);
451
452   if (priv->last_caps) {
453     if (gst_caps_is_equal (priv->last_caps, caps)) {
454       res = TRUE;
455       goto caps_not_changed;
456     } else {
457       gst_caps_unref (priv->last_caps);
458       priv->last_caps = NULL;
459     }
460   }
461
462   caps_struct = gst_caps_get_structure (caps, 0);
463
464   value = gst_structure_get_value (caps_struct, "onvif-mode");
465   if (value && G_VALUE_HOLDS_BOOLEAN (value))
466     priv->onvif_mode = g_value_get_boolean (value);
467   else
468     priv->onvif_mode = FALSE;
469   GST_DEBUG_OBJECT (filter, "Onvif mode: %d", priv->onvif_mode);
470
471   if (priv->onvif_mode)
472     filter->need_newsegment = FALSE;
473
474   /* get other values for newsegment */
475   value = gst_structure_get_value (caps_struct, "npt-start");
476   if (value && G_VALUE_HOLDS_UINT64 (value))
477     priv->npt_start = g_value_get_uint64 (value);
478   else
479     priv->npt_start = 0;
480   GST_DEBUG_OBJECT (filter, "NPT start %" G_GUINT64_FORMAT, priv->npt_start);
481
482   value = gst_structure_get_value (caps_struct, "npt-stop");
483   if (value && G_VALUE_HOLDS_UINT64 (value))
484     priv->npt_stop = g_value_get_uint64 (value);
485   else
486     priv->npt_stop = -1;
487
488   GST_DEBUG_OBJECT (filter, "NPT stop %" G_GUINT64_FORMAT, priv->npt_stop);
489
490   value = gst_structure_get_value (caps_struct, "play-speed");
491   if (value && G_VALUE_HOLDS_DOUBLE (value))
492     priv->play_speed = g_value_get_double (value);
493   else
494     priv->play_speed = 1.0;
495
496   value = gst_structure_get_value (caps_struct, "play-scale");
497   if (value && G_VALUE_HOLDS_DOUBLE (value))
498     priv->play_scale = g_value_get_double (value);
499   else
500     priv->play_scale = 1.0;
501
502   value = gst_structure_get_value (caps_struct, "clock-base");
503   if (value && G_VALUE_HOLDS_UINT (value))
504     priv->clock_base = g_value_get_uint (value);
505   else
506     priv->clock_base = -1;
507
508   {
509     /* ensure we have header extension implementations for the list in the
510      * caps */
511     guint i, j, n_fields = gst_structure_n_fields (caps_struct);
512     GPtrArray *header_exts = g_ptr_array_new_with_free_func (gst_object_unref);
513     GPtrArray *to_add = g_ptr_array_new ();
514     GPtrArray *to_remove = g_ptr_array_new ();
515
516     GST_OBJECT_LOCK (filter);
517     g_ptr_array_foreach (filter->priv->header_exts,
518         (GFunc) add_and_ref_item, header_exts);
519     GST_OBJECT_UNLOCK (filter);
520
521     for (i = 0; i < n_fields; i++) {
522       const gchar *field_name = gst_structure_nth_field_name (caps_struct, i);
523       if (g_str_has_prefix (field_name, "extmap-")) {
524         const GValue *val;
525         const gchar *uri = NULL;
526         gchar *nptr;
527         guint64 ext_id;
528         GstRTPHeaderExtension *ext = NULL;
529
530         errno = 0;
531         ext_id = g_ascii_strtoull (&field_name[strlen ("extmap-")], &nptr, 10);
532         if (errno != 0 || (ext_id == 0 && field_name == nptr)) {
533           GST_WARNING_OBJECT (filter, "could not parse id from %s", field_name);
534           res = FALSE;
535           goto ext_out;
536         }
537
538         val = gst_structure_get_value (caps_struct, field_name);
539         if (G_VALUE_HOLDS_STRING (val)) {
540           uri = g_value_get_string (val);
541         } else if (GST_VALUE_HOLDS_ARRAY (val)) {
542           /* the uri is the second value in the array */
543           const GValue *str = gst_value_array_get_value (val, 1);
544           if (G_VALUE_HOLDS_STRING (str)) {
545             uri = g_value_get_string (str);
546           }
547         }
548
549         if (!uri) {
550           GST_WARNING_OBJECT (filter, "could not get extmap uri for "
551               "field %s", field_name);
552           res = FALSE;
553           goto ext_out;
554         }
555
556         /* try to find if this extension mapping already exists */
557         for (j = 0; j < header_exts->len; j++) {
558           ext = g_ptr_array_index (header_exts, j);
559           if (gst_rtp_header_extension_get_id (ext) == ext_id) {
560             if (g_strcmp0 (uri, gst_rtp_header_extension_get_uri (ext)) == 0) {
561               /* still matching, we're good, set attributes from caps in case
562                * the caps have changed */
563               if (!gst_rtp_header_extension_set_attributes_from_caps (ext,
564                       caps)) {
565                 GST_WARNING_OBJECT (filter,
566                     "Failed to configure rtp header " "extension %"
567                     GST_PTR_FORMAT " attributes from caps %" GST_PTR_FORMAT,
568                     ext, caps);
569                 res = FALSE;
570                 goto ext_out;
571               }
572               break;
573             } else {
574               GST_DEBUG_OBJECT (filter, "extension id %" G_GUINT64_FORMAT
575                   "was replaced with a different extension uri "
576                   "original:\'%s' vs \'%s\'", ext_id,
577                   gst_rtp_header_extension_get_uri (ext), uri);
578               g_ptr_array_add (to_remove, ext);
579               ext = NULL;
580               break;
581             }
582           } else {
583             ext = NULL;
584           }
585         }
586
587         /* if no extension, attempt to request one */
588         if (!ext) {
589           GST_DEBUG_OBJECT (filter, "requesting extension for id %"
590               G_GUINT64_FORMAT " and uri %s", ext_id, uri);
591           g_signal_emit (filter,
592               gst_rtp_base_depayload_signals[SIGNAL_REQUEST_EXTENSION], 0,
593               ext_id, uri, &ext);
594           GST_DEBUG_OBJECT (filter, "request returned extension %p \'%s\' "
595               "for id %" G_GUINT64_FORMAT " and uri %s", ext,
596               ext ? GST_OBJECT_NAME (ext) : "", ext_id, uri);
597
598           /* We require the caller to set the appropriate extension if it's required */
599           if (ext && gst_rtp_header_extension_get_id (ext) != ext_id) {
600             g_warning ("\'request-extension\' signal provided an rtp header "
601                 "extension for uri \'%s\' that does not match the requested "
602                 "extension id %" G_GUINT64_FORMAT, uri, ext_id);
603             gst_clear_object (&ext);
604           }
605
606           if (ext && !gst_rtp_header_extension_set_attributes_from_caps (ext,
607                   caps)) {
608             GST_WARNING_OBJECT (filter,
609                 "Failed to configure rtp header " "extension %"
610                 GST_PTR_FORMAT " attributes from caps %" GST_PTR_FORMAT,
611                 ext, caps);
612             res = FALSE;
613             g_clear_object (&ext);
614             goto ext_out;
615           }
616
617           if (ext)
618             g_ptr_array_add (to_add, ext);
619         }
620       }
621     }
622
623     /* Note: we intentionally don't remove extensions that are not listed
624      * in caps */
625
626     GST_OBJECT_LOCK (filter);
627     g_ptr_array_foreach (to_remove, (GFunc) remove_item_from,
628         filter->priv->header_exts);
629     g_ptr_array_foreach (to_add, (GFunc) add_item_to,
630         filter->priv->header_exts);
631     GST_OBJECT_UNLOCK (filter);
632
633   ext_out:
634     g_ptr_array_unref (to_add);
635     g_ptr_array_unref (to_remove);
636     g_ptr_array_unref (header_exts);
637
638     if (!res)
639       return res;
640   }
641
642   if (bclass->set_caps) {
643     res = bclass->set_caps (filter, caps);
644     if (!res) {
645       GST_WARNING_OBJECT (filter, "Subclass rejected caps %" GST_PTR_FORMAT,
646           caps);
647     }
648   } else {
649     res = TRUE;
650   }
651
652   priv->negotiated = res;
653
654   if (priv->negotiated)
655     priv->last_caps = gst_caps_ref (caps);
656
657   return res;
658
659 caps_not_changed:
660   {
661     GST_DEBUG_OBJECT (filter, "Caps did not change");
662     return res;
663   }
664 }
665
666 /* takes ownership of the input buffer */
667 static GstFlowReturn
668 gst_rtp_base_depayload_handle_buffer (GstRTPBaseDepayload * filter,
669     GstRTPBaseDepayloadClass * bclass, GstBuffer * in)
670 {
671   GstBuffer *(*process_rtp_packet_func) (GstRTPBaseDepayload * base,
672       GstRTPBuffer * rtp_buffer);
673   GstBuffer *(*process_func) (GstRTPBaseDepayload * base, GstBuffer * in);
674   GstRTPBaseDepayloadPrivate *priv;
675   GstBuffer *out_buf;
676   guint32 ssrc;
677   guint16 seqnum;
678   guint32 rtptime;
679   gboolean discont, buf_discont;
680   gint gap;
681   GstRTPBuffer rtp = { NULL };
682
683   priv = filter->priv;
684   priv->process_flow_ret = GST_FLOW_OK;
685
686   process_func = bclass->process;
687   process_rtp_packet_func = bclass->process_rtp_packet;
688
689   /* we must have a setcaps first */
690   if (G_UNLIKELY (!priv->negotiated))
691     goto not_negotiated;
692
693   if (G_UNLIKELY (!gst_rtp_buffer_map (in, GST_MAP_READ, &rtp)))
694     goto invalid_buffer;
695
696   buf_discont = GST_BUFFER_IS_DISCONT (in);
697
698   priv->pts = GST_BUFFER_PTS (in);
699   priv->dts = GST_BUFFER_DTS (in);
700   priv->duration = GST_BUFFER_DURATION (in);
701
702   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
703   seqnum = gst_rtp_buffer_get_seq (&rtp);
704   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
705
706   priv->last_seqnum = seqnum;
707   priv->last_rtptime = rtptime;
708
709   discont = buf_discont;
710
711   GST_LOG_OBJECT (filter, "discont %d, seqnum %u, rtptime %u, pts %"
712       GST_TIME_FORMAT ", dts %" GST_TIME_FORMAT, buf_discont, seqnum, rtptime,
713       GST_TIME_ARGS (priv->pts), GST_TIME_ARGS (priv->dts));
714
715   /* Check seqnum. This is a very simple check that makes sure that the seqnums
716    * are strictly increasing, dropping anything that is out of the ordinary. We
717    * can only do this when the next_seqnum is known. */
718   if (G_LIKELY (priv->next_seqnum != -1)) {
719     if (ssrc != priv->last_ssrc) {
720       GST_LOG_OBJECT (filter,
721           "New ssrc %u (current ssrc %u), sender restarted",
722           ssrc, priv->last_ssrc);
723       discont = TRUE;
724     } else {
725       gap = gst_rtp_buffer_compare_seqnum (seqnum, priv->next_seqnum);
726
727       /* if we have no gap, all is fine */
728       if (G_UNLIKELY (gap != 0)) {
729         GST_LOG_OBJECT (filter, "got packet %u, expected %u, gap %d", seqnum,
730             priv->next_seqnum, gap);
731         if (gap < 0) {
732           /* seqnum > next_seqnum, we are missing some packets, this is always a
733            * DISCONT. */
734           GST_LOG_OBJECT (filter, "%d missing packets", gap);
735           discont = TRUE;
736         } else {
737           /* seqnum < next_seqnum, we have seen this packet before, have a
738            * reordered packet or the sender could be restarted. If the packet
739            * is not too old, we throw it away as a duplicate. Otherwise we
740            * mark discont and continue assuming the sender has restarted. See
741            * also RFC 4737. */
742           if (gap <= priv->max_reorder) {
743             GST_WARNING_OBJECT (filter, "got old packet %u, expected %u, "
744                 "gap %d <= max_reorder (%d), dropping!",
745                 seqnum, priv->next_seqnum, gap, priv->max_reorder);
746             goto dropping;
747           }
748           GST_WARNING_OBJECT (filter, "got old packet %u, expected %u, "
749               "marking discont", seqnum, priv->next_seqnum);
750           discont = TRUE;
751         }
752       }
753     }
754   }
755   priv->next_seqnum = (seqnum + 1) & 0xffff;
756   priv->last_ssrc = ssrc;
757
758   if (G_UNLIKELY (discont)) {
759     priv->discont = TRUE;
760     if (!buf_discont) {
761       gpointer old_inbuf = in;
762
763       /* we detected a seqnum discont but the buffer was not flagged with a discont,
764        * set the discont flag so that the subclass can throw away old data. */
765       GST_LOG_OBJECT (filter, "mark DISCONT on input buffer");
766       in = gst_buffer_make_writable (in);
767       GST_BUFFER_FLAG_SET (in, GST_BUFFER_FLAG_DISCONT);
768       /* depayloaders will check flag on rtpbuffer->buffer, so if the input
769        * buffer was not writable already we need to remap to make our
770        * newly-flagged buffer current on the rtpbuffer */
771       if (in != old_inbuf) {
772         gst_rtp_buffer_unmap (&rtp);
773         if (G_UNLIKELY (!gst_rtp_buffer_map (in, GST_MAP_READ, &rtp)))
774           goto invalid_buffer;
775       }
776     }
777   }
778
779   /* prepare segment event if needed */
780   if (filter->need_newsegment) {
781     priv->segment_event = create_segment_event (filter, rtptime,
782         GST_BUFFER_PTS (in));
783     filter->need_newsegment = FALSE;
784   }
785
786   priv->input_buffer = in;
787
788   if (process_rtp_packet_func != NULL) {
789     out_buf = process_rtp_packet_func (filter, &rtp);
790     gst_rtp_buffer_unmap (&rtp);
791   } else if (process_func != NULL) {
792     gst_rtp_buffer_unmap (&rtp);
793     out_buf = process_func (filter, in);
794   } else {
795     goto no_process;
796   }
797
798   /* let's send it out to processing */
799   if (out_buf) {
800     if (priv->process_flow_ret == GST_FLOW_OK)
801       priv->process_flow_ret = gst_rtp_base_depayload_push (filter, out_buf);
802     else
803       gst_buffer_unref (out_buf);
804   }
805
806   gst_buffer_unref (in);
807   priv->input_buffer = NULL;
808
809   return priv->process_flow_ret;
810
811   /* ERRORS */
812 not_negotiated:
813   {
814     /* this is not fatal but should be filtered earlier */
815     GST_ELEMENT_ERROR (filter, CORE, NEGOTIATION,
816         ("No RTP format was negotiated."),
817         ("Input buffers need to have RTP caps set on them. This is usually "
818             "achieved by setting the 'caps' property of the upstream source "
819             "element (often udpsrc or appsrc), or by putting a capsfilter "
820             "element before the depayloader and setting the 'caps' property "
821             "on that. Also see http://cgit.freedesktop.org/gstreamer/"
822             "gst-plugins-good/tree/gst/rtp/README"));
823     gst_buffer_unref (in);
824     return GST_FLOW_NOT_NEGOTIATED;
825   }
826 invalid_buffer:
827   {
828     /* this is not fatal but should be filtered earlier */
829     GST_ELEMENT_WARNING (filter, STREAM, DECODE, (NULL),
830         ("Received invalid RTP payload, dropping"));
831     gst_buffer_unref (in);
832     return GST_FLOW_OK;
833   }
834 dropping:
835   {
836     gst_rtp_buffer_unmap (&rtp);
837     gst_buffer_unref (in);
838     return GST_FLOW_OK;
839   }
840 no_process:
841   {
842     gst_rtp_buffer_unmap (&rtp);
843     /* this is not fatal but should be filtered earlier */
844     GST_ELEMENT_ERROR (filter, STREAM, NOT_IMPLEMENTED, (NULL),
845         ("The subclass does not have a process or process_rtp_packet method"));
846     gst_buffer_unref (in);
847     return GST_FLOW_ERROR;
848   }
849 }
850
851 static GstFlowReturn
852 gst_rtp_base_depayload_chain (GstPad * pad, GstObject * parent, GstBuffer * in)
853 {
854   GstRTPBaseDepayloadClass *bclass;
855   GstRTPBaseDepayload *basedepay;
856   GstFlowReturn flow_ret;
857
858   basedepay = GST_RTP_BASE_DEPAYLOAD_CAST (parent);
859
860   bclass = GST_RTP_BASE_DEPAYLOAD_GET_CLASS (basedepay);
861
862   flow_ret = gst_rtp_base_depayload_handle_buffer (basedepay, bclass, in);
863
864   return flow_ret;
865 }
866
867 static GstFlowReturn
868 gst_rtp_base_depayload_chain_list (GstPad * pad, GstObject * parent,
869     GstBufferList * list)
870 {
871   GstRTPBaseDepayloadClass *bclass;
872   GstRTPBaseDepayload *basedepay;
873   GstFlowReturn flow_ret;
874   GstBuffer *buffer;
875   guint i, len;
876
877   basedepay = GST_RTP_BASE_DEPAYLOAD_CAST (parent);
878
879   bclass = GST_RTP_BASE_DEPAYLOAD_GET_CLASS (basedepay);
880
881   flow_ret = GST_FLOW_OK;
882
883   /* chain each buffer in list individually */
884   len = gst_buffer_list_length (list);
885
886   if (len == 0)
887     goto done;
888
889   for (i = 0; i < len; i++) {
890     buffer = gst_buffer_list_get (list, i);
891
892     /* handle_buffer takes ownership of input buffer */
893     /* FIXME: add a way to steal buffers from list as we will unref it anyway */
894     gst_buffer_ref (buffer);
895
896     /* Should we fix up any missing timestamps for list buffers here
897      * (e.g. set to first or previous timestamp in list) or just assume
898      * the's a jitterbuffer that will have done that for us? */
899     flow_ret = gst_rtp_base_depayload_handle_buffer (basedepay, bclass, buffer);
900     if (flow_ret != GST_FLOW_OK)
901       break;
902   }
903
904 done:
905
906   gst_buffer_list_unref (list);
907
908   return flow_ret;
909 }
910
911 static gboolean
912 gst_rtp_base_depayload_handle_event (GstRTPBaseDepayload * filter,
913     GstEvent * event)
914 {
915   gboolean res = TRUE;
916   gboolean forward = TRUE;
917
918   switch (GST_EVENT_TYPE (event)) {
919     case GST_EVENT_FLUSH_STOP:
920       GST_OBJECT_LOCK (filter);
921       gst_segment_init (&filter->segment, GST_FORMAT_UNDEFINED);
922       GST_OBJECT_UNLOCK (filter);
923
924       filter->need_newsegment = !filter->priv->onvif_mode;
925       filter->priv->next_seqnum = -1;
926       gst_event_replace (&filter->priv->segment_event, NULL);
927       break;
928     case GST_EVENT_CAPS:
929     {
930       GstCaps *caps;
931
932       gst_event_parse_caps (event, &caps);
933
934       res = gst_rtp_base_depayload_setcaps (filter, caps);
935       forward = FALSE;
936       break;
937     }
938     case GST_EVENT_SEGMENT:
939     {
940       GstSegment segment;
941
942       GST_OBJECT_LOCK (filter);
943       gst_event_copy_segment (event, &segment);
944
945       if (segment.format != GST_FORMAT_TIME) {
946         GST_ERROR_OBJECT (filter, "Segment with non-TIME format not supported");
947         res = FALSE;
948       }
949       filter->priv->segment_seqnum = gst_event_get_seqnum (event);
950       filter->segment = segment;
951       GST_OBJECT_UNLOCK (filter);
952
953       /* In ONVIF mode, upstream is expected to send us the correct segment */
954       if (!filter->priv->onvif_mode) {
955         /* don't pass the event downstream, we generate our own segment including
956          * the NTP time and other things we receive in caps */
957         forward = FALSE;
958       }
959       break;
960     }
961     case GST_EVENT_CUSTOM_DOWNSTREAM:
962     {
963       GstRTPBaseDepayloadClass *bclass;
964
965       bclass = GST_RTP_BASE_DEPAYLOAD_GET_CLASS (filter);
966
967       if (gst_event_has_name (event, "GstRTPPacketLost")) {
968         /* we get this event from the jitterbuffer when it considers a packet as
969          * being lost. We send it to our packet_lost vmethod. The default
970          * implementation will make time progress by pushing out a GAP event.
971          * Subclasses can override and do one of the following:
972          *  - Adjust timestamp/duration to something more accurate before
973          *    calling the parent (default) packet_lost method.
974          *  - do some more advanced error concealing on the already received
975          *    (fragmented) packets.
976          *  - ignore the packet lost.
977          */
978         if (bclass->packet_lost)
979           res = bclass->packet_lost (filter, event);
980         forward = FALSE;
981       }
982       break;
983     }
984     default:
985       break;
986   }
987
988   if (forward)
989     res = gst_pad_push_event (filter->srcpad, event);
990   else
991     gst_event_unref (event);
992
993   return res;
994 }
995
996 static gboolean
997 gst_rtp_base_depayload_handle_sink_event (GstPad * pad, GstObject * parent,
998     GstEvent * event)
999 {
1000   gboolean res = FALSE;
1001   GstRTPBaseDepayload *filter;
1002   GstRTPBaseDepayloadClass *bclass;
1003
1004   filter = GST_RTP_BASE_DEPAYLOAD (parent);
1005   bclass = GST_RTP_BASE_DEPAYLOAD_GET_CLASS (filter);
1006   if (bclass->handle_event)
1007     res = bclass->handle_event (filter, event);
1008   else
1009     gst_event_unref (event);
1010
1011   return res;
1012 }
1013
1014 static GstEvent *
1015 create_segment_event (GstRTPBaseDepayload * filter, guint rtptime,
1016     GstClockTime position)
1017 {
1018   GstEvent *event;
1019   GstClockTime start, stop, running_time;
1020   GstRTPBaseDepayloadPrivate *priv;
1021   GstSegment segment;
1022
1023   priv = filter->priv;
1024
1025   /* We don't need the object lock around - the segment
1026    * can't change here while we're holding the STREAM_LOCK
1027    */
1028
1029   /* determining the start of the segment */
1030   start = filter->segment.start;
1031   if (priv->clock_base != -1 && position != -1) {
1032     GstClockTime exttime, gap;
1033
1034     exttime = priv->clock_base;
1035     gst_rtp_buffer_ext_timestamp (&exttime, rtptime);
1036     gap = gst_util_uint64_scale_int (exttime - priv->clock_base,
1037         filter->clock_rate, GST_SECOND);
1038
1039     /* account for lost packets */
1040     if (position > gap) {
1041       GST_DEBUG_OBJECT (filter,
1042           "Found gap of %" GST_TIME_FORMAT ", adjusting start: %"
1043           GST_TIME_FORMAT " = %" GST_TIME_FORMAT " - %" GST_TIME_FORMAT,
1044           GST_TIME_ARGS (gap), GST_TIME_ARGS (position - gap),
1045           GST_TIME_ARGS (position), GST_TIME_ARGS (gap));
1046       start = position - gap;
1047     }
1048   }
1049
1050   /* determining the stop of the segment */
1051   stop = filter->segment.stop;
1052   if (priv->npt_stop != -1)
1053     stop = start + (priv->npt_stop - priv->npt_start);
1054
1055   if (position == -1)
1056     position = start;
1057
1058   running_time = gst_segment_to_running_time (&filter->segment,
1059       GST_FORMAT_TIME, start);
1060
1061   gst_segment_init (&segment, GST_FORMAT_TIME);
1062   segment.rate = priv->play_speed;
1063   segment.applied_rate = priv->play_scale;
1064   segment.start = start;
1065   segment.stop = stop;
1066   segment.time = priv->npt_start;
1067   segment.position = position;
1068   segment.base = running_time;
1069
1070   GST_DEBUG_OBJECT (filter, "Creating segment event %" GST_SEGMENT_FORMAT,
1071       &segment);
1072   event = gst_event_new_segment (&segment);
1073   if (filter->priv->segment_seqnum != GST_SEQNUM_INVALID)
1074     gst_event_set_seqnum (event, filter->priv->segment_seqnum);
1075
1076   return event;
1077 }
1078
1079 static gboolean
1080 foreach_metadata_drop (GstBuffer * buffer, GstMeta ** meta, gpointer user_data)
1081 {
1082   GType drop_api_type = (GType) user_data;
1083   const GstMetaInfo *info = (*meta)->info;
1084
1085   if (info->api == drop_api_type)
1086     *meta = NULL;
1087
1088   return TRUE;
1089 }
1090
1091 static void
1092 add_rtp_source_meta (GstBuffer * outbuf, GstBuffer * rtpbuf)
1093 {
1094   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
1095   GstRTPSourceMeta *meta;
1096   guint32 ssrc;
1097   GType source_meta_api = gst_rtp_source_meta_api_get_type ();
1098
1099   if (!gst_rtp_buffer_map (rtpbuf, GST_MAP_READ, &rtp))
1100     return;
1101
1102   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
1103
1104   /* remove any pre-existing source-meta */
1105   gst_buffer_foreach_meta (outbuf, foreach_metadata_drop,
1106       (gpointer) source_meta_api);
1107
1108   meta = gst_buffer_add_rtp_source_meta (outbuf, &ssrc, NULL, 0);
1109   if (meta != NULL) {
1110     gint i;
1111     gint csrc_count = gst_rtp_buffer_get_csrc_count (&rtp);
1112     for (i = 0; i < csrc_count; i++) {
1113       guint32 csrc = gst_rtp_buffer_get_csrc (&rtp, i);
1114       gst_rtp_source_meta_append_csrc (meta, &csrc, 1);
1115     }
1116   }
1117
1118   gst_rtp_buffer_unmap (&rtp);
1119 }
1120
1121 static void
1122 gst_rtp_base_depayload_add_extension (GstRTPBaseDepayload * rtpbasepayload,
1123     GstRTPHeaderExtension * ext)
1124 {
1125   g_return_if_fail (GST_IS_RTP_HEADER_EXTENSION (ext));
1126   g_return_if_fail (gst_rtp_header_extension_get_id (ext) > 0);
1127
1128   /* XXX: check for duplicate ids? */
1129   GST_OBJECT_LOCK (rtpbasepayload);
1130   g_ptr_array_add (rtpbasepayload->priv->header_exts, gst_object_ref (ext));
1131   GST_OBJECT_UNLOCK (rtpbasepayload);
1132 }
1133
1134 static void
1135 gst_rtp_base_depayload_clear_extensions (GstRTPBaseDepayload * rtpbasepayload)
1136 {
1137   GST_OBJECT_LOCK (rtpbasepayload);
1138   g_ptr_array_set_size (rtpbasepayload->priv->header_exts, 0);
1139   GST_OBJECT_UNLOCK (rtpbasepayload);
1140 }
1141
1142 static gboolean
1143 read_rtp_header_extensions (GstRTPBaseDepayload * depayload,
1144     GstBuffer * input, GstBuffer * output)
1145 {
1146   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
1147   guint16 bit_pattern;
1148   guint8 *pdata;
1149   guint wordlen;
1150   gboolean needs_src_caps_update = FALSE;
1151
1152   if (!input) {
1153     GST_DEBUG_OBJECT (depayload, "no input buffer");
1154     return needs_src_caps_update;
1155   }
1156
1157   if (!gst_rtp_buffer_map (input, GST_MAP_READ, &rtp)) {
1158     GST_WARNING_OBJECT (depayload, "Failed to map buffer");
1159     return needs_src_caps_update;
1160   }
1161
1162   if (gst_rtp_buffer_get_extension_data (&rtp, &bit_pattern, (gpointer) & pdata,
1163           &wordlen)) {
1164     GstRTPHeaderExtensionFlags ext_flags = 0;
1165     gsize bytelen = wordlen * 4;
1166     guint hdr_unit_bytes;
1167     gsize offset = 0;
1168
1169     if (bit_pattern == 0xBEDE) {
1170       /* one byte extensions */
1171       hdr_unit_bytes = 1;
1172       ext_flags |= GST_RTP_HEADER_EXTENSION_ONE_BYTE;
1173     } else if (bit_pattern >> 4 == 0x100) {
1174       /* two byte extensions */
1175       hdr_unit_bytes = 2;
1176       ext_flags |= GST_RTP_HEADER_EXTENSION_TWO_BYTE;
1177     } else {
1178       GST_DEBUG_OBJECT (depayload, "unknown extension bit pattern 0x%02x%02x",
1179           bit_pattern >> 8, bit_pattern & 0xff);
1180       goto out;
1181     }
1182
1183     while (TRUE) {
1184       guint8 read_id, read_len;
1185       GstRTPHeaderExtension *ext = NULL;
1186       guint i;
1187
1188       if (offset + hdr_unit_bytes >= bytelen)
1189         /* not enough remaning data */
1190         break;
1191
1192       if (ext_flags & GST_RTP_HEADER_EXTENSION_ONE_BYTE) {
1193         read_id = GST_READ_UINT8 (pdata + offset) >> 4;
1194         read_len = (GST_READ_UINT8 (pdata + offset) & 0x0F) + 1;
1195         offset += 1;
1196
1197         if (read_id == 0)
1198           /* padding */
1199           continue;
1200
1201         if (read_id == 15)
1202           /* special id for possible future expansion */
1203           break;
1204       } else {
1205         read_id = GST_READ_UINT8 (pdata + offset);
1206         offset += 1;
1207
1208         if (read_id == 0)
1209           /* padding */
1210           continue;
1211
1212         read_len = GST_READ_UINT8 (pdata + offset);
1213         offset += 1;
1214       }
1215       GST_TRACE_OBJECT (depayload, "found rtp header extension with id %u and "
1216           "length %u", read_id, read_len);
1217
1218       /* Ignore extension headers where the size does not fit */
1219       if (offset + read_len > bytelen) {
1220         GST_WARNING_OBJECT (depayload, "Extension length extends past the "
1221             "size of the extension data");
1222         break;
1223       }
1224
1225       GST_OBJECT_LOCK (depayload);
1226       for (i = 0; i < depayload->priv->header_exts->len; i++) {
1227         ext = g_ptr_array_index (depayload->priv->header_exts, i);
1228         if (read_id == gst_rtp_header_extension_get_id (ext)) {
1229           gst_object_ref (ext);
1230           break;
1231         }
1232         ext = NULL;
1233       }
1234
1235       if (ext) {
1236         if (!gst_rtp_header_extension_read (ext, ext_flags, &pdata[offset],
1237                 read_len, output)) {
1238           GST_WARNING_OBJECT (depayload, "RTP header extension (%s) could "
1239               "not read payloaded data", GST_OBJECT_NAME (ext));
1240           GST_OBJECT_UNLOCK (ext);
1241           gst_object_unref (ext);
1242           goto out;
1243         }
1244
1245         if (gst_rtp_header_extension_wants_update_non_rtp_src_caps (ext)) {
1246           needs_src_caps_update = TRUE;
1247         }
1248
1249         gst_object_unref (ext);
1250       }
1251       GST_OBJECT_UNLOCK (depayload);
1252
1253       offset += read_len;
1254     }
1255   }
1256
1257 out:
1258   gst_rtp_buffer_unmap (&rtp);
1259
1260   return needs_src_caps_update;
1261 }
1262
1263 static gboolean
1264 gst_rtp_base_depayload_set_headers (GstRTPBaseDepayload * depayload,
1265     GstBuffer * buffer)
1266 {
1267   GstRTPBaseDepayloadPrivate *priv = depayload->priv;
1268   GstClockTime pts, dts, duration;
1269
1270   pts = GST_BUFFER_PTS (buffer);
1271   dts = GST_BUFFER_DTS (buffer);
1272   duration = GST_BUFFER_DURATION (buffer);
1273
1274   /* apply last incoming timestamp and duration to outgoing buffer if
1275    * not otherwise set. */
1276   if (!GST_CLOCK_TIME_IS_VALID (pts))
1277     GST_BUFFER_PTS (buffer) = priv->pts;
1278   if (!GST_CLOCK_TIME_IS_VALID (dts))
1279     GST_BUFFER_DTS (buffer) = priv->dts;
1280   if (!GST_CLOCK_TIME_IS_VALID (duration))
1281     GST_BUFFER_DURATION (buffer) = priv->duration;
1282
1283   if (G_UNLIKELY (depayload->priv->discont)) {
1284     GST_LOG_OBJECT (depayload, "Marking DISCONT on output buffer");
1285     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1286     depayload->priv->discont = FALSE;
1287   }
1288
1289   /* make sure we only set the timestamp on the first packet */
1290   priv->pts = GST_CLOCK_TIME_NONE;
1291   priv->dts = GST_CLOCK_TIME_NONE;
1292   priv->duration = GST_CLOCK_TIME_NONE;
1293
1294   if (priv->input_buffer) {
1295     if (priv->source_info)
1296       add_rtp_source_meta (buffer, priv->input_buffer);
1297
1298     return read_rtp_header_extensions (depayload, priv->input_buffer, buffer);
1299   }
1300
1301   return FALSE;
1302 }
1303
1304 static GstFlowReturn
1305 gst_rtp_base_depayload_finish_push (GstRTPBaseDepayload * filter,
1306     gboolean is_list, gpointer obj)
1307 {
1308   /* if this is the first buffer send a NEWSEGMENT */
1309   if (G_UNLIKELY (filter->priv->segment_event)) {
1310     gst_pad_push_event (filter->srcpad, filter->priv->segment_event);
1311     filter->priv->segment_event = NULL;
1312     GST_DEBUG_OBJECT (filter, "Pushed newsegment event on this first buffer");
1313   }
1314
1315   if (is_list) {
1316     GstBufferList *blist = obj;
1317     return gst_pad_push_list (filter->srcpad, blist);
1318   } else {
1319     GstBuffer *buf = obj;
1320     return gst_pad_push (filter->srcpad, buf);
1321   }
1322 }
1323
1324 static gboolean
1325 gst_rtp_base_depayload_set_src_caps_from_hdrext (GstRTPBaseDepayload * filter)
1326 {
1327   gboolean update_ok = TRUE;
1328   GstCaps *src_caps = gst_pad_get_current_caps (filter->srcpad);
1329
1330   if (src_caps) {
1331     GstCaps *new_caps;
1332     gint i;
1333
1334     new_caps = gst_caps_copy (src_caps);
1335     for (i = 0; i < filter->priv->header_exts->len; i++) {
1336       GstRTPHeaderExtension *ext;
1337
1338       ext = g_ptr_array_index (filter->priv->header_exts, i);
1339       update_ok =
1340           gst_rtp_header_extension_update_non_rtp_src_caps (ext, new_caps);
1341
1342       if (!update_ok) {
1343         GST_ELEMENT_ERROR (filter, STREAM, DECODE,
1344             ("RTP header extension (%s) could not update src caps",
1345                 GST_OBJECT_NAME (ext)), (NULL));
1346         break;
1347       }
1348     }
1349
1350     if (G_UNLIKELY (update_ok && !gst_caps_is_equal (src_caps, new_caps))) {
1351       gst_pad_set_caps (filter->srcpad, new_caps);
1352     }
1353
1354     gst_caps_unref (src_caps);
1355     gst_caps_unref (new_caps);
1356   }
1357
1358   return update_ok;
1359 }
1360
1361 static GstFlowReturn
1362 gst_rtp_base_depayload_do_push (GstRTPBaseDepayload * filter, gboolean is_list,
1363     gpointer obj)
1364 {
1365   GstFlowReturn res;
1366
1367   if (is_list) {
1368     GstBufferList *blist = obj;
1369     guint i;
1370     guint first_not_pushed_idx = 0;
1371
1372     for (i = 0; i < gst_buffer_list_length (blist); ++i) {
1373       GstBuffer *buf = gst_buffer_list_get_writable (blist, i);
1374
1375       if (G_UNLIKELY (gst_rtp_base_depayload_set_headers (filter, buf))) {
1376         /* src caps have changed; push the buffers preceding the current one,
1377          * then apply the new caps on the src pad */
1378         guint j;
1379
1380         for (j = first_not_pushed_idx; j < i; ++j) {
1381           res = gst_rtp_base_depayload_finish_push (filter, FALSE,
1382               gst_buffer_ref (gst_buffer_list_get (blist, j)));
1383           if (G_UNLIKELY (res != GST_FLOW_OK)) {
1384             goto error_list;
1385           }
1386         }
1387         first_not_pushed_idx = i;
1388
1389         if (!gst_rtp_base_depayload_set_src_caps_from_hdrext (filter)) {
1390           res = GST_FLOW_ERROR;
1391           goto error_list;
1392         }
1393       }
1394     }
1395
1396     if (G_LIKELY (first_not_pushed_idx == 0)) {
1397       res = gst_rtp_base_depayload_finish_push (filter, TRUE, blist);
1398       blist = NULL;
1399     } else {
1400       for (i = first_not_pushed_idx; i < gst_buffer_list_length (blist); ++i) {
1401         res = gst_rtp_base_depayload_finish_push (filter, FALSE,
1402             gst_buffer_ref (gst_buffer_list_get (blist, i)));
1403         if (G_UNLIKELY (res != GST_FLOW_OK)) {
1404           break;
1405         }
1406       }
1407     }
1408
1409   error_list:
1410     gst_clear_buffer_list (&blist);
1411   } else {
1412     GstBuffer *buf = obj;
1413     if (G_UNLIKELY (gst_rtp_base_depayload_set_headers (filter, buf))) {
1414       if (!gst_rtp_base_depayload_set_src_caps_from_hdrext (filter)) {
1415         res = GST_FLOW_ERROR;
1416         goto error_buffer;
1417       }
1418     }
1419
1420     res = gst_rtp_base_depayload_finish_push (filter, FALSE, buf);
1421     buf = NULL;
1422
1423   error_buffer:
1424     gst_clear_buffer (&buf);
1425   }
1426
1427   return res;
1428 }
1429
1430 /**
1431  * gst_rtp_base_depayload_push:
1432  * @filter: a #GstRTPBaseDepayload
1433  * @out_buf: a #GstBuffer
1434  *
1435  * Push @out_buf to the peer of @filter. This function takes ownership of
1436  * @out_buf.
1437  *
1438  * This function will by default apply the last incoming timestamp on
1439  * the outgoing buffer when it didn't have a timestamp already.
1440  *
1441  * Returns: a #GstFlowReturn.
1442  */
1443 GstFlowReturn
1444 gst_rtp_base_depayload_push (GstRTPBaseDepayload * filter, GstBuffer * out_buf)
1445 {
1446   GstFlowReturn res;
1447
1448   res = gst_rtp_base_depayload_do_push (filter, FALSE, out_buf);
1449
1450   if (res != GST_FLOW_OK)
1451     filter->priv->process_flow_ret = res;
1452
1453   return res;
1454 }
1455
1456 /**
1457  * gst_rtp_base_depayload_push_list:
1458  * @filter: a #GstRTPBaseDepayload
1459  * @out_list: a #GstBufferList
1460  *
1461  * Push @out_list to the peer of @filter. This function takes ownership of
1462  * @out_list.
1463  *
1464  * Returns: a #GstFlowReturn.
1465  */
1466 GstFlowReturn
1467 gst_rtp_base_depayload_push_list (GstRTPBaseDepayload * filter,
1468     GstBufferList * out_list)
1469 {
1470   GstFlowReturn res;
1471
1472   res = gst_rtp_base_depayload_do_push (filter, TRUE, out_list);
1473
1474   if (res != GST_FLOW_OK)
1475     filter->priv->process_flow_ret = res;
1476
1477   return res;
1478 }
1479
1480 /* convert the PacketLost event from a jitterbuffer to a GAP event.
1481  * subclasses can override this.  */
1482 static gboolean
1483 gst_rtp_base_depayload_packet_lost (GstRTPBaseDepayload * filter,
1484     GstEvent * event)
1485 {
1486   GstClockTime timestamp, duration;
1487   GstEvent *sevent;
1488   const GstStructure *s;
1489   gboolean might_have_been_fec;
1490   gboolean res = TRUE;
1491
1492   s = gst_event_get_structure (event);
1493
1494   /* first start by parsing the timestamp and duration */
1495   timestamp = -1;
1496   duration = -1;
1497
1498   if (!gst_structure_get_clock_time (s, "timestamp", &timestamp) ||
1499       !gst_structure_get_clock_time (s, "duration", &duration)) {
1500     GST_ERROR_OBJECT (filter,
1501         "Packet loss event without timestamp or duration");
1502     return FALSE;
1503   }
1504
1505   sevent = gst_pad_get_sticky_event (filter->srcpad, GST_EVENT_SEGMENT, 0);
1506   if (G_UNLIKELY (!sevent)) {
1507     /* Typically happens if lost event arrives before first buffer */
1508     GST_DEBUG_OBJECT (filter,
1509         "Ignore packet loss because segment event missing");
1510     return FALSE;
1511   }
1512   gst_event_unref (sevent);
1513
1514   if (!gst_structure_get_boolean (s, "might-have-been-fec",
1515           &might_have_been_fec) || !might_have_been_fec) {
1516     /* send GAP event */
1517     sevent = gst_event_new_gap (timestamp, duration);
1518     gst_event_set_gap_flags (sevent, GST_GAP_FLAG_MISSING_DATA);
1519     res = gst_pad_push_event (filter->srcpad, sevent);
1520   }
1521
1522   return res;
1523 }
1524
1525 static GstStateChangeReturn
1526 gst_rtp_base_depayload_change_state (GstElement * element,
1527     GstStateChange transition)
1528 {
1529   GstRTPBaseDepayload *filter;
1530   GstRTPBaseDepayloadPrivate *priv;
1531   GstStateChangeReturn ret;
1532
1533   filter = GST_RTP_BASE_DEPAYLOAD (element);
1534   priv = filter->priv;
1535
1536   switch (transition) {
1537     case GST_STATE_CHANGE_NULL_TO_READY:
1538       break;
1539     case GST_STATE_CHANGE_READY_TO_PAUSED:
1540       filter->need_newsegment = TRUE;
1541       priv->npt_start = 0;
1542       priv->npt_stop = -1;
1543       priv->play_speed = 1.0;
1544       priv->play_scale = 1.0;
1545       priv->clock_base = -1;
1546       priv->onvif_mode = FALSE;
1547       priv->next_seqnum = -1;
1548       priv->negotiated = FALSE;
1549       priv->discont = FALSE;
1550       priv->segment_seqnum = GST_SEQNUM_INVALID;
1551       break;
1552     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1553       break;
1554     default:
1555       break;
1556   }
1557
1558   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1559
1560   switch (transition) {
1561     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1562       break;
1563     case GST_STATE_CHANGE_PAUSED_TO_READY:
1564       gst_caps_replace (&priv->last_caps, NULL);
1565       gst_event_replace (&priv->segment_event, NULL);
1566       break;
1567     case GST_STATE_CHANGE_READY_TO_NULL:
1568       break;
1569     default:
1570       break;
1571   }
1572   return ret;
1573 }
1574
1575 static GstStructure *
1576 gst_rtp_base_depayload_create_stats (GstRTPBaseDepayload * depayload)
1577 {
1578   GstRTPBaseDepayloadPrivate *priv;
1579   GstStructure *s;
1580   GstClockTime pts = GST_CLOCK_TIME_NONE, dts = GST_CLOCK_TIME_NONE;
1581
1582   priv = depayload->priv;
1583
1584   GST_OBJECT_LOCK (depayload);
1585   if (depayload->segment.format != GST_FORMAT_UNDEFINED) {
1586     pts = gst_segment_to_running_time (&depayload->segment, GST_FORMAT_TIME,
1587         priv->pts);
1588     dts = gst_segment_to_running_time (&depayload->segment, GST_FORMAT_TIME,
1589         priv->dts);
1590   }
1591   GST_OBJECT_UNLOCK (depayload);
1592
1593   s = gst_structure_new ("application/x-rtp-depayload-stats",
1594       "clock_rate", G_TYPE_UINT, depayload->clock_rate,
1595       "npt-start", G_TYPE_UINT64, priv->npt_start,
1596       "npt-stop", G_TYPE_UINT64, priv->npt_stop,
1597       "play-speed", G_TYPE_DOUBLE, priv->play_speed,
1598       "play-scale", G_TYPE_DOUBLE, priv->play_scale,
1599       "running-time-dts", G_TYPE_UINT64, dts,
1600       "running-time-pts", G_TYPE_UINT64, pts,
1601       "seqnum", G_TYPE_UINT, (guint) priv->last_seqnum,
1602       "timestamp", G_TYPE_UINT, (guint) priv->last_rtptime, NULL);
1603
1604   return s;
1605 }
1606
1607
1608 static void
1609 gst_rtp_base_depayload_set_property (GObject * object, guint prop_id,
1610     const GValue * value, GParamSpec * pspec)
1611 {
1612   GstRTPBaseDepayload *depayload;
1613   GstRTPBaseDepayloadPrivate *priv;
1614
1615   depayload = GST_RTP_BASE_DEPAYLOAD (object);
1616   priv = depayload->priv;
1617
1618   switch (prop_id) {
1619     case PROP_SOURCE_INFO:
1620       gst_rtp_base_depayload_set_source_info_enabled (depayload,
1621           g_value_get_boolean (value));
1622       break;
1623     case PROP_MAX_REORDER:
1624       priv->max_reorder = g_value_get_int (value);
1625       break;
1626     case PROP_AUTO_HEADER_EXTENSION:
1627       priv->auto_hdr_ext = g_value_get_boolean (value);
1628       break;
1629     default:
1630       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1631       break;
1632   }
1633 }
1634
1635 static void
1636 gst_rtp_base_depayload_get_property (GObject * object, guint prop_id,
1637     GValue * value, GParamSpec * pspec)
1638 {
1639   GstRTPBaseDepayload *depayload;
1640   GstRTPBaseDepayloadPrivate *priv;
1641
1642   depayload = GST_RTP_BASE_DEPAYLOAD (object);
1643   priv = depayload->priv;
1644
1645   switch (prop_id) {
1646     case PROP_STATS:
1647       g_value_take_boxed (value,
1648           gst_rtp_base_depayload_create_stats (depayload));
1649       break;
1650     case PROP_SOURCE_INFO:
1651       g_value_set_boolean (value,
1652           gst_rtp_base_depayload_is_source_info_enabled (depayload));
1653       break;
1654     case PROP_MAX_REORDER:
1655       g_value_set_int (value, priv->max_reorder);
1656       break;
1657     case PROP_AUTO_HEADER_EXTENSION:
1658       g_value_set_boolean (value, priv->auto_hdr_ext);
1659       break;
1660     default:
1661       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1662       break;
1663   }
1664 }
1665
1666 /**
1667  * gst_rtp_base_depayload_set_source_info_enabled:
1668  * @depayload: a #GstRTPBaseDepayload
1669  * @enable: whether to add meta about RTP sources to buffer
1670  *
1671  * Enable or disable adding #GstRTPSourceMeta to depayloaded buffers.
1672  *
1673  * Since: 1.16
1674  **/
1675 void
1676 gst_rtp_base_depayload_set_source_info_enabled (GstRTPBaseDepayload * depayload,
1677     gboolean enable)
1678 {
1679   depayload->priv->source_info = enable;
1680 }
1681
1682 /**
1683  * gst_rtp_base_depayload_is_source_info_enabled:
1684  * @depayload: a #GstRTPBaseDepayload
1685  *
1686  * Queries whether #GstRTPSourceMeta will be added to depayloaded buffers.
1687  *
1688  * Returns: %TRUE if source-info is enabled.
1689  *
1690  * Since: 1.16
1691  **/
1692 gboolean
1693 gst_rtp_base_depayload_is_source_info_enabled (GstRTPBaseDepayload * depayload)
1694 {
1695   return depayload->priv->source_info;
1696 }