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