rtp: Update codes based on 1.18.4
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtpvorbispay.c
1 /* GStreamer
2  * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <string.h>
25
26 #include <gst/rtp/gstrtpbuffer.h>
27 #include <gst/audio/audio.h>
28
29 #include "fnv1hash.h"
30 #include "gstrtpvorbispay.h"
31 #include "gstrtputils.h"
32
33 GST_DEBUG_CATEGORY_STATIC (rtpvorbispay_debug);
34 #define GST_CAT_DEFAULT (rtpvorbispay_debug)
35
36 /* references:
37  * http://www.rfc-editor.org/rfc/rfc5215.txt
38  */
39
40 static GstStaticPadTemplate gst_rtp_vorbis_pay_src_template =
41 GST_STATIC_PAD_TEMPLATE ("src",
42     GST_PAD_SRC,
43     GST_PAD_ALWAYS,
44     GST_STATIC_CAPS ("application/x-rtp, "
45         "media = (string) \"audio\", "
46         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
47         "clock-rate = (int) [1, MAX ], " "encoding-name = (string) \"VORBIS\""
48         /* All required parameters
49          *
50          * "encoding-params = (string) <num channels>"
51          * "configuration = (string) ANY"
52          */
53     )
54     );
55
56 static GstStaticPadTemplate gst_rtp_vorbis_pay_sink_template =
57 GST_STATIC_PAD_TEMPLATE ("sink",
58     GST_PAD_SINK,
59     GST_PAD_ALWAYS,
60     GST_STATIC_CAPS ("audio/x-vorbis")
61     );
62
63 #define DEFAULT_CONFIG_INTERVAL 0
64
65 enum
66 {
67   PROP_0,
68   PROP_CONFIG_INTERVAL
69 };
70
71 #define gst_rtp_vorbis_pay_parent_class parent_class
72 G_DEFINE_TYPE (GstRtpVorbisPay, gst_rtp_vorbis_pay, GST_TYPE_RTP_BASE_PAYLOAD);
73
74 static gboolean gst_rtp_vorbis_pay_setcaps (GstRTPBasePayload * basepayload,
75     GstCaps * caps);
76 static GstStateChangeReturn gst_rtp_vorbis_pay_change_state (GstElement *
77     element, GstStateChange transition);
78 static GstFlowReturn gst_rtp_vorbis_pay_handle_buffer (GstRTPBasePayload * pad,
79     GstBuffer * buffer);
80 static gboolean gst_rtp_vorbis_pay_sink_event (GstRTPBasePayload * payload,
81     GstEvent * event);
82
83 static gboolean gst_rtp_vorbis_pay_parse_id (GstRTPBasePayload * basepayload,
84     guint8 * data, guint size);
85 static gboolean gst_rtp_vorbis_pay_finish_headers (GstRTPBasePayload *
86     basepayload);
87
88 static void gst_rtp_vorbis_pay_set_property (GObject * object, guint prop_id,
89     const GValue * value, GParamSpec * pspec);
90 static void gst_rtp_vorbis_pay_get_property (GObject * object, guint prop_id,
91     GValue * value, GParamSpec * pspec);
92
93 static void
94 gst_rtp_vorbis_pay_class_init (GstRtpVorbisPayClass * klass)
95 {
96   GObjectClass *gobject_class;
97   GstElementClass *gstelement_class;
98   GstRTPBasePayloadClass *gstrtpbasepayload_class;
99
100   gobject_class = (GObjectClass *) klass;
101   gstelement_class = (GstElementClass *) klass;
102   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
103
104   gstelement_class->change_state = gst_rtp_vorbis_pay_change_state;
105
106   gstrtpbasepayload_class->set_caps = gst_rtp_vorbis_pay_setcaps;
107   gstrtpbasepayload_class->handle_buffer = gst_rtp_vorbis_pay_handle_buffer;
108   gstrtpbasepayload_class->sink_event = gst_rtp_vorbis_pay_sink_event;
109
110   gobject_class->set_property = gst_rtp_vorbis_pay_set_property;
111   gobject_class->get_property = gst_rtp_vorbis_pay_get_property;
112
113   gst_element_class_add_static_pad_template (gstelement_class,
114       &gst_rtp_vorbis_pay_src_template);
115   gst_element_class_add_static_pad_template (gstelement_class,
116       &gst_rtp_vorbis_pay_sink_template);
117
118   gst_element_class_set_static_metadata (gstelement_class,
119       "RTP Vorbis payloader",
120       "Codec/Payloader/Network/RTP",
121       "Payload-encode Vorbis audio into RTP packets (RFC 5215)",
122       "Wim Taymans <wim.taymans@gmail.com>");
123
124   GST_DEBUG_CATEGORY_INIT (rtpvorbispay_debug, "rtpvorbispay", 0,
125       "Vorbis RTP Payloader");
126
127   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CONFIG_INTERVAL,
128       g_param_spec_uint ("config-interval", "Config Send Interval",
129           "Send Config Insertion Interval in seconds (configuration headers "
130           "will be multiplexed in the data stream when detected.) (0 = disabled)",
131           0, 3600, DEFAULT_CONFIG_INTERVAL,
132           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
133       );
134 }
135
136 static void
137 gst_rtp_vorbis_pay_init (GstRtpVorbisPay * rtpvorbispay)
138 {
139   rtpvorbispay->last_config = GST_CLOCK_TIME_NONE;
140 }
141
142 static void
143 gst_rtp_vorbis_pay_clear_packet (GstRtpVorbisPay * rtpvorbispay)
144 {
145   if (rtpvorbispay->packet)
146     gst_buffer_unref (rtpvorbispay->packet);
147   rtpvorbispay->packet = NULL;
148   g_list_free_full (rtpvorbispay->packet_buffers,
149       (GDestroyNotify) gst_buffer_unref);
150   rtpvorbispay->packet_buffers = NULL;
151 }
152
153 static void
154 gst_rtp_vorbis_pay_cleanup (GstRtpVorbisPay * rtpvorbispay)
155 {
156   gst_rtp_vorbis_pay_clear_packet (rtpvorbispay);
157   g_list_free_full (rtpvorbispay->headers, (GDestroyNotify) gst_buffer_unref);
158   rtpvorbispay->headers = NULL;
159   g_free (rtpvorbispay->config_data);
160   rtpvorbispay->config_data = NULL;
161   rtpvorbispay->last_config = GST_CLOCK_TIME_NONE;
162 }
163
164 static gboolean
165 gst_rtp_vorbis_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
166 {
167   GstRtpVorbisPay *rtpvorbispay;
168   GstStructure *s;
169   const GValue *array;
170   gint asize, i;
171   GstBuffer *buf;
172   GstMapInfo map;
173
174   rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
175
176   s = gst_caps_get_structure (caps, 0);
177
178   rtpvorbispay->need_headers = TRUE;
179
180   if ((array = gst_structure_get_value (s, "streamheader")) == NULL)
181     goto done;
182
183   if (G_VALUE_TYPE (array) != GST_TYPE_ARRAY)
184     goto done;
185
186   if ((asize = gst_value_array_get_size (array)) < 3)
187     goto done;
188
189   for (i = 0; i < asize; i++) {
190     const GValue *value;
191
192     value = gst_value_array_get_value (array, i);
193     if ((buf = gst_value_get_buffer (value)) == NULL)
194       goto null_buffer;
195
196     gst_buffer_map (buf, &map, GST_MAP_READ);
197     if (map.size < 1)
198       goto invalid_streamheader;
199
200     /* no data packets allowed */
201     if ((map.data[0] & 1) == 0)
202       goto invalid_streamheader;
203
204     /* we need packets with id 1, 3, 5 */
205     if (map.data[0] != (i * 2) + 1)
206       goto invalid_streamheader;
207
208     if (i == 0) {
209       /* identification, we need to parse this in order to get the clock rate. */
210       if (G_UNLIKELY (!gst_rtp_vorbis_pay_parse_id (basepayload, map.data,
211                   map.size)))
212         goto parse_id_failed;
213     }
214     GST_DEBUG_OBJECT (rtpvorbispay, "collecting header %d", i);
215     rtpvorbispay->headers =
216         g_list_append (rtpvorbispay->headers, gst_buffer_ref (buf));
217     gst_buffer_unmap (buf, &map);
218   }
219   if (!gst_rtp_vorbis_pay_finish_headers (basepayload))
220     goto finish_failed;
221
222 done:
223   return TRUE;
224
225   /* ERRORS */
226 null_buffer:
227   {
228     GST_WARNING_OBJECT (rtpvorbispay, "streamheader with null buffer received");
229     return FALSE;
230   }
231 invalid_streamheader:
232   {
233     GST_WARNING_OBJECT (rtpvorbispay, "unable to parse initial header");
234     gst_buffer_unmap (buf, &map);
235     return FALSE;
236   }
237 parse_id_failed:
238   {
239     GST_WARNING_OBJECT (rtpvorbispay, "unable to parse initial header");
240     gst_buffer_unmap (buf, &map);
241     return FALSE;
242   }
243 finish_failed:
244   {
245     GST_WARNING_OBJECT (rtpvorbispay, "unable to finish headers");
246     return FALSE;
247   }
248 }
249
250 static void
251 gst_rtp_vorbis_pay_reset_packet (GstRtpVorbisPay * rtpvorbispay, guint8 VDT)
252 {
253   guint payload_len;
254   GstRTPBuffer rtp = { NULL };
255
256   GST_LOG_OBJECT (rtpvorbispay, "reset packet");
257
258   rtpvorbispay->payload_pos = 4;
259   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_READ, &rtp);
260   payload_len = gst_rtp_buffer_get_payload_len (&rtp);
261   gst_rtp_buffer_unmap (&rtp);
262   rtpvorbispay->payload_left = payload_len - 4;
263   rtpvorbispay->payload_duration = 0;
264   rtpvorbispay->payload_F = 0;
265   rtpvorbispay->payload_VDT = VDT;
266   rtpvorbispay->payload_pkts = 0;
267 }
268
269 static void
270 gst_rtp_vorbis_pay_init_packet (GstRtpVorbisPay * rtpvorbispay, guint8 VDT,
271     GstClockTime timestamp)
272 {
273   guint len;
274
275   GST_LOG_OBJECT (rtpvorbispay, "starting new packet, VDT: %d", VDT);
276
277   gst_rtp_vorbis_pay_clear_packet (rtpvorbispay);
278
279   /* new packet allocate max packet size */
280   len = gst_rtp_buffer_calc_payload_len (GST_RTP_BASE_PAYLOAD_MTU
281       (rtpvorbispay), 0, 0);
282   rtpvorbispay->packet =
283       gst_rtp_base_payload_allocate_output_buffer (GST_RTP_BASE_PAYLOAD
284       (rtpvorbispay), len, 0, 0);
285   gst_rtp_vorbis_pay_reset_packet (rtpvorbispay, VDT);
286
287   GST_BUFFER_PTS (rtpvorbispay->packet) = timestamp;
288 }
289
290 static GstFlowReturn
291 gst_rtp_vorbis_pay_flush_packet (GstRtpVorbisPay * rtpvorbispay)
292 {
293   GstFlowReturn ret;
294   guint8 *payload;
295   guint hlen;
296   GstRTPBuffer rtp = { NULL };
297   GList *l;
298
299   /* check for empty packet */
300   if (!rtpvorbispay->packet || rtpvorbispay->payload_pos <= 4)
301     return GST_FLOW_OK;
302
303   GST_LOG_OBJECT (rtpvorbispay, "flushing packet");
304
305   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
306
307   /* fix header */
308   payload = gst_rtp_buffer_get_payload (&rtp);
309   /*
310    *  0                   1                   2                   3
311    *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
312    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
313    * |                     Ident                     | F |VDT|# pkts.|
314    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
315    *
316    * F: Fragment type (0=none, 1=start, 2=cont, 3=end)
317    * VDT: Vorbis data type (0=vorbis, 1=config, 2=comment, 3=reserved)
318    * pkts: number of packets.
319    */
320   payload[0] = (rtpvorbispay->payload_ident >> 16) & 0xff;
321   payload[1] = (rtpvorbispay->payload_ident >> 8) & 0xff;
322   payload[2] = (rtpvorbispay->payload_ident) & 0xff;
323   payload[3] = (rtpvorbispay->payload_F & 0x3) << 6 |
324       (rtpvorbispay->payload_VDT & 0x3) << 4 |
325       (rtpvorbispay->payload_pkts & 0xf);
326
327   gst_rtp_buffer_unmap (&rtp);
328
329   /* shrink the buffer size to the last written byte */
330   hlen = gst_rtp_buffer_calc_header_len (0);
331   gst_buffer_resize (rtpvorbispay->packet, 0, hlen + rtpvorbispay->payload_pos);
332
333   GST_BUFFER_DURATION (rtpvorbispay->packet) = rtpvorbispay->payload_duration;
334
335   for (l = g_list_last (rtpvorbispay->packet_buffers); l; l = l->prev) {
336     GstBuffer *buf = GST_BUFFER_CAST (l->data);
337     gst_rtp_copy_audio_meta (rtpvorbispay, rtpvorbispay->packet, buf);
338     gst_buffer_unref (buf);
339   }
340   g_list_free (rtpvorbispay->packet_buffers);
341   rtpvorbispay->packet_buffers = NULL;
342
343   /* push, this gives away our ref to the packet, so clear it. */
344   ret =
345       gst_rtp_base_payload_push (GST_RTP_BASE_PAYLOAD (rtpvorbispay),
346       rtpvorbispay->packet);
347   rtpvorbispay->packet = NULL;
348
349   return ret;
350 }
351
352 static gboolean
353 gst_rtp_vorbis_pay_finish_headers (GstRTPBasePayload * basepayload)
354 {
355   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
356   GList *walk;
357   guint length, size, n_headers, configlen, extralen;
358   gchar *cstr, *configuration;
359   guint8 *data, *config;
360   guint32 ident;
361   gboolean res;
362
363   GST_DEBUG_OBJECT (rtpvorbispay, "finish headers");
364
365   if (!rtpvorbispay->headers)
366     goto no_headers;
367
368   /* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
369    * |                     Number of packed headers                  |
370    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
371    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
372    * |                          Packed header                        |
373    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
374    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
375    * |                          Packed header                        |
376    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
377    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
378    * |                          ....                                 |
379    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
380    *
381    * We only construct a config containing 1 packed header like this:
382    *
383    *  0                   1                   2                   3
384    *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
385    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
386    * |                   Ident                       | length       ..
387    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
388    * ..              | n. of headers |    length1    |    length2   ..
389    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
390    * ..              |             Identification Header            ..
391    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
392    * .................................................................
393    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
394    * ..              |         Comment Header                       ..
395    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
396    * .................................................................
397    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
398    * ..                        Comment Header                        |
399    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
400    * |                          Setup Header                        ..
401    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
402    * .................................................................
403    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
404    * ..                         Setup Header                         |
405    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
406    */
407
408   /* we need 4 bytes for the number of headers (which is always 1), 3 bytes for
409    * the ident, 2 bytes for length, 1 byte for n. of headers. */
410   size = 4 + 3 + 2 + 1;
411
412   /* count the size of the headers first and update the hash */
413   length = 0;
414   n_headers = 0;
415   ident = fnv1_hash_32_new ();
416   extralen = 1;
417   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
418     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
419     GstMapInfo map;
420     guint bsize;
421
422     bsize = gst_buffer_get_size (buf);
423     length += bsize;
424     n_headers++;
425
426     /* count number of bytes needed for length fields, we don't need this for
427      * the last header. */
428     if (g_list_next (walk)) {
429       do {
430         size++;
431         extralen++;
432         bsize >>= 7;
433       } while (bsize);
434     }
435     /* update hash */
436     gst_buffer_map (buf, &map, GST_MAP_READ);
437     ident = fnv1_hash_32_update (ident, map.data, map.size);
438     gst_buffer_unmap (buf, &map);
439   }
440
441   /* packet length is header size + packet length */
442   configlen = size + length;
443   config = data = g_malloc (configlen);
444
445   /* number of packed headers, we only pack 1 header */
446   data[0] = 0;
447   data[1] = 0;
448   data[2] = 0;
449   data[3] = 1;
450
451   ident = fnv1_hash_32_to_24 (ident);
452   rtpvorbispay->payload_ident = ident;
453   GST_DEBUG_OBJECT (rtpvorbispay, "ident 0x%08x", ident);
454
455   /* take lower 3 bytes */
456   data[4] = (ident >> 16) & 0xff;
457   data[5] = (ident >> 8) & 0xff;
458   data[6] = ident & 0xff;
459
460   /* store length of all vorbis headers */
461   data[7] = ((length) >> 8) & 0xff;
462   data[8] = (length) & 0xff;
463
464   /* store number of headers minus one. */
465   data[9] = n_headers - 1;
466   data += 10;
467
468   /* store length for each header */
469   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
470     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
471     guint bsize, size, temp;
472     guint flag;
473
474     /* only need to store the length when it's not the last header */
475     if (!g_list_next (walk))
476       break;
477
478     bsize = gst_buffer_get_size (buf);
479
480     /* calc size */
481     size = 0;
482     do {
483       size++;
484       bsize >>= 7;
485     } while (bsize);
486     temp = size;
487
488     bsize = gst_buffer_get_size (buf);
489     /* write the size backwards */
490     flag = 0;
491     while (size) {
492       size--;
493       data[size] = (bsize & 0x7f) | flag;
494       bsize >>= 7;
495       flag = 0x80;              /* Flag bit on all bytes of the length except the last */
496     }
497     data += temp;
498   }
499
500   /* copy header data */
501   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
502     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
503
504     gst_buffer_extract (buf, 0, data, gst_buffer_get_size (buf));
505     data += gst_buffer_get_size (buf);
506   }
507   rtpvorbispay->need_headers = FALSE;
508
509   /* serialize to base64 */
510   configuration = g_base64_encode (config, configlen);
511
512   /* store for later re-sending */
513   g_free (rtpvorbispay->config_data);
514   rtpvorbispay->config_size = configlen - 4 - 3 - 2;
515   rtpvorbispay->config_data = g_malloc (rtpvorbispay->config_size);
516   rtpvorbispay->config_extra_len = extralen;
517   memcpy (rtpvorbispay->config_data, config + 4 + 3 + 2,
518       rtpvorbispay->config_size);
519
520   g_free (config);
521
522   /* configure payloader settings */
523   cstr = g_strdup_printf ("%d", rtpvorbispay->channels);
524   gst_rtp_base_payload_set_options (basepayload, "audio", TRUE, "VORBIS",
525       rtpvorbispay->rate);
526   res =
527       gst_rtp_base_payload_set_outcaps (basepayload, "encoding-params",
528       G_TYPE_STRING, cstr, "configuration", G_TYPE_STRING, configuration, NULL);
529   g_free (cstr);
530   g_free (configuration);
531
532   return res;
533
534   /* ERRORS */
535 no_headers:
536   {
537     GST_DEBUG_OBJECT (rtpvorbispay, "finish headers");
538     return FALSE;
539   }
540 }
541
542 static gboolean
543 gst_rtp_vorbis_pay_parse_id (GstRTPBasePayload * basepayload, guint8 * data,
544     guint size)
545 {
546   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
547   guint8 channels;
548   gint32 rate, version;
549
550   if (G_UNLIKELY (size < 16))
551     goto too_short;
552
553   if (G_UNLIKELY (memcmp (data, "\001vorbis", 7)))
554     goto invalid_start;
555   data += 7;
556
557   if (G_UNLIKELY ((version = GST_READ_UINT32_LE (data)) != 0))
558     goto invalid_version;
559   data += 4;
560
561   if (G_UNLIKELY ((channels = *data++) < 1))
562     goto invalid_channels;
563
564   if (G_UNLIKELY ((rate = GST_READ_UINT32_LE (data)) < 1))
565     goto invalid_rate;
566
567   /* all fine, store the values */
568   rtpvorbispay->channels = channels;
569   rtpvorbispay->rate = rate;
570
571   return TRUE;
572
573   /* ERRORS */
574 too_short:
575   {
576     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
577         ("Identification packet is too short, need at least 16, got %d", size),
578         (NULL));
579     return FALSE;
580   }
581 invalid_start:
582   {
583     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
584         ("Invalid header start in identification packet"), (NULL));
585     return FALSE;
586   }
587 invalid_version:
588   {
589     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
590         ("Invalid version, expected 0, got %d", version), (NULL));
591     return FALSE;
592   }
593 invalid_rate:
594   {
595     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
596         ("Invalid rate %d", rate), (NULL));
597     return FALSE;
598   }
599 invalid_channels:
600   {
601     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
602         ("Invalid channels %d", channels), (NULL));
603     return FALSE;
604   }
605 }
606
607 static GstFlowReturn
608 gst_rtp_vorbis_pay_payload_buffer (GstRtpVorbisPay * rtpvorbispay, guint8 VDT,
609     GstBuffer * buffer, guint8 * data, guint size, GstClockTime timestamp,
610     GstClockTime duration, guint not_in_length)
611 {
612   GstFlowReturn ret = GST_FLOW_OK;
613   guint newsize;
614   guint packet_len;
615   GstClockTime newduration;
616   gboolean flush;
617   guint plen;
618   guint8 *ppos, *payload;
619   gboolean fragmented;
620   GstRTPBuffer rtp = { NULL };
621
622   /* size increases with packet length and 2 bytes size eader. */
623   newduration = rtpvorbispay->payload_duration;
624   if (duration != GST_CLOCK_TIME_NONE)
625     newduration += duration;
626
627   newsize = rtpvorbispay->payload_pos + 2 + size;
628   packet_len = gst_rtp_buffer_calc_packet_len (newsize, 0, 0);
629
630   /* check buffer filled against length and max latency */
631   flush = gst_rtp_base_payload_is_filled (GST_RTP_BASE_PAYLOAD (rtpvorbispay),
632       packet_len, newduration);
633   /* we can store up to 15 vorbis packets in one RTP packet. */
634   flush |= (rtpvorbispay->payload_pkts == 15);
635   /* flush if we have a new VDT */
636   if (rtpvorbispay->packet)
637     flush |= (rtpvorbispay->payload_VDT != VDT);
638   if (flush)
639     ret = gst_rtp_vorbis_pay_flush_packet (rtpvorbispay);
640
641   if (ret != GST_FLOW_OK)
642     goto done;
643
644   /* create new packet if we must */
645   if (!rtpvorbispay->packet) {
646     gst_rtp_vorbis_pay_init_packet (rtpvorbispay, VDT, timestamp);
647   }
648
649   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
650   payload = gst_rtp_buffer_get_payload (&rtp);
651   ppos = payload + rtpvorbispay->payload_pos;
652   fragmented = FALSE;
653
654   /* put buffer in packet, it either fits completely or needs to be fragmented
655    * over multiple RTP packets. */
656   do {
657     plen = MIN (rtpvorbispay->payload_left - 2, size);
658
659     GST_LOG_OBJECT (rtpvorbispay, "append %u bytes", plen);
660
661     /* data is copied in the payload with a 2 byte length header */
662     ppos[0] = ((plen - not_in_length) >> 8) & 0xff;
663     ppos[1] = ((plen - not_in_length) & 0xff);
664     if (plen)
665       memcpy (&ppos[2], data, plen);
666
667     if (buffer) {
668       if (!rtpvorbispay->packet_buffers
669           || rtpvorbispay->packet_buffers->data != (gpointer) buffer)
670         rtpvorbispay->packet_buffers =
671             g_list_prepend (rtpvorbispay->packet_buffers,
672             gst_buffer_ref (buffer));
673     } else {
674       GList *l;
675
676       for (l = rtpvorbispay->headers; l; l = l->next)
677         rtpvorbispay->packet_buffers =
678             g_list_prepend (rtpvorbispay->packet_buffers,
679             gst_buffer_ref (l->data));
680     }
681
682     /* only first (only) configuration cuts length field */
683     /* NOTE: spec (if any) is not clear on this ... */
684     not_in_length = 0;
685
686     size -= plen;
687     data += plen;
688
689     rtpvorbispay->payload_pos += plen + 2;
690     rtpvorbispay->payload_left -= plen + 2;
691
692     if (fragmented) {
693       if (size == 0)
694         /* last fragment, set F to 0x3. */
695         rtpvorbispay->payload_F = 0x3;
696       else
697         /* fragment continues, set F to 0x2. */
698         rtpvorbispay->payload_F = 0x2;
699     } else {
700       if (size > 0) {
701         /* fragmented packet starts, set F to 0x1, mark ourselves as
702          * fragmented. */
703         rtpvorbispay->payload_F = 0x1;
704         fragmented = TRUE;
705       }
706     }
707     if (fragmented) {
708       gst_rtp_buffer_unmap (&rtp);
709       /* fragmented packets are always flushed and have ptks of 0 */
710       rtpvorbispay->payload_pkts = 0;
711       ret = gst_rtp_vorbis_pay_flush_packet (rtpvorbispay);
712
713       if (size > 0) {
714         /* start new packet and get pointers. VDT stays the same. */
715         gst_rtp_vorbis_pay_init_packet (rtpvorbispay,
716             rtpvorbispay->payload_VDT, timestamp);
717         gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
718         payload = gst_rtp_buffer_get_payload (&rtp);
719         ppos = payload + rtpvorbispay->payload_pos;
720       }
721     } else {
722       /* unfragmented packet, update stats for next packet, size == 0 and we
723        * exit the while loop */
724       rtpvorbispay->payload_pkts++;
725       if (duration != GST_CLOCK_TIME_NONE)
726         rtpvorbispay->payload_duration += duration;
727     }
728   } while (size && ret == GST_FLOW_OK);
729
730   if (rtp.buffer)
731     gst_rtp_buffer_unmap (&rtp);
732
733 done:
734
735   return ret;
736 }
737
738 static GstFlowReturn
739 gst_rtp_vorbis_pay_handle_buffer (GstRTPBasePayload * basepayload,
740     GstBuffer * buffer)
741 {
742   GstRtpVorbisPay *rtpvorbispay;
743   GstFlowReturn ret;
744   GstMapInfo map;
745   gsize size;
746   guint8 *data;
747   GstClockTime duration, timestamp;
748   guint8 VDT;
749
750   rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
751
752   gst_buffer_map (buffer, &map, GST_MAP_READ);
753   data = map.data;
754   size = map.size;
755   duration = GST_BUFFER_DURATION (buffer);
756   timestamp = GST_BUFFER_PTS (buffer);
757
758   GST_LOG_OBJECT (rtpvorbispay, "size %" G_GSIZE_FORMAT
759       ", duration %" GST_TIME_FORMAT, size, GST_TIME_ARGS (duration));
760
761   if (G_UNLIKELY (size < 1))
762     goto wrong_size;
763
764   /* find packet type */
765   if (data[0] & 1) {
766     /* header */
767     if (data[0] == 1) {
768       /* identification, we need to parse this in order to get the clock rate. */
769       if (G_UNLIKELY (!gst_rtp_vorbis_pay_parse_id (basepayload, data, size)))
770         goto parse_id_failed;
771       VDT = 1;
772     } else if (data[0] == 3) {
773       /* comment */
774       VDT = 2;
775     } else if (data[0] == 5) {
776       /* setup */
777       VDT = 1;
778     } else
779       goto unknown_header;
780   } else
781     /* data */
782     VDT = 0;
783
784   /* we need to collect the headers and construct a config string from them */
785   if (VDT != 0) {
786     rtpvorbispay->need_headers = TRUE;
787     if (!rtpvorbispay->need_headers && VDT == 1) {
788       GST_INFO_OBJECT (rtpvorbispay, "getting new headers, replace existing");
789       g_list_free_full (rtpvorbispay->headers,
790           (GDestroyNotify) gst_buffer_unref);
791       rtpvorbispay->headers = NULL;
792     }
793     GST_DEBUG_OBJECT (rtpvorbispay, "collecting header");
794     /* append header to the list of headers, or replace
795      * if the same type of header was already in there.
796      *
797      * This prevents storing an infinite amount of e.g. comment headers, there
798      * must only be one */
799     gst_buffer_unmap (buffer, &map);
800
801     if (rtpvorbispay->headers) {
802       gboolean found = FALSE;
803       GList *l;
804       guint8 new_header_type;
805
806       gst_buffer_extract (buffer, 0, &new_header_type, 1);
807
808       for (l = rtpvorbispay->headers; l; l = l->next) {
809         GstBuffer *header = l->data;
810         guint8 header_type;
811
812         if (gst_buffer_extract (header, 0, &header_type, 1)
813             && header_type == new_header_type) {
814           found = TRUE;
815           gst_buffer_unref (header);
816           l->data = buffer;
817           break;
818         }
819       }
820       if (!found)
821         rtpvorbispay->headers = g_list_append (rtpvorbispay->headers, buffer);
822     } else {
823       rtpvorbispay->headers = g_list_append (rtpvorbispay->headers, buffer);
824     }
825
826     ret = GST_FLOW_OK;
827     goto done;
828   } else if (rtpvorbispay->headers && rtpvorbispay->need_headers) {
829     if (!gst_rtp_vorbis_pay_finish_headers (basepayload))
830       goto header_error;
831   }
832
833   /* there is a config request, see if we need to insert it */
834   if (rtpvorbispay->config_interval > 0 && rtpvorbispay->config_data) {
835     gboolean send_config = FALSE;
836     GstClockTime running_time =
837         gst_segment_to_running_time (&basepayload->segment, GST_FORMAT_TIME,
838         timestamp);
839
840     if (rtpvorbispay->last_config != -1) {
841       guint64 diff;
842
843       GST_LOG_OBJECT (rtpvorbispay,
844           "now %" GST_TIME_FORMAT ", last config %" GST_TIME_FORMAT,
845           GST_TIME_ARGS (running_time),
846           GST_TIME_ARGS (rtpvorbispay->last_config));
847
848       /* calculate diff between last config in milliseconds */
849       if (running_time > rtpvorbispay->last_config) {
850         diff = running_time - rtpvorbispay->last_config;
851       } else {
852         diff = 0;
853       }
854
855       GST_DEBUG_OBJECT (rtpvorbispay,
856           "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
857
858       /* bigger than interval, queue config */
859       if (GST_TIME_AS_SECONDS (diff) >= rtpvorbispay->config_interval) {
860         GST_DEBUG_OBJECT (rtpvorbispay, "time to send config");
861         send_config = TRUE;
862       }
863     } else {
864       /* no known previous config time, send now */
865       GST_DEBUG_OBJECT (rtpvorbispay, "no previous config time, send now");
866       send_config = TRUE;
867     }
868
869     if (send_config) {
870       /* we need to send config now first */
871       /* different TDT type forces flush */
872       gst_rtp_vorbis_pay_payload_buffer (rtpvorbispay, 1,
873           NULL, rtpvorbispay->config_data, rtpvorbispay->config_size,
874           timestamp, GST_CLOCK_TIME_NONE, rtpvorbispay->config_extra_len);
875
876       if (running_time != -1) {
877         rtpvorbispay->last_config = running_time;
878       }
879     }
880   }
881
882   ret =
883       gst_rtp_vorbis_pay_payload_buffer (rtpvorbispay, VDT, buffer, data, size,
884       timestamp, duration, 0);
885
886   gst_buffer_unmap (buffer, &map);
887   gst_buffer_unref (buffer);
888
889 done:
890   return ret;
891
892   /* ERRORS */
893 wrong_size:
894   {
895     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
896         ("Invalid packet size (1 < %" G_GSIZE_FORMAT ")", size), (NULL));
897     gst_buffer_unmap (buffer, &map);
898     gst_buffer_unref (buffer);
899     return GST_FLOW_OK;
900   }
901 parse_id_failed:
902   {
903     gst_buffer_unmap (buffer, &map);
904     gst_buffer_unref (buffer);
905     return GST_FLOW_ERROR;
906   }
907 unknown_header:
908   {
909     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
910         (NULL), ("Ignoring unknown header received"));
911     gst_buffer_unmap (buffer, &map);
912     gst_buffer_unref (buffer);
913     return GST_FLOW_OK;
914   }
915 header_error:
916   {
917     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
918         (NULL), ("Error initializing header config"));
919     gst_buffer_unmap (buffer, &map);
920     gst_buffer_unref (buffer);
921     return GST_FLOW_OK;
922   }
923 }
924
925 static gboolean
926 gst_rtp_vorbis_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
927 {
928   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (payload);
929
930   switch (GST_EVENT_TYPE (event)) {
931     case GST_EVENT_FLUSH_STOP:
932       gst_rtp_vorbis_pay_clear_packet (rtpvorbispay);
933       break;
934     default:
935       break;
936   }
937   /* false to let parent handle event as well */
938   return GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
939 }
940
941 static GstStateChangeReturn
942 gst_rtp_vorbis_pay_change_state (GstElement * element,
943     GstStateChange transition)
944 {
945   GstRtpVorbisPay *rtpvorbispay;
946   GstStateChangeReturn ret;
947
948   rtpvorbispay = GST_RTP_VORBIS_PAY (element);
949
950   switch (transition) {
951     default:
952       break;
953   }
954
955   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
956
957   switch (transition) {
958     case GST_STATE_CHANGE_PAUSED_TO_READY:
959       gst_rtp_vorbis_pay_cleanup (rtpvorbispay);
960       break;
961     default:
962       break;
963   }
964   return ret;
965 }
966
967 static void
968 gst_rtp_vorbis_pay_set_property (GObject * object, guint prop_id,
969     const GValue * value, GParamSpec * pspec)
970 {
971   GstRtpVorbisPay *rtpvorbispay;
972
973   rtpvorbispay = GST_RTP_VORBIS_PAY (object);
974
975   switch (prop_id) {
976     case PROP_CONFIG_INTERVAL:
977       rtpvorbispay->config_interval = g_value_get_uint (value);
978       break;
979     default:
980       break;
981   }
982 }
983
984 static void
985 gst_rtp_vorbis_pay_get_property (GObject * object, guint prop_id,
986     GValue * value, GParamSpec * pspec)
987 {
988   GstRtpVorbisPay *rtpvorbispay;
989
990   rtpvorbispay = GST_RTP_VORBIS_PAY (object);
991
992   switch (prop_id) {
993     case PROP_CONFIG_INTERVAL:
994       g_value_set_uint (value, rtpvorbispay->config_interval);
995       break;
996     default:
997       break;
998   }
999 }
1000
1001 gboolean
1002 gst_rtp_vorbis_pay_plugin_init (GstPlugin * plugin)
1003 {
1004   return gst_element_register (plugin, "rtpvorbispay",
1005       GST_RANK_SECONDARY, GST_TYPE_RTP_VORBIS_PAY);
1006 }