Merge branch 'plugin-move-rtp-h265'
[platform/upstream/gst-plugins-good.git] / gst / rtpmanager / gstrtprtxreceive.c
1 /* RTP Retransmission receiver element for GStreamer
2  *
3  * gstrtprtxreceive.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-rtprtxreceive
26  * @see_also: rtprtxsend, rtpsession, rtpjitterbuffer
27  *
28  * The receiver will listen to the custom retransmission events from the
29  * downstream jitterbuffer and will remember the SSRC1 of the stream and
30  * seqnum that was requested. When it sees a packet with one of the stored
31  * seqnum, it associates the SSRC2 of the stream with the SSRC1 of the
32  * master stream. From then it knows that SSRC2 is the retransmission
33  * stream of SSRC1. This algorithm is stated in RFC 4588. For this
34  * algorithm to work, RFC4588 also states that no two pending retransmission
35  * requests can exist for the same seqnum and different SSRCs or else it
36  * would be impossible to associate the retransmission with the original
37  * requester SSRC.
38  * When the RTX receiver has associated the retransmission packets,
39  * it can depayload and forward them to the source pad of the element.
40  * RTX is SSRC-multiplexed. See #GstRtpRtxSend
41  *
42  * <refsect2>
43  * <title>Example pipelines</title>
44  * |[
45  * gst-launch-1.0 rtpsession name=rtpsession \
46  *         audiotestsrc ! speexenc ! rtpspeexpay pt=97 ! rtprtxsend rtx-payload-type=99 ! \
47  *             identity drop-probability=0.1 ! rtpsession.send_rtp_sink \
48  *             rtpsession.send_rtp_src ! udpsink host="127.0.0.1" port=5000 \
49  *         udpsrc port=5001 ! rtpsession.recv_rtcp_sink \
50  *         rtpsession.send_rtcp_src ! udpsink host="127.0.0.1" port=5002 sync=false async=false
51  * ]| Send audio stream through port 5000. (5001 and 5002 are just the rtcp link with the receiver)
52  * |[
53  * gst-launch-1.0 rtpsession name=rtpsession \
54  *         udpsrc port=5000 caps="application/x-rtp,media=(string)audio,clock-rate=(int)44100,encoding-name=(string)SPEEX,encoding-params=(string)1,octet-align=(string)1" ! \
55  *             rtpsession.recv_rtp_sink \
56  *             rtpsession.recv_rtp_src ! rtprtxreceive rtx-payload-types="99" ! rtpjitterbuffer do-retransmission=true ! rtpspeexdepay ! \
57  *             speexdec ! audioconvert ! autoaudiosink \
58  *         rtpsession.send_rtcp_src ! udpsink host="127.0.0.1" port=5001 \
59  *         udpsrc port=5002 ! rtpsession.recv_rtcp_sink sync=fakse async=false
60  * ]| Receive audio stream from port 5000. (5001 and 5002 are just the rtcp link with the sender)
61  * On sender side make sure to use a different payload type for the stream and
62  * its associated retransmission stream (see #GstRtpRtxSend). Note that several retransmission streams can
63  * have the same payload type so this is not deterministic. Actually the
64  * rtprtxreceiver element does the association using seqnum values.
65  * On receiver side set all the retransmission payload types (Those informations are retrieve
66  * through SDP).
67  * You should still hear a clear sound when setting drop-probability to something greater than 0.
68  * The rtpjitterbuffer will generate a custom upstream event GstRTPRetransmissionRequest when
69  * it assumes that one packet is missing. Then this request is translated to a FB NACK in the rtcp link
70  * Finally the rtpsession of the sender side re-convert it in a GstRTPRetransmissionRequest that will
71  * be handle by rtprtxsend.
72  * When increasing this value it may be possible that even the retransmission stream would be dropped
73  * so the receiver will ask to resend the packets again and again until it actually receive them.
74  * If the value is too high the rtprtxsend will not be able to retrieve the packet in its list of
75  * stored packets. For learning purpose you could try to increase the max-size-packets or max-size-time
76  * rtprtxsender's properties.
77  * Also note that you should use rtprtxsend through rtpbin and its set-aux-send property. See #GstRtpBin.
78  * |[
79  * gst-launch-1.0 rtpsession name=rtpsession0 \
80  *         audiotestsrc wave=0 ! speexenc ! rtpspeexpay pt=97 ! rtprtxsend rtx-payload-type=99 seqnum-offset=1 ! \
81  *             identity drop-probability=0.1 ! rtpsession0.send_rtp_sink \
82  *             rtpsession0.send_rtp_src ! udpsink host="127.0.0.1" port=5000 \
83  *         udpsrc port=5001 ! rtpsession0.recv_rtcp_sink \
84  *         rtpsession0.send_rtcp_src ! udpsink host="127.0.0.1" port=5002 sync=false async=false \
85  *                rtpsession name=rtpsession1 \
86  *         audiotestsrc wave=0 ! speexenc ! rtpspeexpay pt=97 ! rtprtxsend rtx-payload-type=99 seqnum-offset=10 ! \
87  *             identity drop-probability=0.1 ! rtpsession1.send_rtp_sink \
88  *             rtpsession1.send_rtp_src ! udpsink host="127.0.0.1" port=5000 \
89  *         udpsrc port=5004 ! rtpsession1.recv_rtcp_sink \
90  *         rtpsession1.send_rtcp_src ! udpsink host="127.0.0.1" port=5002 sync=false async=false
91  * ]| Send two audio streams to port 5000.
92  * |[
93  * gst-launch-1.0 rtpsession name=rtpsession
94  *         udpsrc port=5000 caps="application/x-rtp,media=(string)audio,clock-rate=(int)44100,encoding-name=(string)SPEEX,encoding-params=(string)1,octet-align=(string)1" ! \
95  *             rtpsession.recv_rtp_sink \
96  *             rtpsession.recv_rtp_src ! rtprtxreceive rtx-payload-types="99" ! rtpssrcdemux name=demux \
97  *             demux. ! queue ! rtpjitterbuffer do-retransmission=true ! rtpspeexdepay ! speexdec ! audioconvert ! autoaudiosink \
98  *             demux. ! queue ! rtpjitterbuffer do-retransmission=true ! rtpspeexdepay ! speexdec ! audioconvert ! autoaudiosink \
99  *         rtpsession.send_rtcp_src ! ! tee name=t ! queue ! udpsink host="127.0.0.1" port=5001 t. ! queue ! udpsink host="127.0.0.1" port=5004 \
100  *         udpsrc port=5002 ! rtpsession.recv_rtcp_sink sync=fakse async=false
101  * ]| Receive audio stream from port 5000.
102  * On sender side the two streams have the same payload type for master streams, Same about retransmission streams.
103  * The streams are sent to the network through two distincts sessions.
104  * But we need to set a different seqnum-offset to make sure their seqnum navigate at a different rate like in concrete cases.
105  * We could also choose the same seqnum offset but we would require to set a different initial seqnum value.
106  * This is also why the rtprtxreceive can succeed to do the association between master and retransmission stream.
107  * On receiver side the same session is used to receive the two streams. So the rtpssrcdemux is here to demultiplex
108  * those two streams. The rtprtxreceive is responsible for reconstructing the original packets from the two retransmission streams.
109  * You can play with the drop-probability value for one or both streams.
110  * You should hear a clear sound. (after a few seconds the two streams wave feel synchronized)
111  * </refsect2>
112  */
113
114 #ifdef HAVE_CONFIG_H
115 #include "config.h"
116 #endif
117
118 #include <gst/gst.h>
119 #include <gst/rtp/gstrtpbuffer.h>
120 #include <string.h>
121 #include <stdlib.h>
122
123 #include "gstrtprtxreceive.h"
124
125 #define ASSOC_TIMEOUT (GST_SECOND)
126
127 GST_DEBUG_CATEGORY_STATIC (gst_rtp_rtx_receive_debug);
128 #define GST_CAT_DEFAULT gst_rtp_rtx_receive_debug
129
130 enum
131 {
132   PROP_0,
133   PROP_PAYLOAD_TYPE_MAP,
134   PROP_NUM_RTX_REQUESTS,
135   PROP_NUM_RTX_PACKETS,
136   PROP_NUM_RTX_ASSOC_PACKETS
137 };
138
139 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
140     GST_PAD_SRC,
141     GST_PAD_ALWAYS,
142     GST_STATIC_CAPS ("application/x-rtp")
143     );
144
145 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
146     GST_PAD_SINK,
147     GST_PAD_ALWAYS,
148     GST_STATIC_CAPS ("application/x-rtp")
149     );
150
151 static gboolean gst_rtp_rtx_receive_src_event (GstPad * pad, GstObject * parent,
152     GstEvent * event);
153 static GstFlowReturn gst_rtp_rtx_receive_chain (GstPad * pad,
154     GstObject * parent, GstBuffer * buffer);
155
156 static GstStateChangeReturn gst_rtp_rtx_receive_change_state (GstElement *
157     element, GstStateChange transition);
158
159 static void gst_rtp_rtx_receive_set_property (GObject * object, guint prop_id,
160     const GValue * value, GParamSpec * pspec);
161 static void gst_rtp_rtx_receive_get_property (GObject * object, guint prop_id,
162     GValue * value, GParamSpec * pspec);
163 static void gst_rtp_rtx_receive_finalize (GObject * object);
164
165 G_DEFINE_TYPE (GstRtpRtxReceive, gst_rtp_rtx_receive, GST_TYPE_ELEMENT);
166
167 static void
168 gst_rtp_rtx_receive_class_init (GstRtpRtxReceiveClass * klass)
169 {
170   GObjectClass *gobject_class;
171   GstElementClass *gstelement_class;
172
173   gobject_class = (GObjectClass *) klass;
174   gstelement_class = (GstElementClass *) klass;
175
176   gobject_class->get_property = gst_rtp_rtx_receive_get_property;
177   gobject_class->set_property = gst_rtp_rtx_receive_set_property;
178   gobject_class->finalize = gst_rtp_rtx_receive_finalize;
179
180   g_object_class_install_property (gobject_class, PROP_PAYLOAD_TYPE_MAP,
181       g_param_spec_boxed ("payload-type-map", "Payload Type Map",
182           "Map of original payload types to their retransmission payload types",
183           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
184
185   g_object_class_install_property (gobject_class, PROP_NUM_RTX_REQUESTS,
186       g_param_spec_uint ("num-rtx-requests", "Num RTX Requests",
187           "Number of retransmission events received", 0, G_MAXUINT,
188           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
189
190   g_object_class_install_property (gobject_class, PROP_NUM_RTX_PACKETS,
191       g_param_spec_uint ("num-rtx-packets", "Num RTX Packets",
192           " Number of retransmission packets received", 0, G_MAXUINT,
193           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
194
195   g_object_class_install_property (gobject_class, PROP_NUM_RTX_ASSOC_PACKETS,
196       g_param_spec_uint ("num-rtx-assoc-packets",
197           "Num RTX Associated Packets", "Number of retransmission packets "
198           "correctly associated with retransmission requests", 0, G_MAXUINT,
199           0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
200
201   gst_element_class_add_pad_template (gstelement_class,
202       gst_static_pad_template_get (&src_factory));
203   gst_element_class_add_pad_template (gstelement_class,
204       gst_static_pad_template_get (&sink_factory));
205
206   gst_element_class_set_static_metadata (gstelement_class,
207       "RTP Retransmission receiver", "Codec",
208       "Receive retransmitted RTP packets according to RFC4588",
209       "Julien Isorce <julien.isorce@collabora.co.uk>");
210
211   gstelement_class->change_state =
212       GST_DEBUG_FUNCPTR (gst_rtp_rtx_receive_change_state);
213 }
214
215 static void
216 gst_rtp_rtx_receive_reset (GstRtpRtxReceive * rtx)
217 {
218   GST_OBJECT_LOCK (rtx);
219   g_hash_table_remove_all (rtx->ssrc2_ssrc1_map);
220   g_hash_table_remove_all (rtx->seqnum_ssrc1_map);
221   rtx->num_rtx_requests = 0;
222   rtx->num_rtx_packets = 0;
223   rtx->num_rtx_assoc_packets = 0;
224   GST_OBJECT_UNLOCK (rtx);
225 }
226
227 static void
228 gst_rtp_rtx_receive_finalize (GObject * object)
229 {
230   GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (object);
231
232   g_hash_table_unref (rtx->ssrc2_ssrc1_map);
233   g_hash_table_unref (rtx->seqnum_ssrc1_map);
234   g_hash_table_unref (rtx->rtx_pt_map);
235   if (rtx->rtx_pt_map_structure)
236     gst_structure_free (rtx->rtx_pt_map_structure);
237
238   G_OBJECT_CLASS (gst_rtp_rtx_receive_parent_class)->finalize (object);
239 }
240
241 typedef struct
242 {
243   guint32 ssrc;
244   GstClockTime time;
245 } SsrcAssoc;
246
247 static SsrcAssoc *
248 ssrc_assoc_new (guint32 ssrc, GstClockTime time)
249 {
250   SsrcAssoc *assoc = g_slice_new (SsrcAssoc);
251
252   assoc->ssrc = ssrc;
253   assoc->time = time;
254
255   return assoc;
256 }
257
258 static void
259 ssrc_assoc_free (SsrcAssoc * assoc)
260 {
261   g_slice_free (SsrcAssoc, assoc);
262 }
263
264 static void
265 gst_rtp_rtx_receive_init (GstRtpRtxReceive * rtx)
266 {
267   GstElementClass *klass = GST_ELEMENT_GET_CLASS (rtx);
268
269   rtx->srcpad =
270       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
271           "src"), "src");
272   GST_PAD_SET_PROXY_CAPS (rtx->srcpad);
273   GST_PAD_SET_PROXY_ALLOCATION (rtx->srcpad);
274   gst_pad_set_event_function (rtx->srcpad,
275       GST_DEBUG_FUNCPTR (gst_rtp_rtx_receive_src_event));
276   gst_element_add_pad (GST_ELEMENT (rtx), rtx->srcpad);
277
278   rtx->sinkpad =
279       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
280           "sink"), "sink");
281   GST_PAD_SET_PROXY_CAPS (rtx->sinkpad);
282   GST_PAD_SET_PROXY_ALLOCATION (rtx->sinkpad);
283   gst_pad_set_chain_function (rtx->sinkpad,
284       GST_DEBUG_FUNCPTR (gst_rtp_rtx_receive_chain));
285   gst_element_add_pad (GST_ELEMENT (rtx), rtx->sinkpad);
286
287   rtx->ssrc2_ssrc1_map = g_hash_table_new (g_direct_hash, g_direct_equal);
288   rtx->seqnum_ssrc1_map = g_hash_table_new_full (g_direct_hash, g_direct_equal,
289       NULL, (GDestroyNotify) ssrc_assoc_free);
290
291   rtx->rtx_pt_map = g_hash_table_new (g_direct_hash, g_direct_equal);
292 }
293
294 static gboolean
295 gst_rtp_rtx_receive_src_event (GstPad * pad, GstObject * parent,
296     GstEvent * event)
297 {
298   GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (parent);
299   gboolean res;
300
301   switch (GST_EVENT_TYPE (event)) {
302     case GST_EVENT_CUSTOM_UPSTREAM:
303     {
304       const GstStructure *s = gst_event_get_structure (event);
305
306       /* This event usually comes from the downstream gstrtpjitterbuffer */
307       if (gst_structure_has_name (s, "GstRTPRetransmissionRequest")) {
308         guint seqnum = 0;
309         guint ssrc = 0;
310         gpointer ssrc2 = 0;
311
312         /* retrieve seqnum of the packet that need to be retransmitted */
313         if (!gst_structure_get_uint (s, "seqnum", &seqnum))
314           seqnum = -1;
315
316         /* retrieve ssrc of the packet that need to be retransmitted
317          * it's useful when reconstructing the original packet from the rtx packet */
318         if (!gst_structure_get_uint (s, "ssrc", &ssrc))
319           ssrc = -1;
320
321         GST_DEBUG_OBJECT (rtx,
322             "request seqnum: %" G_GUINT32_FORMAT ", ssrc: %" G_GUINT32_FORMAT,
323             seqnum, ssrc);
324
325         GST_OBJECT_LOCK (rtx);
326
327         /* increase number of seen requests for our statistics */
328         ++rtx->num_rtx_requests;
329
330         /* First, we lookup in our map to see if we have already associate this
331          * master stream ssrc with its retransmitted stream.
332          * Every ssrc are unique so we can use the same hash table
333          * for both retrieving the ssrc1 from ssrc2 and also ssrc2 from ssrc1
334          */
335         if (g_hash_table_lookup_extended (rtx->ssrc2_ssrc1_map,
336                 GUINT_TO_POINTER (ssrc), NULL, &ssrc2)
337             && GPOINTER_TO_UINT (ssrc2) != GPOINTER_TO_UINT (ssrc)) {
338           GST_DEBUG_OBJECT (rtx, "Retransmited stream %" G_GUINT32_FORMAT
339               " already associated to its master", GPOINTER_TO_UINT (ssrc2));
340         } else {
341           SsrcAssoc *assoc;
342
343           /* not already associated but also we have to check that we have not
344            * already considered this request.
345            */
346           if (g_hash_table_lookup_extended (rtx->seqnum_ssrc1_map,
347                   GUINT_TO_POINTER (seqnum), NULL, (gpointer *) & assoc)) {
348             if (assoc->ssrc == ssrc) {
349               /* do nothing because we have already considered this request
350                * The jitter may be too impatient of the rtx packet has been
351                * lost too.
352                * It does not mean we reject the event, we still want to forward
353                * the request to the gstrtpsession to be translater into a FB NACK
354                */
355               GST_DEBUG_OBJECT (rtx, "Duplicated request seqnum: %"
356                   G_GUINT32_FORMAT ", ssrc1: %" G_GUINT32_FORMAT, seqnum, ssrc);
357             } else {
358
359               /* If the association attempt is larger than ASSOC_TIMEOUT,
360                * then we give up on it, and try this one.
361                */
362               if (!GST_CLOCK_TIME_IS_VALID (rtx->last_time) ||
363                   !GST_CLOCK_TIME_IS_VALID (assoc->time) ||
364                   assoc->time + ASSOC_TIMEOUT < rtx->last_time) {
365                 /* From RFC 4588:
366                  * the receiver MUST NOT have two outstanding requests for the
367                  * same packet sequence number in two different original streams
368                  * before the association is resolved. Otherwise it's impossible
369                  * to associate a rtx stream and its master stream
370                  */
371
372                 /* remove seqnum in order to reuse the spot */
373                 g_hash_table_remove (rtx->seqnum_ssrc1_map,
374                     GUINT_TO_POINTER (seqnum));
375                 goto retransmit;
376               } else {
377                 GST_DEBUG_OBJECT (rtx,
378                     "reject request for seqnum %" G_GUINT32_FORMAT
379                     " of master stream %" G_GUINT32_FORMAT, seqnum, ssrc);
380
381                 /* do not forward the event as we are rejecting this request */
382                 GST_OBJECT_UNLOCK (rtx);
383                 gst_event_unref (event);
384                 return TRUE;
385               }
386             }
387           } else {
388           retransmit:
389             /* the request has not been already considered
390              * insert it for the first time */
391             g_hash_table_insert (rtx->seqnum_ssrc1_map,
392                 GUINT_TO_POINTER (seqnum),
393                 ssrc_assoc_new (ssrc, rtx->last_time));
394           }
395         }
396
397         GST_DEBUG_OBJECT (rtx,
398             "packet number %" G_GUINT32_FORMAT " of master stream %"
399             G_GUINT32_FORMAT " needs to be retransmitted", seqnum, ssrc);
400
401         GST_OBJECT_UNLOCK (rtx);
402       }
403
404       /* Transfer event upstream so that the request can acutally by translated
405        * through gstrtpsession through the network */
406       res = gst_pad_event_default (pad, parent, event);
407       break;
408     }
409     default:
410       res = gst_pad_event_default (pad, parent, event);
411       break;
412   }
413   return res;
414 }
415
416 /* Copy fixed header and extension. Replace current ssrc by ssrc1,
417  * remove OSN and replace current seq num by OSN.
418  * Copy memory to avoid to manually copy each rtp buffer field.
419  */
420 static GstBuffer *
421 _gst_rtp_buffer_new_from_rtx (GstRTPBuffer * rtp, guint32 ssrc1,
422     guint16 orign_seqnum, guint8 origin_payload_type)
423 {
424   GstMemory *mem = NULL;
425   GstRTPBuffer new_rtp = GST_RTP_BUFFER_INIT;
426   GstBuffer *new_buffer = gst_buffer_new ();
427   GstMapInfo map;
428   guint payload_len = 0;
429
430   /* copy fixed header */
431   mem = gst_memory_copy (rtp->map[0].memory,
432       (guint8 *) rtp->data[0] - rtp->map[0].data, rtp->size[0]);
433   gst_buffer_append_memory (new_buffer, mem);
434
435   /* copy extension if any */
436   if (rtp->size[1]) {
437     mem = gst_memory_copy (rtp->map[1].memory,
438         (guint8 *) rtp->data[1] - rtp->map[1].data, rtp->size[1]);
439     gst_buffer_append_memory (new_buffer, mem);
440   }
441
442   /* copy payload and remove OSN */
443   payload_len = rtp->size[2] - 2;
444   mem = gst_allocator_alloc (NULL, payload_len, NULL);
445
446   gst_memory_map (mem, &map, GST_MAP_WRITE);
447   if (rtp->size[2])
448     memcpy (map.data, (guint8 *) rtp->data[2] + 2, payload_len);
449   gst_memory_unmap (mem, &map);
450   gst_buffer_append_memory (new_buffer, mem);
451
452   /* the sender always constructs rtx packets without padding,
453    * But the receiver can still receive rtx packets with padding.
454    * So just copy it.
455    */
456   if (rtp->size[3]) {
457     guint pad_len = rtp->size[3];
458
459     mem = gst_allocator_alloc (NULL, pad_len, NULL);
460
461     gst_memory_map (mem, &map, GST_MAP_WRITE);
462     map.data[pad_len - 1] = pad_len;
463     gst_memory_unmap (mem, &map);
464
465     gst_buffer_append_memory (new_buffer, mem);
466   }
467
468   /* set ssrc and seq num */
469   gst_rtp_buffer_map (new_buffer, GST_MAP_WRITE, &new_rtp);
470   gst_rtp_buffer_set_ssrc (&new_rtp, ssrc1);
471   gst_rtp_buffer_set_seq (&new_rtp, orign_seqnum);
472   gst_rtp_buffer_set_payload_type (&new_rtp, origin_payload_type);
473   gst_rtp_buffer_unmap (&new_rtp);
474
475   gst_buffer_copy_into (new_buffer, rtp->buffer,
476       GST_BUFFER_COPY_FLAGS | GST_BUFFER_COPY_TIMESTAMPS, 0, -1);
477
478   return new_buffer;
479 }
480
481 static GstFlowReturn
482 gst_rtp_rtx_receive_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
483 {
484   GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (parent);
485   GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
486   GstFlowReturn ret = GST_FLOW_OK;
487   GstBuffer *new_buffer = NULL;
488   guint32 ssrc = 0;
489   gpointer ssrc1 = 0;
490   guint32 ssrc2 = 0;
491   guint16 seqnum = 0;
492   guint16 orign_seqnum = 0;
493   guint8 payload_type = 0;
494   guint8 origin_payload_type = 0;
495   gboolean is_rtx;
496   gboolean drop = FALSE;
497
498   /* map current rtp packet to parse its header */
499   gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp);
500   ssrc = gst_rtp_buffer_get_ssrc (&rtp);
501   seqnum = gst_rtp_buffer_get_seq (&rtp);
502   payload_type = gst_rtp_buffer_get_payload_type (&rtp);
503
504   /* check if we have a retransmission packet (this information comes from SDP) */
505   GST_OBJECT_LOCK (rtx);
506
507   rtx->last_time = GST_BUFFER_PTS (buffer);
508
509   is_rtx =
510       g_hash_table_lookup_extended (rtx->rtx_pt_map,
511       GUINT_TO_POINTER (payload_type), NULL, NULL);
512
513   /* if the current packet is from a retransmission stream */
514   if (is_rtx) {
515     /* increase our statistic */
516     ++rtx->num_rtx_packets;
517
518     /* read OSN in the rtx payload */
519     orign_seqnum = GST_READ_UINT16_BE (gst_rtp_buffer_get_payload (&rtp));
520     origin_payload_type =
521         GPOINTER_TO_UINT (g_hash_table_lookup (rtx->rtx_pt_map,
522             GUINT_TO_POINTER (payload_type)));
523
524     /* first we check if we already have associated this retransmission stream
525      * to a master stream */
526     if (g_hash_table_lookup_extended (rtx->ssrc2_ssrc1_map,
527             GUINT_TO_POINTER (ssrc), NULL, &ssrc1)) {
528       GST_DEBUG_OBJECT (rtx,
529           "packet is from retransmission stream %" G_GUINT32_FORMAT
530           " already associated to master stream %" G_GUINT32_FORMAT, ssrc,
531           GPOINTER_TO_UINT (ssrc1));
532       ssrc2 = ssrc;
533     } else {
534       SsrcAssoc *assoc;
535
536       /* the current retransmitted packet has its rtx stream not already
537        * associated to a master stream, so retrieve it from our request
538        * history */
539       if (g_hash_table_lookup_extended (rtx->seqnum_ssrc1_map,
540               GUINT_TO_POINTER (orign_seqnum), NULL, (gpointer *) & assoc)) {
541         GST_DEBUG_OBJECT (rtx,
542             "associate retransmitted stream %" G_GUINT32_FORMAT
543             " to master stream %" G_GUINT32_FORMAT " thanks to packet %"
544             G_GUINT16_FORMAT "", ssrc, assoc->ssrc, orign_seqnum);
545         ssrc1 = GUINT_TO_POINTER (assoc->ssrc);
546         ssrc2 = ssrc;
547
548         /* just put a guard */
549         if (GPOINTER_TO_UINT (ssrc1) == ssrc2)
550           GST_WARNING_OBJECT (rtx, "RTX receiver ssrc2_ssrc1_map bad state, "
551               "ssrc %" G_GUINT32_FORMAT " are the same\n", ssrc);
552
553         /* free the spot so that this seqnum can be used to do another
554          * association */
555         g_hash_table_remove (rtx->seqnum_ssrc1_map,
556             GUINT_TO_POINTER (orign_seqnum));
557
558         /* actually do the association between rtx stream and master stream */
559         g_hash_table_insert (rtx->ssrc2_ssrc1_map, GUINT_TO_POINTER (ssrc2),
560             ssrc1);
561
562         /* also do the association between master stream and rtx stream
563          * every ssrc are unique so we can use the same hash table
564          * for both retrieving the ssrc1 from ssrc2 and also ssrc2 from ssrc1
565          */
566         g_hash_table_insert (rtx->ssrc2_ssrc1_map, ssrc1,
567             GUINT_TO_POINTER (ssrc2));
568
569       } else {
570         /* we are not able to associate this rtx packet with a master stream */
571         GST_DEBUG_OBJECT (rtx,
572             "drop rtx packet because its orign_seqnum %" G_GUINT16_FORMAT
573             " is not in pending retransmission requests", orign_seqnum);
574         drop = TRUE;
575       }
576     }
577   }
578
579   /* if not dropped the packet was successfully associated */
580   if (is_rtx && !drop)
581     ++rtx->num_rtx_assoc_packets;
582
583   GST_OBJECT_UNLOCK (rtx);
584
585   /* just drop the packet if the association could not have been made */
586   if (drop) {
587     gst_rtp_buffer_unmap (&rtp);
588     gst_buffer_unref (buffer);
589     return GST_FLOW_OK;
590   }
591
592   /* create the retransmission packet */
593   if (is_rtx)
594     new_buffer =
595         _gst_rtp_buffer_new_from_rtx (&rtp, GPOINTER_TO_UINT (ssrc1),
596         orign_seqnum, origin_payload_type);
597
598   gst_rtp_buffer_unmap (&rtp);
599
600   /* push the packet */
601   if (is_rtx) {
602     gst_buffer_unref (buffer);
603     GST_LOG_OBJECT (rtx, "push packet seqnum:%" G_GUINT16_FORMAT
604         " from a restransmission stream ssrc2:%" G_GUINT32_FORMAT " (src %"
605         G_GUINT32_FORMAT ")", orign_seqnum, ssrc2, GPOINTER_TO_UINT (ssrc1));
606     ret = gst_pad_push (rtx->srcpad, new_buffer);
607   } else {
608     GST_LOG_OBJECT (rtx, "push packet seqnum:%" G_GUINT16_FORMAT
609         " from a master stream ssrc: %" G_GUINT32_FORMAT, seqnum, ssrc);
610     ret = gst_pad_push (rtx->srcpad, buffer);
611   }
612
613   return ret;
614 }
615
616 static void
617 gst_rtp_rtx_receive_get_property (GObject * object,
618     guint prop_id, GValue * value, GParamSpec * pspec)
619 {
620   GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (object);
621
622   switch (prop_id) {
623     case PROP_PAYLOAD_TYPE_MAP:
624       GST_OBJECT_LOCK (rtx);
625       g_value_set_boxed (value, rtx->rtx_pt_map_structure);
626       GST_OBJECT_UNLOCK (rtx);
627       break;
628     case PROP_NUM_RTX_REQUESTS:
629       GST_OBJECT_LOCK (rtx);
630       g_value_set_uint (value, rtx->num_rtx_requests);
631       GST_OBJECT_UNLOCK (rtx);
632       break;
633     case PROP_NUM_RTX_PACKETS:
634       GST_OBJECT_LOCK (rtx);
635       g_value_set_uint (value, rtx->num_rtx_packets);
636       GST_OBJECT_UNLOCK (rtx);
637       break;
638     case PROP_NUM_RTX_ASSOC_PACKETS:
639       GST_OBJECT_LOCK (rtx);
640       g_value_set_uint (value, rtx->num_rtx_assoc_packets);
641       GST_OBJECT_UNLOCK (rtx);
642       break;
643     default:
644       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
645       break;
646   }
647 }
648
649 static gboolean
650 structure_to_hash_table_inv (GQuark field_id, const GValue * value,
651     gpointer hash)
652 {
653   const gchar *field_str;
654   guint field_uint;
655   guint value_uint;
656
657   field_str = g_quark_to_string (field_id);
658   field_uint = atoi (field_str);
659   value_uint = g_value_get_uint (value);
660   g_hash_table_insert ((GHashTable *) hash, GUINT_TO_POINTER (value_uint),
661       GUINT_TO_POINTER (field_uint));
662
663   return TRUE;
664 }
665
666 static void
667 gst_rtp_rtx_receive_set_property (GObject * object,
668     guint prop_id, const GValue * value, GParamSpec * pspec)
669 {
670   GstRtpRtxReceive *rtx = GST_RTP_RTX_RECEIVE (object);
671
672   switch (prop_id) {
673     case PROP_PAYLOAD_TYPE_MAP:
674       GST_OBJECT_LOCK (rtx);
675       if (rtx->rtx_pt_map_structure)
676         gst_structure_free (rtx->rtx_pt_map_structure);
677       rtx->rtx_pt_map_structure = g_value_dup_boxed (value);
678       g_hash_table_remove_all (rtx->rtx_pt_map);
679       gst_structure_foreach (rtx->rtx_pt_map_structure,
680           structure_to_hash_table_inv, rtx->rtx_pt_map);
681       GST_OBJECT_UNLOCK (rtx);
682       break;
683     default:
684       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
685       break;
686   }
687 }
688
689 static GstStateChangeReturn
690 gst_rtp_rtx_receive_change_state (GstElement * element,
691     GstStateChange transition)
692 {
693   GstStateChangeReturn ret;
694   GstRtpRtxReceive *rtx;
695
696   rtx = GST_RTP_RTX_RECEIVE (element);
697
698   switch (transition) {
699     default:
700       break;
701   }
702
703   ret =
704       GST_ELEMENT_CLASS (gst_rtp_rtx_receive_parent_class)->change_state
705       (element, transition);
706
707   switch (transition) {
708     case GST_STATE_CHANGE_PAUSED_TO_READY:
709       gst_rtp_rtx_receive_reset (rtx);
710       break;
711     default:
712       break;
713   }
714
715   return ret;
716 }
717
718 gboolean
719 gst_rtp_rtx_receive_plugin_init (GstPlugin * plugin)
720 {
721   GST_DEBUG_CATEGORY_INIT (gst_rtp_rtx_receive_debug, "rtprtxreceive", 0,
722       "rtp retransmission receiver");
723
724   return gst_element_register (plugin, "rtprtxreceive", GST_RANK_NONE,
725       GST_TYPE_RTP_RTX_RECEIVE);
726 }