rtprtxsend: print valid type where guint32 is expected
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / gstrtprtxsend.c
1 /* RTP Retransmission sender element for GStreamer
2  *
3  * gstrtprtxsend.c:
4  *
5  * Copyright (C) 2013 Collabora Ltd.
6  *   @author Julien Isorce <julien.isorce@collabora.co.uk>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:element-rtprtxsend
26  *
27  * See #GstRtpRtxReceive for examples
28  * 
29  * The purpose of the sender RTX object is to keep a history of RTP packets up
30  * to a configurable limit (max-size-time or max-size-packets). It will listen
31  * for upstream custom retransmission events (GstRTPRetransmissionRequest) that
32  * comes from downstream (#GstRtpSession). When receiving a request it will
33  * look up the requested seqnum in its list of stored packets. If the packet
34  * is available, it will create a RTX packet according to RFC 4588 and send
35  * this as an auxiliary stream. RTX is SSRC-multiplexed
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include <gst/gst.h>
43 #include <gst/rtp/gstrtpbuffer.h>
44 #include <string.h>
45 #include <stdlib.h>
46
47 #include "gstrtprtxsend.h"
48
49 GST_DEBUG_CATEGORY_STATIC (gst_rtp_rtx_send_debug);
50 #define GST_CAT_DEFAULT gst_rtp_rtx_send_debug
51
52 #define DEFAULT_RTX_PAYLOAD_TYPE 0
53 #define DEFAULT_MAX_SIZE_TIME    0
54 #define DEFAULT_MAX_SIZE_PACKETS 100
55
56 enum
57 {
58   PROP_0,
59   PROP_SSRC_MAP,
60   PROP_PAYLOAD_TYPE_MAP,
61   PROP_MAX_SIZE_TIME,
62   PROP_MAX_SIZE_PACKETS,
63   PROP_NUM_RTX_REQUESTS,
64   PROP_NUM_RTX_PACKETS
65 };
66
67 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
68     GST_PAD_SRC,
69     GST_PAD_ALWAYS,
70     GST_STATIC_CAPS ("application/x-rtp")
71     );
72
73 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
74     GST_PAD_SINK,
75     GST_PAD_ALWAYS,
76     GST_STATIC_CAPS ("application/x-rtp, " "clock-rate = (int) [1, MAX]")
77     );
78
79 static gboolean gst_rtp_rtx_send_queue_check_full (GstDataQueue * queue,
80     guint visible, guint bytes, guint64 time, gpointer checkdata);
81
82 static gboolean gst_rtp_rtx_send_src_event (GstPad * pad, GstObject * parent,
83     GstEvent * event);
84 static gboolean gst_rtp_rtx_send_sink_event (GstPad * pad, GstObject * parent,
85     GstEvent * event);
86 static GstFlowReturn gst_rtp_rtx_send_chain (GstPad * pad, GstObject * parent,
87     GstBuffer * buffer);
88 static GstFlowReturn gst_rtp_rtx_send_chain_list (GstPad * pad,
89     GstObject * parent, GstBufferList * list);
90
91 static void gst_rtp_rtx_send_src_loop (GstRtpRtxSend * rtx);
92 static gboolean gst_rtp_rtx_send_activate_mode (GstPad * pad,
93     GstObject * parent, GstPadMode mode, gboolean active);
94
95 static GstStateChangeReturn gst_rtp_rtx_send_change_state (GstElement *
96     element, GstStateChange transition);
97
98 static void gst_rtp_rtx_send_set_property (GObject * object, guint prop_id,
99     const GValue * value, GParamSpec * pspec);
100 static void gst_rtp_rtx_send_get_property (GObject * object, guint prop_id,
101     GValue * value, GParamSpec * pspec);
102 static void gst_rtp_rtx_send_finalize (GObject * object);
103
104 G_DEFINE_TYPE (GstRtpRtxSend, gst_rtp_rtx_send, GST_TYPE_ELEMENT);
105
106 typedef struct
107 {
108   guint16 seqnum;
109   guint32 timestamp;
110   GstBuffer *buffer;
111 } BufferQueueItem;
112
113 static void
114 buffer_queue_item_free (BufferQueueItem * item)
115 {
116   gst_buffer_unref (item->buffer);
117   g_slice_free (BufferQueueItem, item);
118 }
119
120 typedef struct
121 {
122   guint32 rtx_ssrc;
123   guint16 seqnum_base, next_seqnum;
124   gint clock_rate;
125
126   /* history of rtp packets */
127   GSequence *queue;
128 } SSRCRtxData;
129
130 static SSRCRtxData *
131 ssrc_rtx_data_new (guint32 rtx_ssrc)
132 {
133   SSRCRtxData *data = g_slice_new0 (SSRCRtxData);
134
135   data->rtx_ssrc = rtx_ssrc;
136   data->next_seqnum = data->seqnum_base = g_random_int_range (0, G_MAXUINT16);
137   data->queue = g_sequence_new ((GDestroyNotify) buffer_queue_item_free);
138
139   return data;
140 }
141
142 static void
143 ssrc_rtx_data_free (SSRCRtxData * data)
144 {
145   g_sequence_free (data->queue);
146   g_slice_free (SSRCRtxData, data);
147 }
148
149 static void
150 gst_rtp_rtx_send_class_init (GstRtpRtxSendClass * klass)
151 {
152   GObjectClass *gobject_class;
153   GstElementClass *gstelement_class;
154
155   gobject_class = (GObjectClass *) klass;
156   gstelement_class = (GstElementClass *) klass;
157
158   gobject_class->get_property = gst_rtp_rtx_send_get_property;
159   gobject_class->set_property = gst_rtp_rtx_send_set_property;
160   gobject_class->finalize = gst_rtp_rtx_send_finalize;
161
162   g_object_class_install_property (gobject_class, PROP_SSRC_MAP,
163       g_param_spec_boxed ("ssrc-map", "SSRC Map",
164           "Map of SSRCs to their retransmission SSRCs for SSRC-multiplexed mode"
165           " (default = random)", GST_TYPE_STRUCTURE,
166           G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
167
168   g_object_class_install_property (gobject_class, PROP_PAYLOAD_TYPE_MAP,
169       g_param_spec_boxed ("payload-type-map", "Payload Type Map",
170           "Map of original payload types to their retransmission payload types",
171           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
172
173   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
174       g_param_spec_uint ("max-size-time", "Max Size Time",
175           "Amount of ms to queue (0 = unlimited)", 0, G_MAXUINT,
176           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
177
178   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_PACKETS,
179       g_param_spec_uint ("max-size-packets", "Max Size Packets",
180           "Amount of packets to queue (0 = unlimited)", 0, G_MAXINT16,
181           DEFAULT_MAX_SIZE_PACKETS,
182           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
183
184   g_object_class_install_property (gobject_class, PROP_NUM_RTX_REQUESTS,
185       g_param_spec_uint ("num-rtx-requests", "Num RTX Requests",
186           "Number of retransmission events received", 0, G_MAXUINT,
187           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
188
189   g_object_class_install_property (gobject_class, PROP_NUM_RTX_PACKETS,
190       g_param_spec_uint ("num-rtx-packets", "Num RTX Packets",
191           " Number of retransmission packets sent", 0, G_MAXUINT,
192           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
193
194   gst_element_class_add_pad_template (gstelement_class,
195       gst_static_pad_template_get (&src_factory));
196   gst_element_class_add_pad_template (gstelement_class,
197       gst_static_pad_template_get (&sink_factory));
198
199   gst_element_class_set_static_metadata (gstelement_class,
200       "RTP Retransmission Sender", "Codec",
201       "Retransmit RTP packets when needed, according to RFC4588",
202       "Julien Isorce <julien.isorce@collabora.co.uk>");
203
204   gstelement_class->change_state =
205       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_change_state);
206 }
207
208 static void
209 gst_rtp_rtx_send_reset (GstRtpRtxSend * rtx)
210 {
211   GST_OBJECT_LOCK (rtx);
212   gst_data_queue_flush (rtx->queue);
213   g_hash_table_remove_all (rtx->ssrc_data);
214   g_hash_table_remove_all (rtx->rtx_ssrcs);
215   rtx->num_rtx_requests = 0;
216   rtx->num_rtx_packets = 0;
217   GST_OBJECT_UNLOCK (rtx);
218 }
219
220 static void
221 gst_rtp_rtx_send_finalize (GObject * object)
222 {
223   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (object);
224
225   g_hash_table_unref (rtx->ssrc_data);
226   g_hash_table_unref (rtx->rtx_ssrcs);
227   if (rtx->external_ssrc_map)
228     gst_structure_free (rtx->external_ssrc_map);
229   g_hash_table_unref (rtx->rtx_pt_map);
230   if (rtx->rtx_pt_map_structure)
231     gst_structure_free (rtx->rtx_pt_map_structure);
232   g_object_unref (rtx->queue);
233
234   G_OBJECT_CLASS (gst_rtp_rtx_send_parent_class)->finalize (object);
235 }
236
237 static void
238 gst_rtp_rtx_send_init (GstRtpRtxSend * rtx)
239 {
240   GstElementClass *klass = GST_ELEMENT_GET_CLASS (rtx);
241
242   rtx->srcpad =
243       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
244           "src"), "src");
245   GST_PAD_SET_PROXY_CAPS (rtx->srcpad);
246   GST_PAD_SET_PROXY_ALLOCATION (rtx->srcpad);
247   gst_pad_set_event_function (rtx->srcpad,
248       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_src_event));
249   gst_pad_set_activatemode_function (rtx->srcpad,
250       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_activate_mode));
251   gst_element_add_pad (GST_ELEMENT (rtx), rtx->srcpad);
252
253   rtx->sinkpad =
254       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
255           "sink"), "sink");
256   GST_PAD_SET_PROXY_CAPS (rtx->sinkpad);
257   GST_PAD_SET_PROXY_ALLOCATION (rtx->sinkpad);
258   gst_pad_set_event_function (rtx->sinkpad,
259       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_sink_event));
260   gst_pad_set_chain_function (rtx->sinkpad,
261       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_chain));
262   gst_pad_set_chain_list_function (rtx->sinkpad,
263       GST_DEBUG_FUNCPTR (gst_rtp_rtx_send_chain_list));
264   gst_element_add_pad (GST_ELEMENT (rtx), rtx->sinkpad);
265
266   rtx->queue = gst_data_queue_new (gst_rtp_rtx_send_queue_check_full, NULL,
267       NULL, rtx);
268   rtx->ssrc_data = g_hash_table_new_full (g_direct_hash, g_direct_equal,
269       NULL, (GDestroyNotify) ssrc_rtx_data_free);
270   rtx->rtx_ssrcs = g_hash_table_new (g_direct_hash, g_direct_equal);
271   rtx->rtx_pt_map = g_hash_table_new (g_direct_hash, g_direct_equal);
272
273   rtx->max_size_time = DEFAULT_MAX_SIZE_TIME;
274   rtx->max_size_packets = DEFAULT_MAX_SIZE_PACKETS;
275 }
276
277 static void
278 gst_rtp_rtx_send_set_flushing (GstRtpRtxSend * rtx, gboolean flush)
279 {
280   GST_OBJECT_LOCK (rtx);
281   gst_data_queue_set_flushing (rtx->queue, flush);
282   gst_data_queue_flush (rtx->queue);
283   GST_OBJECT_UNLOCK (rtx);
284 }
285
286 static gboolean
287 gst_rtp_rtx_send_queue_check_full (GstDataQueue * queue,
288     guint visible, guint bytes, guint64 time, gpointer checkdata)
289 {
290   return FALSE;
291 }
292
293 static void
294 gst_rtp_rtx_data_queue_item_free (gpointer item)
295 {
296   GstDataQueueItem *data = item;
297   if (data->object)
298     gst_mini_object_unref (data->object);
299   g_slice_free (GstDataQueueItem, data);
300 }
301
302 static gboolean
303 gst_rtp_rtx_send_push_out (GstRtpRtxSend * rtx, gpointer object)
304 {
305   GstDataQueueItem *data;
306   gboolean success;
307
308   data = g_slice_new0 (GstDataQueueItem);
309   data->object = GST_MINI_OBJECT (object);
310   data->size = 1;
311   data->duration = 1;
312   data->visible = TRUE;
313   data->destroy = gst_rtp_rtx_data_queue_item_free;
314
315   success = gst_data_queue_push (rtx->queue, data);
316
317   if (!success)
318     data->destroy (data);
319
320   return success;
321 }
322
323 static guint32
324 gst_rtp_rtx_send_choose_ssrc (GstRtpRtxSend * rtx, guint32 choice,
325     gboolean consider_choice)
326 {
327   guint32 ssrc = consider_choice ? choice : g_random_int ();
328
329   /* make sure to be different than any other */
330   while (g_hash_table_contains (rtx->ssrc_data, GUINT_TO_POINTER (ssrc)) ||
331       g_hash_table_contains (rtx->rtx_ssrcs, GUINT_TO_POINTER (ssrc))) {
332     ssrc = g_random_int ();
333   }
334
335   return ssrc;
336 }
337
338 static SSRCRtxData *
339 gst_rtp_rtx_send_get_ssrc_data (GstRtpRtxSend * rtx, guint32 ssrc)
340 {
341   SSRCRtxData *data;
342   guint32 rtx_ssrc = 0;
343   gboolean consider = FALSE;
344
345   if (G_UNLIKELY (!g_hash_table_contains (rtx->ssrc_data,
346               GUINT_TO_POINTER (ssrc)))) {
347     if (rtx->external_ssrc_map) {
348       gchar *ssrc_str;
349       ssrc_str = g_strdup_printf ("%" G_GUINT32_FORMAT, ssrc);
350       consider = gst_structure_get_uint (rtx->external_ssrc_map, ssrc_str,
351           &rtx_ssrc);
352       g_free (ssrc_str);
353     }
354     rtx_ssrc = gst_rtp_rtx_send_choose_ssrc (rtx, rtx_ssrc, consider);
355     data = ssrc_rtx_data_new (rtx_ssrc);
356     g_hash_table_insert (rtx->ssrc_data, GUINT_TO_POINTER (ssrc), data);
357     g_hash_table_insert (rtx->rtx_ssrcs, GUINT_TO_POINTER (rtx_ssrc),
358         GUINT_TO_POINTER (ssrc));
359   } else {
360     data = g_hash_table_lookup (rtx->ssrc_data, GUINT_TO_POINTER (ssrc));
361   }
362   return data;
363 }
364
365 /* Copy fixed header and extension. Add OSN before to copy payload
366  * Copy memory to avoid to manually copy each rtp buffer field.
367  */
368 static GstBuffer *
369 gst_rtp_rtx_buffer_new (GstRtpRtxSend * rtx, GstBuffer * buffer)
370 {
371   GstMemory *mem = NULL;
372   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
373   GstRTPBuffer new_rtp = GST_RTP_BUFFER_INIT;
374   GstBuffer *new_buffer = gst_buffer_new ();
375   GstMapInfo map;
376   guint payload_len = 0;
377   SSRCRtxData *data;
378   guint32 ssrc;
379   guint16 seqnum;
380   guint8 fmtp;
381
382   gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp);
383
384   /* get needed data from GstRtpRtxSend */
385   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
386   data = gst_rtp_rtx_send_get_ssrc_data (rtx, ssrc);
387   ssrc = data->rtx_ssrc;
388   seqnum = data->next_seqnum++;
389   fmtp = GPOINTER_TO_UINT (g_hash_table_lookup (rtx->rtx_pt_map,
390           GUINT_TO_POINTER (gst_rtp_buffer_get_payload_type (&rtp))));
391
392   GST_DEBUG_OBJECT (rtx,
393       "retransmit seqnum: %" G_GUINT16_FORMAT ", ssrc: %" G_GUINT32_FORMAT,
394       seqnum, ssrc);
395
396   /* gst_rtp_buffer_map does not map the payload so do it now */
397   gst_rtp_buffer_get_payload (&rtp);
398
399   /* copy fixed header */
400   mem = gst_memory_copy (rtp.map[0].memory, 0, rtp.size[0]);
401   gst_buffer_append_memory (new_buffer, mem);
402
403   /* copy extension if any */
404   if (rtp.size[1]) {
405     mem = gst_memory_copy (rtp.map[1].memory, 0, rtp.size[1]);
406     gst_buffer_append_memory (new_buffer, mem);
407   }
408
409   /* copy payload and add OSN just before */
410   payload_len = 2 + rtp.size[2];
411   mem = gst_allocator_alloc (NULL, payload_len, NULL);
412
413   gst_memory_map (mem, &map, GST_MAP_WRITE);
414   GST_WRITE_UINT16_BE (map.data, gst_rtp_buffer_get_seq (&rtp));
415   if (rtp.size[2])
416     memcpy (map.data + 2, rtp.data[2], rtp.size[2]);
417   gst_memory_unmap (mem, &map);
418   gst_buffer_append_memory (new_buffer, mem);
419
420   /* everything needed is copied */
421   gst_rtp_buffer_unmap (&rtp);
422
423   /* set ssrc, seqnum and fmtp */
424   gst_rtp_buffer_map (new_buffer, GST_MAP_WRITE, &new_rtp);
425   gst_rtp_buffer_set_ssrc (&new_rtp, ssrc);
426   gst_rtp_buffer_set_seq (&new_rtp, seqnum);
427   gst_rtp_buffer_set_payload_type (&new_rtp, fmtp);
428   /* RFC 4588: let other elements do the padding, as normal */
429   gst_rtp_buffer_set_padding (&new_rtp, FALSE);
430   gst_rtp_buffer_unmap (&new_rtp);
431
432   /* Copy over timestamps */
433   gst_buffer_copy_into (new_buffer, buffer, GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
434
435   return new_buffer;
436 }
437
438 static gint
439 buffer_queue_items_cmp (BufferQueueItem * a, BufferQueueItem * b,
440     gpointer user_data)
441 {
442   /* gst_rtp_buffer_compare_seqnum returns the opposite of what we want,
443    * it returns negative when seqnum1 > seqnum2 and we want negative
444    * when b > a, i.e. a is smaller, so it comes first in the sequence */
445   return gst_rtp_buffer_compare_seqnum (b->seqnum, a->seqnum);
446 }
447
448 static gboolean
449 gst_rtp_rtx_send_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
450 {
451   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (parent);
452   gboolean res;
453
454   switch (GST_EVENT_TYPE (event)) {
455     case GST_EVENT_CUSTOM_UPSTREAM:
456     {
457       const GstStructure *s = gst_event_get_structure (event);
458
459       /* This event usually comes from the downstream gstrtpsession */
460       if (gst_structure_has_name (s, "GstRTPRetransmissionRequest")) {
461         guint seqnum = 0;
462         guint ssrc = 0;
463         GstBuffer *rtx_buf = NULL;
464
465         /* retrieve seqnum of the packet that need to be retransmitted */
466         if (!gst_structure_get_uint (s, "seqnum", &seqnum))
467           seqnum = -1;
468
469         /* retrieve ssrc of the packet that need to be retransmitted */
470         if (!gst_structure_get_uint (s, "ssrc", &ssrc))
471           ssrc = -1;
472
473         GST_DEBUG_OBJECT (rtx,
474             "request seqnum: %" G_GUINT32_FORMAT ", ssrc: %" G_GUINT32_FORMAT,
475             seqnum, ssrc);
476
477         GST_OBJECT_LOCK (rtx);
478         /* check if request is for us */
479         if (g_hash_table_contains (rtx->ssrc_data, GUINT_TO_POINTER (ssrc))) {
480           SSRCRtxData *data;
481           GSequenceIter *iter;
482           BufferQueueItem search_item;
483
484           /* update statistics */
485           ++rtx->num_rtx_requests;
486
487           data = gst_rtp_rtx_send_get_ssrc_data (rtx, ssrc);
488
489           search_item.seqnum = seqnum;
490           iter = g_sequence_lookup (data->queue, &search_item,
491               (GCompareDataFunc) buffer_queue_items_cmp, NULL);
492           if (iter) {
493             BufferQueueItem *item = g_sequence_get (iter);
494             GST_DEBUG_OBJECT (rtx, "found %" G_GUINT16_FORMAT, item->seqnum);
495             rtx_buf = gst_rtp_rtx_buffer_new (rtx, item->buffer);
496           }
497         }
498         GST_OBJECT_UNLOCK (rtx);
499
500         if (rtx_buf)
501           gst_rtp_rtx_send_push_out (rtx, rtx_buf);
502
503         gst_event_unref (event);
504         res = TRUE;
505
506         /* This event usually comes from the downstream gstrtpsession */
507       } else if (gst_structure_has_name (s, "GstRTPCollision")) {
508         guint ssrc = 0;
509
510         if (!gst_structure_get_uint (s, "ssrc", &ssrc))
511           ssrc = -1;
512
513         GST_DEBUG_OBJECT (rtx, "collision ssrc: %" G_GUINT32_FORMAT, ssrc);
514
515         GST_OBJECT_LOCK (rtx);
516
517         /* choose another ssrc for our retransmited stream */
518         if (g_hash_table_contains (rtx->rtx_ssrcs, GUINT_TO_POINTER (ssrc))) {
519           guint master_ssrc;
520           SSRCRtxData *data;
521
522           master_ssrc = GPOINTER_TO_UINT (g_hash_table_lookup (rtx->rtx_ssrcs,
523                   GUINT_TO_POINTER (ssrc)));
524           data = gst_rtp_rtx_send_get_ssrc_data (rtx, master_ssrc);
525
526           /* change rtx_ssrc and update the reverse map */
527           data->rtx_ssrc = gst_rtp_rtx_send_choose_ssrc (rtx, 0, FALSE);
528           g_hash_table_remove (rtx->rtx_ssrcs, GUINT_TO_POINTER (ssrc));
529           g_hash_table_insert (rtx->rtx_ssrcs,
530               GUINT_TO_POINTER (data->rtx_ssrc),
531               GUINT_TO_POINTER (master_ssrc));
532
533           GST_OBJECT_UNLOCK (rtx);
534
535           /* no need to forward to payloader because we make sure to have
536            * a different ssrc
537            */
538           gst_event_unref (event);
539           res = TRUE;
540         } else {
541           /* if master ssrc has collided, remove it from our data, as it
542            * is not going to be used any longer */
543           if (g_hash_table_contains (rtx->ssrc_data, GUINT_TO_POINTER (ssrc))) {
544             SSRCRtxData *data;
545             data = gst_rtp_rtx_send_get_ssrc_data (rtx, ssrc);
546             g_hash_table_remove (rtx->rtx_ssrcs,
547                 GUINT_TO_POINTER (data->rtx_ssrc));
548             g_hash_table_remove (rtx->ssrc_data, GUINT_TO_POINTER (ssrc));
549           }
550
551           GST_OBJECT_UNLOCK (rtx);
552
553           /* forward event to payloader in case collided ssrc is
554            * master stream */
555           res = gst_pad_event_default (pad, parent, event);
556         }
557       } else {
558         res = gst_pad_event_default (pad, parent, event);
559       }
560       break;
561     }
562     default:
563       res = gst_pad_event_default (pad, parent, event);
564       break;
565   }
566   return res;
567 }
568
569 static gboolean
570 gst_rtp_rtx_send_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
571 {
572   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (parent);
573
574   switch (GST_EVENT_TYPE (event)) {
575     case GST_EVENT_FLUSH_START:
576       gst_pad_push_event (rtx->srcpad, event);
577       gst_rtp_rtx_send_set_flushing (rtx, TRUE);
578       gst_pad_pause_task (rtx->srcpad);
579       return TRUE;
580     case GST_EVENT_FLUSH_STOP:
581       gst_pad_push_event (rtx->srcpad, event);
582       gst_rtp_rtx_send_set_flushing (rtx, FALSE);
583       gst_pad_start_task (rtx->srcpad,
584           (GstTaskFunction) gst_rtp_rtx_send_src_loop, rtx, NULL);
585       return TRUE;
586     case GST_EVENT_EOS:
587       GST_INFO_OBJECT (rtx, "Got EOS - enqueueing it");
588       gst_rtp_rtx_send_push_out (rtx, event);
589       return TRUE;
590     case GST_EVENT_CAPS:
591     {
592       GstCaps *caps;
593       GstStructure *s;
594       guint ssrc;
595       gint payload;
596       gpointer rtx_payload;
597       SSRCRtxData *data;
598
599       gst_event_parse_caps (event, &caps);
600
601       s = gst_caps_get_structure (caps, 0);
602       if (!gst_structure_get_uint (s, "ssrc", &ssrc))
603         ssrc = -1;
604       if (!gst_structure_get_int (s, "payload", &payload))
605         payload = -1;
606
607       if (payload == -1)
608         GST_WARNING_OBJECT (rtx, "No payload in caps");
609
610       GST_OBJECT_LOCK (rtx);
611       data = gst_rtp_rtx_send_get_ssrc_data (rtx, ssrc);
612       if (!g_hash_table_lookup_extended (rtx->rtx_pt_map,
613               GUINT_TO_POINTER (payload), NULL, &rtx_payload))
614         rtx_payload = GINT_TO_POINTER (-1);
615
616       if (GPOINTER_TO_INT (rtx_payload) == -1 && payload != -1)
617         GST_WARNING_OBJECT (rtx, "Payload %d not in rtx-pt-map", payload);
618
619       GST_DEBUG_OBJECT (rtx,
620           "got caps for payload: %d->%d, ssrc: %u->%" G_GUINT32_FORMAT ": %"
621           GST_PTR_FORMAT, payload, GPOINTER_TO_INT (rtx_payload), ssrc,
622           data->rtx_ssrc, caps);
623
624       gst_structure_get_int (s, "clock-rate", &data->clock_rate);
625
626       /* The session might need to know the RTX ssrc */
627       caps = gst_caps_copy (caps);
628       gst_caps_set_simple (caps, "rtx-ssrc", G_TYPE_UINT, data->rtx_ssrc,
629           "rtx-seqnum-offset", G_TYPE_UINT, data->seqnum_base, NULL);
630
631       if (GPOINTER_TO_INT (rtx_payload) != -1)
632         gst_caps_set_simple (caps, "rtx-payload", G_TYPE_INT,
633             GPOINTER_TO_INT (rtx_payload), NULL);
634
635       GST_DEBUG_OBJECT (rtx, "got clock-rate from caps: %d for ssrc: %u",
636           data->clock_rate, ssrc);
637       GST_OBJECT_UNLOCK (rtx);
638
639       gst_event_unref (event);
640       event = gst_event_new_caps (caps);
641       gst_caps_unref (caps);
642       break;
643     }
644     default:
645       break;
646   }
647   return gst_pad_event_default (pad, parent, event);
648 }
649
650 /* like rtp_jitter_buffer_get_ts_diff() */
651 static guint32
652 gst_rtp_rtx_send_get_ts_diff (SSRCRtxData * data)
653 {
654   guint64 high_ts, low_ts;
655   BufferQueueItem *high_buf, *low_buf;
656   guint32 result;
657
658   high_buf =
659       g_sequence_get (g_sequence_iter_prev (g_sequence_get_end_iter
660           (data->queue)));
661   low_buf = g_sequence_get (g_sequence_get_begin_iter (data->queue));
662
663   if (!high_buf || !low_buf || high_buf == low_buf)
664     return 0;
665
666   high_ts = high_buf->timestamp;
667   low_ts = low_buf->timestamp;
668
669   /* it needs to work if ts wraps */
670   if (high_ts >= low_ts) {
671     result = (guint32) (high_ts - low_ts);
672   } else {
673     result = (guint32) (high_ts + G_MAXUINT32 + 1 - low_ts);
674   }
675
676   /* return value in ms instead of clock ticks */
677   return (guint32) gst_util_uint64_scale_int (result, 1000, data->clock_rate);
678 }
679
680 /* Must be called with lock */
681 static void
682 process_buffer (GstRtpRtxSend * rtx, GstBuffer * buffer)
683 {
684   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
685   BufferQueueItem *item;
686   SSRCRtxData *data;
687   guint16 seqnum;
688   guint8 payload_type;
689   guint32 ssrc, rtptime;
690
691   /* read the information we want from the buffer */
692   gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp);
693   seqnum = gst_rtp_buffer_get_seq (&rtp);
694   payload_type = gst_rtp_buffer_get_payload_type (&rtp);
695   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
696   rtptime = gst_rtp_buffer_get_timestamp (&rtp);
697   gst_rtp_buffer_unmap (&rtp);
698
699   GST_LOG_OBJECT (rtx,
700       "Processing buffer seqnum: %" G_GUINT16_FORMAT ", ssrc: %"
701       G_GUINT32_FORMAT, seqnum, ssrc);
702
703   /* do not store the buffer if it's payload type is unknown */
704   if (g_hash_table_contains (rtx->rtx_pt_map, GUINT_TO_POINTER (payload_type))) {
705     data = gst_rtp_rtx_send_get_ssrc_data (rtx, ssrc);
706
707     /* add current rtp buffer to queue history */
708     item = g_slice_new0 (BufferQueueItem);
709     item->seqnum = seqnum;
710     item->timestamp = rtptime;
711     item->buffer = gst_buffer_ref (buffer);
712     g_sequence_append (data->queue, item);
713
714     /* remove oldest packets from history if they are too many */
715     if (rtx->max_size_packets) {
716       while (g_sequence_get_length (data->queue) > rtx->max_size_packets)
717         g_sequence_remove (g_sequence_get_begin_iter (data->queue));
718     }
719     if (rtx->max_size_time) {
720       while (gst_rtp_rtx_send_get_ts_diff (data) > rtx->max_size_time)
721         g_sequence_remove (g_sequence_get_begin_iter (data->queue));
722     }
723   }
724 }
725
726 static GstFlowReturn
727 gst_rtp_rtx_send_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
728 {
729   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (parent);
730   GstFlowReturn ret;
731
732   GST_OBJECT_LOCK (rtx);
733   process_buffer (rtx, buffer);
734   GST_OBJECT_UNLOCK (rtx);
735   ret = gst_pad_push (rtx->srcpad, buffer);
736
737   return ret;
738 }
739
740 static gboolean
741 process_buffer_from_list (GstBuffer ** buffer, guint idx, gpointer user_data)
742 {
743   process_buffer (user_data, *buffer);
744   return TRUE;
745 }
746
747 static GstFlowReturn
748 gst_rtp_rtx_send_chain_list (GstPad * pad, GstObject * parent,
749     GstBufferList * list)
750 {
751   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (parent);
752   GstFlowReturn ret;
753
754   GST_OBJECT_LOCK (rtx);
755   gst_buffer_list_foreach (list, process_buffer_from_list, rtx);
756   GST_OBJECT_UNLOCK (rtx);
757
758   ret = gst_pad_push_list (rtx->srcpad, list);
759
760   return ret;
761 }
762
763 static void
764 gst_rtp_rtx_send_src_loop (GstRtpRtxSend * rtx)
765 {
766   GstDataQueueItem *data;
767
768   if (gst_data_queue_pop (rtx->queue, &data)) {
769     GST_LOG_OBJECT (rtx, "pushing rtx buffer %p", data->object);
770
771     if (G_LIKELY (GST_IS_BUFFER (data->object))) {
772       gst_pad_push (rtx->srcpad, GST_BUFFER (data->object));
773
774       GST_OBJECT_LOCK (rtx);
775       rtx->num_rtx_packets++;
776       GST_OBJECT_UNLOCK (rtx);
777     } else if (GST_IS_EVENT (data->object)) {
778       gst_pad_push_event (rtx->srcpad, GST_EVENT (data->object));
779
780       /* after EOS, we should not send any more buffers,
781        * even if there are more requests coming in */
782       if (GST_EVENT_TYPE (data->object) == GST_EVENT_EOS) {
783         gst_rtp_rtx_send_set_flushing (rtx, TRUE);
784       }
785     } else {
786       g_assert_not_reached ();
787     }
788
789     data->object = NULL;        /* we no longer own that object */
790     data->destroy (data);
791   } else {
792     GST_LOG_OBJECT (rtx, "flushing");
793     gst_pad_pause_task (rtx->srcpad);
794   }
795 }
796
797 static gboolean
798 gst_rtp_rtx_send_activate_mode (GstPad * pad, GstObject * parent,
799     GstPadMode mode, gboolean active)
800 {
801   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (parent);
802   gboolean ret = FALSE;
803
804   switch (mode) {
805     case GST_PAD_MODE_PUSH:
806       if (active) {
807         gst_rtp_rtx_send_set_flushing (rtx, FALSE);
808         ret = gst_pad_start_task (rtx->srcpad,
809             (GstTaskFunction) gst_rtp_rtx_send_src_loop, rtx, NULL);
810       } else {
811         gst_rtp_rtx_send_set_flushing (rtx, TRUE);
812         ret = gst_pad_stop_task (rtx->srcpad);
813       }
814       GST_INFO_OBJECT (rtx, "activate_mode: active %d, ret %d", active, ret);
815       break;
816     default:
817       break;
818   }
819   return ret;
820 }
821
822 static void
823 gst_rtp_rtx_send_get_property (GObject * object,
824     guint prop_id, GValue * value, GParamSpec * pspec)
825 {
826   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (object);
827
828   switch (prop_id) {
829     case PROP_PAYLOAD_TYPE_MAP:
830       GST_OBJECT_LOCK (rtx);
831       g_value_set_boxed (value, rtx->rtx_pt_map_structure);
832       GST_OBJECT_UNLOCK (rtx);
833       break;
834     case PROP_MAX_SIZE_TIME:
835       GST_OBJECT_LOCK (rtx);
836       g_value_set_uint (value, rtx->max_size_time);
837       GST_OBJECT_UNLOCK (rtx);
838       break;
839     case PROP_MAX_SIZE_PACKETS:
840       GST_OBJECT_LOCK (rtx);
841       g_value_set_uint (value, rtx->max_size_packets);
842       GST_OBJECT_UNLOCK (rtx);
843       break;
844     case PROP_NUM_RTX_REQUESTS:
845       GST_OBJECT_LOCK (rtx);
846       g_value_set_uint (value, rtx->num_rtx_requests);
847       GST_OBJECT_UNLOCK (rtx);
848       break;
849     case PROP_NUM_RTX_PACKETS:
850       GST_OBJECT_LOCK (rtx);
851       g_value_set_uint (value, rtx->num_rtx_packets);
852       GST_OBJECT_UNLOCK (rtx);
853       break;
854     default:
855       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
856       break;
857   }
858 }
859
860 static gboolean
861 structure_to_hash_table (GQuark field_id, const GValue * value, gpointer hash)
862 {
863   const gchar *field_str;
864   guint field_uint;
865   guint value_uint;
866
867   field_str = g_quark_to_string (field_id);
868   field_uint = atoi (field_str);
869   value_uint = g_value_get_uint (value);
870   g_hash_table_insert ((GHashTable *) hash, GUINT_TO_POINTER (field_uint),
871       GUINT_TO_POINTER (value_uint));
872
873   return TRUE;
874 }
875
876 static void
877 gst_rtp_rtx_send_set_property (GObject * object,
878     guint prop_id, const GValue * value, GParamSpec * pspec)
879 {
880   GstRtpRtxSend *rtx = GST_RTP_RTX_SEND (object);
881
882   switch (prop_id) {
883     case PROP_SSRC_MAP:
884       GST_OBJECT_LOCK (rtx);
885       if (rtx->external_ssrc_map)
886         gst_structure_free (rtx->external_ssrc_map);
887       rtx->external_ssrc_map = g_value_dup_boxed (value);
888       GST_OBJECT_UNLOCK (rtx);
889       break;
890     case PROP_PAYLOAD_TYPE_MAP:
891       GST_OBJECT_LOCK (rtx);
892       if (rtx->rtx_pt_map_structure)
893         gst_structure_free (rtx->rtx_pt_map_structure);
894       rtx->rtx_pt_map_structure = g_value_dup_boxed (value);
895       g_hash_table_remove_all (rtx->rtx_pt_map);
896       gst_structure_foreach (rtx->rtx_pt_map_structure, structure_to_hash_table,
897           rtx->rtx_pt_map);
898       GST_OBJECT_UNLOCK (rtx);
899       break;
900     case PROP_MAX_SIZE_TIME:
901       GST_OBJECT_LOCK (rtx);
902       rtx->max_size_time = g_value_get_uint (value);
903       GST_OBJECT_UNLOCK (rtx);
904       break;
905     case PROP_MAX_SIZE_PACKETS:
906       GST_OBJECT_LOCK (rtx);
907       rtx->max_size_packets = g_value_get_uint (value);
908       GST_OBJECT_UNLOCK (rtx);
909       break;
910     default:
911       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
912       break;
913   }
914 }
915
916 static GstStateChangeReturn
917 gst_rtp_rtx_send_change_state (GstElement * element, GstStateChange transition)
918 {
919   GstStateChangeReturn ret;
920   GstRtpRtxSend *rtx;
921
922   rtx = GST_RTP_RTX_SEND (element);
923
924   switch (transition) {
925     default:
926       break;
927   }
928
929   ret =
930       GST_ELEMENT_CLASS (gst_rtp_rtx_send_parent_class)->change_state (element,
931       transition);
932
933   switch (transition) {
934     case GST_STATE_CHANGE_PAUSED_TO_READY:
935       gst_rtp_rtx_send_reset (rtx);
936       break;
937     default:
938       break;
939   }
940
941   return ret;
942 }
943
944 gboolean
945 gst_rtp_rtx_send_plugin_init (GstPlugin * plugin)
946 {
947   GST_DEBUG_CATEGORY_INIT (gst_rtp_rtx_send_debug, "rtprtxsend", 0,
948       "rtp retransmission sender");
949
950   return gst_element_register (plugin, "rtprtxsend", GST_RANK_NONE,
951       GST_TYPE_RTP_RTX_SEND);
952 }