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