rtp{vorbis,theora}{pay,depay}: Cosmetic cleanup
[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_pad_template (gstelement_class,
114       gst_static_pad_template_get (&gst_rtp_vorbis_pay_src_template));
115   gst_element_class_add_pad_template (gstelement_class,
116       gst_static_pad_template_get (&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   if (rtpvorbispay->config_data)
160     g_free (rtpvorbispay->config_data);
161   rtpvorbispay->config_data = NULL;
162   rtpvorbispay->last_config = GST_CLOCK_TIME_NONE;
163 }
164
165 static gboolean
166 gst_rtp_vorbis_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
167 {
168   GstRtpVorbisPay *rtpvorbispay;
169   GstStructure *s;
170   const GValue *array;
171   gint asize, i;
172   GstBuffer *buf;
173   GstMapInfo map;
174
175   rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
176
177   s = gst_caps_get_structure (caps, 0);
178
179   rtpvorbispay->need_headers = TRUE;
180
181   if ((array = gst_structure_get_value (s, "streamheader")) == NULL)
182     goto done;
183
184   if (G_VALUE_TYPE (array) != GST_TYPE_ARRAY)
185     goto done;
186
187   if ((asize = gst_value_array_get_size (array)) < 3)
188     goto done;
189
190   for (i = 0; i < asize; i++) {
191     const GValue *value;
192
193     value = gst_value_array_get_value (array, i);
194     if ((buf = gst_value_get_buffer (value)) == NULL)
195       goto null_buffer;
196
197     gst_buffer_map (buf, &map, GST_MAP_READ);
198     if (map.size < 1)
199       goto invalid_streamheader;
200
201     /* no data packets allowed */
202     if ((map.data[0] & 1) == 0)
203       goto invalid_streamheader;
204
205     /* we need packets with id 1, 3, 5 */
206     if (map.data[0] != (i * 2) + 1)
207       goto invalid_streamheader;
208
209     if (i == 0) {
210       /* identification, we need to parse this in order to get the clock rate. */
211       if (G_UNLIKELY (!gst_rtp_vorbis_pay_parse_id (basepayload, map.data,
212                   map.size)))
213         goto parse_id_failed;
214     }
215     GST_DEBUG_OBJECT (rtpvorbispay, "collecting header %d", i);
216     rtpvorbispay->headers =
217         g_list_append (rtpvorbispay->headers, gst_buffer_ref (buf));
218     gst_buffer_unmap (buf, &map);
219   }
220   if (!gst_rtp_vorbis_pay_finish_headers (basepayload))
221     goto finish_failed;
222
223 done:
224   return TRUE;
225
226   /* ERRORS */
227 null_buffer:
228   {
229     GST_WARNING_OBJECT (rtpvorbispay, "streamheader with null buffer received");
230     return FALSE;
231   }
232 invalid_streamheader:
233   {
234     GST_WARNING_OBJECT (rtpvorbispay, "unable to parse initial header");
235     gst_buffer_unmap (buf, &map);
236     return FALSE;
237   }
238 parse_id_failed:
239   {
240     GST_WARNING_OBJECT (rtpvorbispay, "unable to parse initial header");
241     gst_buffer_unmap (buf, &map);
242     return FALSE;
243   }
244 finish_failed:
245   {
246     GST_WARNING_OBJECT (rtpvorbispay, "unable to finish headers");
247     return FALSE;
248   }
249 }
250
251 static void
252 gst_rtp_vorbis_pay_reset_packet (GstRtpVorbisPay * rtpvorbispay, guint8 VDT)
253 {
254   guint payload_len;
255   GstRTPBuffer rtp = { NULL };
256
257   GST_LOG_OBJECT (rtpvorbispay, "reset packet");
258
259   rtpvorbispay->payload_pos = 4;
260   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_READ, &rtp);
261   payload_len = gst_rtp_buffer_get_payload_len (&rtp);
262   gst_rtp_buffer_unmap (&rtp);
263   rtpvorbispay->payload_left = payload_len - 4;
264   rtpvorbispay->payload_duration = 0;
265   rtpvorbispay->payload_F = 0;
266   rtpvorbispay->payload_VDT = VDT;
267   rtpvorbispay->payload_pkts = 0;
268 }
269
270 static void
271 gst_rtp_vorbis_pay_init_packet (GstRtpVorbisPay * rtpvorbispay, guint8 VDT,
272     GstClockTime timestamp)
273 {
274   GST_LOG_OBJECT (rtpvorbispay, "starting new packet, VDT: %d", VDT);
275
276   gst_rtp_vorbis_pay_clear_packet (rtpvorbispay);
277
278   /* new packet allocate max packet size */
279   rtpvorbispay->packet =
280       gst_rtp_buffer_new_allocate_len (GST_RTP_BASE_PAYLOAD_MTU
281       (rtpvorbispay), 0, 0);
282   gst_rtp_vorbis_pay_reset_packet (rtpvorbispay, VDT);
283
284   GST_BUFFER_PTS (rtpvorbispay->packet) = timestamp;
285 }
286
287 static GstFlowReturn
288 gst_rtp_vorbis_pay_flush_packet (GstRtpVorbisPay * rtpvorbispay)
289 {
290   GstFlowReturn ret;
291   guint8 *payload;
292   guint hlen;
293   GstRTPBuffer rtp = { NULL };
294   GList *l;
295
296   /* check for empty packet */
297   if (!rtpvorbispay->packet || rtpvorbispay->payload_pos <= 4)
298     return GST_FLOW_OK;
299
300   GST_LOG_OBJECT (rtpvorbispay, "flushing packet");
301
302   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
303
304   /* fix header */
305   payload = gst_rtp_buffer_get_payload (&rtp);
306   /*
307    *  0                   1                   2                   3
308    *  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
309    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
310    * |                     Ident                     | F |VDT|# pkts.|
311    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
312    *
313    * F: Fragment type (0=none, 1=start, 2=cont, 3=end)
314    * VDT: Vorbis data type (0=vorbis, 1=config, 2=comment, 3=reserved)
315    * pkts: number of packets.
316    */
317   payload[0] = (rtpvorbispay->payload_ident >> 16) & 0xff;
318   payload[1] = (rtpvorbispay->payload_ident >> 8) & 0xff;
319   payload[2] = (rtpvorbispay->payload_ident) & 0xff;
320   payload[3] = (rtpvorbispay->payload_F & 0x3) << 6 |
321       (rtpvorbispay->payload_VDT & 0x3) << 4 |
322       (rtpvorbispay->payload_pkts & 0xf);
323
324   gst_rtp_buffer_unmap (&rtp);
325
326   /* shrink the buffer size to the last written byte */
327   hlen = gst_rtp_buffer_calc_header_len (0);
328   gst_buffer_resize (rtpvorbispay->packet, 0, hlen + rtpvorbispay->payload_pos);
329
330   GST_BUFFER_DURATION (rtpvorbispay->packet) = rtpvorbispay->payload_duration;
331
332   for (l = g_list_last (rtpvorbispay->packet_buffers); l; l = l->prev) {
333     GstBuffer *buf = GST_BUFFER_CAST (l->data);
334     gst_rtp_copy_meta (GST_ELEMENT_CAST (rtpvorbispay), rtpvorbispay->packet,
335         buf, g_quark_from_static_string (GST_META_TAG_AUDIO_STR));
336     gst_buffer_unref (buf);
337   }
338   g_list_free (rtpvorbispay->packet_buffers);
339   rtpvorbispay->packet_buffers = NULL;
340
341   /* push, this gives away our ref to the packet, so clear it. */
342   ret =
343       gst_rtp_base_payload_push (GST_RTP_BASE_PAYLOAD (rtpvorbispay),
344       rtpvorbispay->packet);
345   rtpvorbispay->packet = NULL;
346
347   return ret;
348 }
349
350 static gboolean
351 gst_rtp_vorbis_pay_finish_headers (GstRTPBasePayload * basepayload)
352 {
353   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
354   GList *walk;
355   guint length, size, n_headers, configlen, extralen;
356   gchar *cstr, *configuration;
357   guint8 *data, *config;
358   guint32 ident;
359   gboolean res;
360
361   GST_DEBUG_OBJECT (rtpvorbispay, "finish headers");
362
363   if (!rtpvorbispay->headers)
364     goto no_headers;
365
366   /* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
367    * |                     Number of packed headers                  |
368    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
369    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
370    * |                          Packed header                        |
371    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
372    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
373    * |                          Packed header                        |
374    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
375    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
376    * |                          ....                                 |
377    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
378    *
379    * We only construct a config containing 1 packed header like this:
380    *
381    *  0                   1                   2                   3
382    *  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
383    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
384    * |                   Ident                       | length       ..
385    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
386    * ..              | n. of headers |    length1    |    length2   ..
387    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
388    * ..              |             Identification Header            ..
389    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
390    * .................................................................
391    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
392    * ..              |         Comment Header                       ..
393    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
394    * .................................................................
395    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
396    * ..                        Comment Header                        |
397    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
398    * |                          Setup Header                        ..
399    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
400    * .................................................................
401    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
402    * ..                         Setup Header                         |
403    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
404    */
405
406   /* we need 4 bytes for the number of headers (which is always 1), 3 bytes for
407    * the ident, 2 bytes for length, 1 byte for n. of headers. */
408   size = 4 + 3 + 2 + 1;
409
410   /* count the size of the headers first and update the hash */
411   length = 0;
412   n_headers = 0;
413   ident = fnv1_hash_32_new ();
414   extralen = 1;
415   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
416     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
417     GstMapInfo map;
418     guint bsize;
419
420     bsize = gst_buffer_get_size (buf);
421     length += bsize;
422     n_headers++;
423
424     /* count number of bytes needed for length fields, we don't need this for
425      * the last header. */
426     if (g_list_next (walk)) {
427       do {
428         size++;
429         extralen++;
430         bsize >>= 7;
431       } while (bsize);
432     }
433     /* update hash */
434     gst_buffer_map (buf, &map, GST_MAP_READ);
435     ident = fnv1_hash_32_update (ident, map.data, map.size);
436     gst_buffer_unmap (buf, &map);
437   }
438
439   /* packet length is header size + packet length */
440   configlen = size + length;
441   config = data = g_malloc (configlen);
442
443   /* number of packed headers, we only pack 1 header */
444   data[0] = 0;
445   data[1] = 0;
446   data[2] = 0;
447   data[3] = 1;
448
449   ident = fnv1_hash_32_to_24 (ident);
450   rtpvorbispay->payload_ident = ident;
451   GST_DEBUG_OBJECT (rtpvorbispay, "ident 0x%08x", ident);
452
453   /* take lower 3 bytes */
454   data[4] = (ident >> 16) & 0xff;
455   data[5] = (ident >> 8) & 0xff;
456   data[6] = ident & 0xff;
457
458   /* store length of all vorbis headers */
459   data[7] = ((length) >> 8) & 0xff;
460   data[8] = (length) & 0xff;
461
462   /* store number of headers minus one. */
463   data[9] = n_headers - 1;
464   data += 10;
465
466   /* store length for each header */
467   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
468     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
469     guint bsize, size, temp;
470     guint flag;
471
472     /* only need to store the length when it's not the last header */
473     if (!g_list_next (walk))
474       break;
475
476     bsize = gst_buffer_get_size (buf);
477
478     /* calc size */
479     size = 0;
480     do {
481       size++;
482       bsize >>= 7;
483     } while (bsize);
484     temp = size;
485
486     bsize = gst_buffer_get_size (buf);
487     /* write the size backwards */
488     flag = 0;
489     while (size) {
490       size--;
491       data[size] = (bsize & 0x7f) | flag;
492       bsize >>= 7;
493       flag = 0x80;              /* Flag bit on all bytes of the length except the last */
494     }
495     data += temp;
496   }
497
498   /* copy header data */
499   for (walk = rtpvorbispay->headers; walk; walk = g_list_next (walk)) {
500     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
501
502     gst_buffer_extract (buf, 0, data, gst_buffer_get_size (buf));
503     data += gst_buffer_get_size (buf);
504   }
505   rtpvorbispay->need_headers = FALSE;
506
507   /* serialize to base64 */
508   configuration = g_base64_encode (config, configlen);
509
510   /* store for later re-sending */
511   if (rtpvorbispay->config_data)
512     g_free (rtpvorbispay->config_data);
513   rtpvorbispay->config_size = configlen - 4 - 3 - 2;
514   rtpvorbispay->config_data = g_malloc (rtpvorbispay->config_size);
515   rtpvorbispay->config_extra_len = extralen;
516   memcpy (rtpvorbispay->config_data, config + 4 + 3 + 2,
517       rtpvorbispay->config_size);
518
519   g_free (config);
520
521   /* configure payloader settings */
522   cstr = g_strdup_printf ("%d", rtpvorbispay->channels);
523   gst_rtp_base_payload_set_options (basepayload, "audio", TRUE, "VORBIS",
524       rtpvorbispay->rate);
525   res =
526       gst_rtp_base_payload_set_outcaps (basepayload, "encoding-params",
527       G_TYPE_STRING, cstr, "configuration", G_TYPE_STRING, configuration, NULL);
528   g_free (cstr);
529   g_free (configuration);
530
531   return res;
532
533   /* ERRORS */
534 no_headers:
535   {
536     GST_DEBUG_OBJECT (rtpvorbispay, "finish headers");
537     return FALSE;
538   }
539 }
540
541 static gboolean
542 gst_rtp_vorbis_pay_parse_id (GstRTPBasePayload * basepayload, guint8 * data,
543     guint size)
544 {
545   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
546   guint8 channels;
547   gint32 rate, version;
548
549   if (G_UNLIKELY (size < 16))
550     goto too_short;
551
552   if (G_UNLIKELY (memcmp (data, "\001vorbis", 7)))
553     goto invalid_start;
554   data += 7;
555
556   if (G_UNLIKELY ((version = GST_READ_UINT32_LE (data)) != 0))
557     goto invalid_version;
558   data += 4;
559
560   if (G_UNLIKELY ((channels = *data++) < 1))
561     goto invalid_channels;
562
563   if (G_UNLIKELY ((rate = GST_READ_UINT32_LE (data)) < 1))
564     goto invalid_rate;
565
566   /* all fine, store the values */
567   rtpvorbispay->channels = channels;
568   rtpvorbispay->rate = rate;
569
570   return TRUE;
571
572   /* ERRORS */
573 too_short:
574   {
575     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
576         ("Identification packet is too short, need at least 16, got %d", size),
577         (NULL));
578     return FALSE;
579   }
580 invalid_start:
581   {
582     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
583         ("Invalid header start in identification packet"), (NULL));
584     return FALSE;
585   }
586 invalid_version:
587   {
588     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
589         ("Invalid version, expected 0, got %d", version), (NULL));
590     return FALSE;
591   }
592 invalid_rate:
593   {
594     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
595         ("Invalid rate %d", rate), (NULL));
596     return FALSE;
597   }
598 invalid_channels:
599   {
600     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
601         ("Invalid channels %d", channels), (NULL));
602     return FALSE;
603   }
604 }
605
606 static GstFlowReturn
607 gst_rtp_vorbis_pay_payload_buffer (GstRtpVorbisPay * rtpvorbispay, guint8 VDT,
608     GstBuffer * buffer, guint8 * data, guint size, GstClockTime timestamp,
609     GstClockTime duration, guint not_in_length)
610 {
611   GstFlowReturn ret = GST_FLOW_OK;
612   guint newsize;
613   guint packet_len;
614   GstClockTime newduration;
615   gboolean flush;
616   guint plen;
617   guint8 *ppos, *payload;
618   gboolean fragmented;
619   GstRTPBuffer rtp = { NULL };
620
621   /* size increases with packet length and 2 bytes size eader. */
622   newduration = rtpvorbispay->payload_duration;
623   if (duration != GST_CLOCK_TIME_NONE)
624     newduration += duration;
625
626   newsize = rtpvorbispay->payload_pos + 2 + size;
627   packet_len = gst_rtp_buffer_calc_packet_len (newsize, 0, 0);
628
629   /* check buffer filled against length and max latency */
630   flush = gst_rtp_base_payload_is_filled (GST_RTP_BASE_PAYLOAD (rtpvorbispay),
631       packet_len, newduration);
632   /* we can store up to 15 vorbis packets in one RTP packet. */
633   flush |= (rtpvorbispay->payload_pkts == 15);
634   /* flush if we have a new VDT */
635   if (rtpvorbispay->packet)
636     flush |= (rtpvorbispay->payload_VDT != VDT);
637   if (flush)
638     ret = gst_rtp_vorbis_pay_flush_packet (rtpvorbispay);
639
640   if (ret != GST_FLOW_OK)
641     goto done;
642
643   /* create new packet if we must */
644   if (!rtpvorbispay->packet) {
645     gst_rtp_vorbis_pay_init_packet (rtpvorbispay, VDT, timestamp);
646   }
647
648   gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
649   payload = gst_rtp_buffer_get_payload (&rtp);
650   ppos = payload + rtpvorbispay->payload_pos;
651   fragmented = FALSE;
652
653   /* put buffer in packet, it either fits completely or needs to be fragmented
654    * over multiple RTP packets. */
655   do {
656     plen = MIN (rtpvorbispay->payload_left - 2, size);
657
658     GST_LOG_OBJECT (rtpvorbispay, "append %u bytes", plen);
659
660     /* data is copied in the payload with a 2 byte length header */
661     ppos[0] = ((plen - not_in_length) >> 8) & 0xff;
662     ppos[1] = ((plen - not_in_length) & 0xff);
663     if (plen)
664       memcpy (&ppos[2], data, plen);
665
666     if (buffer) {
667       if (!rtpvorbispay->packet_buffers
668           || rtpvorbispay->packet_buffers->data != (gpointer) buffer)
669         rtpvorbispay->packet_buffers =
670             g_list_prepend (rtpvorbispay->packet_buffers,
671             gst_buffer_ref (buffer));
672     } else {
673       GList *l;
674
675       for (l = rtpvorbispay->headers; l; l = l->next)
676         rtpvorbispay->packet_buffers =
677             g_list_prepend (rtpvorbispay->packet_buffers,
678             gst_buffer_ref (l->data));
679     }
680
681     /* only first (only) configuration cuts length field */
682     /* NOTE: spec (if any) is not clear on this ... */
683     not_in_length = 0;
684
685     size -= plen;
686     data += plen;
687
688     rtpvorbispay->payload_pos += plen + 2;
689     rtpvorbispay->payload_left -= plen + 2;
690
691     if (fragmented) {
692       if (size == 0)
693         /* last fragment, set F to 0x3. */
694         rtpvorbispay->payload_F = 0x3;
695       else
696         /* fragment continues, set F to 0x2. */
697         rtpvorbispay->payload_F = 0x2;
698     } else {
699       if (size > 0) {
700         /* fragmented packet starts, set F to 0x1, mark ourselves as
701          * fragmented. */
702         rtpvorbispay->payload_F = 0x1;
703         fragmented = TRUE;
704       }
705     }
706     if (fragmented) {
707       gst_rtp_buffer_unmap (&rtp);
708       /* fragmented packets are always flushed and have ptks of 0 */
709       rtpvorbispay->payload_pkts = 0;
710       ret = gst_rtp_vorbis_pay_flush_packet (rtpvorbispay);
711
712       if (size > 0) {
713         /* start new packet and get pointers. VDT stays the same. */
714         gst_rtp_vorbis_pay_init_packet (rtpvorbispay,
715             rtpvorbispay->payload_VDT, timestamp);
716         gst_rtp_buffer_map (rtpvorbispay->packet, GST_MAP_WRITE, &rtp);
717         payload = gst_rtp_buffer_get_payload (&rtp);
718         ppos = payload + rtpvorbispay->payload_pos;
719       }
720     } else {
721       /* unfragmented packet, update stats for next packet, size == 0 and we
722        * exit the while loop */
723       rtpvorbispay->payload_pkts++;
724       if (duration != GST_CLOCK_TIME_NONE)
725         rtpvorbispay->payload_duration += duration;
726     }
727   } while (size && ret == GST_FLOW_OK);
728
729   if (rtp.buffer)
730     gst_rtp_buffer_unmap (&rtp);
731
732 done:
733
734   return ret;
735 }
736
737 static GstFlowReturn
738 gst_rtp_vorbis_pay_handle_buffer (GstRTPBasePayload * basepayload,
739     GstBuffer * buffer)
740 {
741   GstRtpVorbisPay *rtpvorbispay;
742   GstFlowReturn ret;
743   GstMapInfo map;
744   gsize size;
745   guint8 *data;
746   GstClockTime duration, timestamp;
747   guint8 VDT;
748
749   rtpvorbispay = GST_RTP_VORBIS_PAY (basepayload);
750
751   gst_buffer_map (buffer, &map, GST_MAP_READ);
752   data = map.data;
753   size = map.size;
754   duration = GST_BUFFER_DURATION (buffer);
755   timestamp = GST_BUFFER_PTS (buffer);
756
757   GST_LOG_OBJECT (rtpvorbispay, "size %" G_GSIZE_FORMAT
758       ", duration %" GST_TIME_FORMAT, size, GST_TIME_ARGS (duration));
759
760   if (G_UNLIKELY (size < 1))
761     goto wrong_size;
762
763   /* find packet type */
764   if (data[0] & 1) {
765     /* header */
766     if (data[0] == 1) {
767       /* identification, we need to parse this in order to get the clock rate. */
768       if (G_UNLIKELY (!gst_rtp_vorbis_pay_parse_id (basepayload, data, size)))
769         goto parse_id_failed;
770       VDT = 1;
771     } else if (data[0] == 3) {
772       /* comment */
773       VDT = 2;
774     } else if (data[0] == 5) {
775       /* setup */
776       VDT = 1;
777     } else
778       goto unknown_header;
779   } else
780     /* data */
781     VDT = 0;
782
783   /* we need to collect the headers and construct a config string from them */
784   if (VDT != 0) {
785     GST_DEBUG_OBJECT (rtpvorbispay, "collecting header");
786     /* append header to the list of headers */
787     gst_buffer_unmap (buffer, &map);
788     rtpvorbispay->headers = g_list_append (rtpvorbispay->headers, buffer);
789     ret = GST_FLOW_OK;
790     goto done;
791   } else if (rtpvorbispay->headers && rtpvorbispay->need_headers) {
792     if (!gst_rtp_vorbis_pay_finish_headers (basepayload))
793       goto header_error;
794   }
795
796   /* there is a config request, see if we need to insert it */
797   if (rtpvorbispay->config_interval > 0 && rtpvorbispay->config_data) {
798     gboolean send_config = FALSE;
799
800     if (rtpvorbispay->last_config != -1) {
801       guint64 diff;
802
803       GST_LOG_OBJECT (rtpvorbispay,
804           "now %" GST_TIME_FORMAT ", last config %" GST_TIME_FORMAT,
805           GST_TIME_ARGS (timestamp), GST_TIME_ARGS (rtpvorbispay->last_config));
806
807       /* calculate diff between last config in milliseconds */
808       if (timestamp > rtpvorbispay->last_config) {
809         diff = timestamp - rtpvorbispay->last_config;
810       } else {
811         diff = 0;
812       }
813
814       GST_DEBUG_OBJECT (rtpvorbispay,
815           "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
816
817       /* bigger than interval, queue config */
818       /* FIXME should convert timestamps to running time */
819       if (GST_TIME_AS_SECONDS (diff) >= rtpvorbispay->config_interval) {
820         GST_DEBUG_OBJECT (rtpvorbispay, "time to send config");
821         send_config = TRUE;
822       }
823     } else {
824       /* no known previous config time, send now */
825       GST_DEBUG_OBJECT (rtpvorbispay, "no previous config time, send now");
826       send_config = TRUE;
827     }
828
829     if (send_config) {
830       /* we need to send config now first */
831       /* different TDT type forces flush */
832       gst_rtp_vorbis_pay_payload_buffer (rtpvorbispay, 1,
833           NULL, rtpvorbispay->config_data, rtpvorbispay->config_size,
834           timestamp, GST_CLOCK_TIME_NONE, rtpvorbispay->config_extra_len);
835
836       if (timestamp != -1) {
837         rtpvorbispay->last_config = timestamp;
838       }
839     }
840   }
841
842   ret =
843       gst_rtp_vorbis_pay_payload_buffer (rtpvorbispay, VDT, buffer, data, size,
844       timestamp, duration, 0);
845
846   gst_buffer_unmap (buffer, &map);
847   gst_buffer_unref (buffer);
848
849 done:
850   return ret;
851
852   /* ERRORS */
853 wrong_size:
854   {
855     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
856         ("Invalid packet size (1 < %" G_GSIZE_FORMAT ")", size), (NULL));
857     gst_buffer_unmap (buffer, &map);
858     gst_buffer_unref (buffer);
859     return GST_FLOW_OK;
860   }
861 parse_id_failed:
862   {
863     gst_buffer_unmap (buffer, &map);
864     gst_buffer_unref (buffer);
865     return GST_FLOW_ERROR;
866   }
867 unknown_header:
868   {
869     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
870         (NULL), ("Ignoring unknown header received"));
871     gst_buffer_unmap (buffer, &map);
872     gst_buffer_unref (buffer);
873     return GST_FLOW_OK;
874   }
875 header_error:
876   {
877     GST_ELEMENT_WARNING (rtpvorbispay, STREAM, DECODE,
878         (NULL), ("Error initializing header config"));
879     gst_buffer_unmap (buffer, &map);
880     gst_buffer_unref (buffer);
881     return GST_FLOW_OK;
882   }
883 }
884
885 static gboolean
886 gst_rtp_vorbis_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
887 {
888   GstRtpVorbisPay *rtpvorbispay = GST_RTP_VORBIS_PAY (payload);
889
890   switch (GST_EVENT_TYPE (event)) {
891     case GST_EVENT_FLUSH_STOP:
892       gst_rtp_vorbis_pay_clear_packet (rtpvorbispay);
893       break;
894     default:
895       break;
896   }
897   /* false to let parent handle event as well */
898   return GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
899 }
900
901 static GstStateChangeReturn
902 gst_rtp_vorbis_pay_change_state (GstElement * element,
903     GstStateChange transition)
904 {
905   GstRtpVorbisPay *rtpvorbispay;
906   GstStateChangeReturn ret;
907
908   rtpvorbispay = GST_RTP_VORBIS_PAY (element);
909
910   switch (transition) {
911     default:
912       break;
913   }
914
915   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
916
917   switch (transition) {
918     case GST_STATE_CHANGE_PAUSED_TO_READY:
919       gst_rtp_vorbis_pay_cleanup (rtpvorbispay);
920       break;
921     default:
922       break;
923   }
924   return ret;
925 }
926
927 static void
928 gst_rtp_vorbis_pay_set_property (GObject * object, guint prop_id,
929     const GValue * value, GParamSpec * pspec)
930 {
931   GstRtpVorbisPay *rtpvorbispay;
932
933   rtpvorbispay = GST_RTP_VORBIS_PAY (object);
934
935   switch (prop_id) {
936     case PROP_CONFIG_INTERVAL:
937       rtpvorbispay->config_interval = g_value_get_uint (value);
938       break;
939     default:
940       break;
941   }
942 }
943
944 static void
945 gst_rtp_vorbis_pay_get_property (GObject * object, guint prop_id,
946     GValue * value, GParamSpec * pspec)
947 {
948   GstRtpVorbisPay *rtpvorbispay;
949
950   rtpvorbispay = GST_RTP_VORBIS_PAY (object);
951
952   switch (prop_id) {
953     case PROP_CONFIG_INTERVAL:
954       g_value_set_uint (value, rtpvorbispay->config_interval);
955       break;
956     default:
957       break;
958   }
959 }
960
961 gboolean
962 gst_rtp_vorbis_pay_plugin_init (GstPlugin * plugin)
963 {
964   return gst_element_register (plugin, "rtpvorbispay",
965       GST_RANK_SECONDARY, GST_TYPE_RTP_VORBIS_PAY);
966 }