Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtptheorapay.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., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, 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
28 #include "fnv1hash.h"
29 #include "gstrtptheorapay.h"
30
31 #define THEORA_ID_LEN   42
32
33 GST_DEBUG_CATEGORY_STATIC (rtptheorapay_debug);
34 #define GST_CAT_DEFAULT (rtptheorapay_debug)
35
36 /* references:
37  * http://svn.xiph.org/trunk/theora/doc/draft-ietf-avt-rtp-theora-01.txt
38  */
39
40 static GstStaticPadTemplate gst_rtp_theora_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) \"video\", "
46         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
47         "clock-rate = (int) 90000, " "encoding-name = (string) \"THEORA\""
48         /* All required parameters
49          *
50          * "sampling = (string) { "YCbCr-4:2:0", "YCbCr-4:2:2", "YCbCr-4:4:4" } "
51          * "width = (string) [1, 1048561] (multiples of 16) "
52          * "height = (string) [1, 1048561] (multiples of 16) "
53          * "configuration = (string) ANY"
54          */
55         /* All optional parameters
56          *
57          * "configuration-uri ="
58          * "delivery-method = (string) { inline, in_band, out_band/<specific_name> } "
59          */
60     )
61     );
62
63 static GstStaticPadTemplate gst_rtp_theora_pay_sink_template =
64 GST_STATIC_PAD_TEMPLATE ("sink",
65     GST_PAD_SINK,
66     GST_PAD_ALWAYS,
67     GST_STATIC_CAPS ("video/x-theora")
68     );
69
70 #define DEFAULT_CONFIG_INTERVAL 0
71
72 enum
73 {
74   PROP_0,
75   PROP_CONFIG_INTERVAL
76 };
77
78 #define gst_rtp_theora_pay_parent_class parent_class
79 G_DEFINE_TYPE (GstRtpTheoraPay, gst_rtp_theora_pay, GST_TYPE_RTP_BASE_PAYLOAD);
80
81 static gboolean gst_rtp_theora_pay_setcaps (GstRTPBasePayload * basepayload,
82     GstCaps * caps);
83 static GstStateChangeReturn gst_rtp_theora_pay_change_state (GstElement *
84     element, GstStateChange transition);
85 static GstFlowReturn gst_rtp_theora_pay_handle_buffer (GstRTPBasePayload * pad,
86     GstBuffer * buffer);
87 static gboolean gst_rtp_theora_pay_sink_event (GstRTPBasePayload * payload,
88     GstEvent * event);
89
90
91 static void gst_rtp_theora_pay_set_property (GObject * object, guint prop_id,
92     const GValue * value, GParamSpec * pspec);
93 static void gst_rtp_theora_pay_get_property (GObject * object, guint prop_id,
94     GValue * value, GParamSpec * pspec);
95
96 static void
97 gst_rtp_theora_pay_class_init (GstRtpTheoraPayClass * klass)
98 {
99   GObjectClass *gobject_class;
100   GstElementClass *gstelement_class;
101   GstRTPBasePayloadClass *gstrtpbasepayload_class;
102
103   gobject_class = (GObjectClass *) klass;
104   gstelement_class = (GstElementClass *) klass;
105   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
106
107   gstelement_class->change_state = gst_rtp_theora_pay_change_state;
108
109   gstrtpbasepayload_class->set_caps = gst_rtp_theora_pay_setcaps;
110   gstrtpbasepayload_class->handle_buffer = gst_rtp_theora_pay_handle_buffer;
111   gstrtpbasepayload_class->sink_event = gst_rtp_theora_pay_sink_event;
112
113   gobject_class->set_property = gst_rtp_theora_pay_set_property;
114   gobject_class->get_property = gst_rtp_theora_pay_get_property;
115
116   gst_element_class_add_pad_template (gstelement_class,
117       gst_static_pad_template_get (&gst_rtp_theora_pay_src_template));
118   gst_element_class_add_pad_template (gstelement_class,
119       gst_static_pad_template_get (&gst_rtp_theora_pay_sink_template));
120
121   gst_element_class_set_details_simple (gstelement_class,
122       "RTP Theora payloader", "Codec/Payloader/Network/RTP",
123       "Payload-encode Theora video into RTP packets (draft-01 RFC XXXX)",
124       "Wim Taymans <wim.taymans@gmail.com>");
125
126   GST_DEBUG_CATEGORY_INIT (rtptheorapay_debug, "rtptheorapay", 0,
127       "Theora RTP Payloader");
128
129   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CONFIG_INTERVAL,
130       g_param_spec_uint ("config-interval", "Config Send Interval",
131           "Send Config Insertion Interval in seconds (configuration headers "
132           "will be multiplexed in the data stream when detected.) (0 = disabled)",
133           0, 3600, DEFAULT_CONFIG_INTERVAL,
134           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
135       );
136 }
137
138 static void
139 gst_rtp_theora_pay_init (GstRtpTheoraPay * rtptheorapay)
140 {
141   rtptheorapay->last_config = GST_CLOCK_TIME_NONE;
142 }
143
144 static void
145 gst_rtp_theora_pay_clear_packet (GstRtpTheoraPay * rtptheorapay)
146 {
147   if (rtptheorapay->packet)
148     gst_buffer_unref (rtptheorapay->packet);
149   rtptheorapay->packet = NULL;
150 }
151
152 static void
153 gst_rtp_theora_pay_cleanup (GstRtpTheoraPay * rtptheorapay)
154 {
155   g_list_foreach (rtptheorapay->headers, (GFunc) gst_mini_object_unref, NULL);
156   g_list_free (rtptheorapay->headers);
157   rtptheorapay->headers = NULL;
158
159   gst_rtp_theora_pay_clear_packet (rtptheorapay);
160
161   if (rtptheorapay->config_data)
162     g_free (rtptheorapay->config_data);
163   rtptheorapay->config_data = NULL;
164   rtptheorapay->last_config = GST_CLOCK_TIME_NONE;
165 }
166
167 static gboolean
168 gst_rtp_theora_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
169 {
170   GstRtpTheoraPay *rtptheorapay;
171
172   rtptheorapay = GST_RTP_THEORA_PAY (basepayload);
173
174   rtptheorapay->need_headers = TRUE;
175
176   return TRUE;
177 }
178
179 static void
180 gst_rtp_theora_pay_reset_packet (GstRtpTheoraPay * rtptheorapay, guint8 TDT)
181 {
182   guint payload_len;
183   GstRTPBuffer rtp = { NULL };
184
185   GST_DEBUG_OBJECT (rtptheorapay, "reset packet");
186
187   rtptheorapay->payload_pos = 4;
188   gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_READ, &rtp);
189   payload_len = gst_rtp_buffer_get_payload_len (&rtp);
190   gst_rtp_buffer_unmap (&rtp);
191   rtptheorapay->payload_left = payload_len - 4;
192   rtptheorapay->payload_duration = 0;
193   rtptheorapay->payload_F = 0;
194   rtptheorapay->payload_TDT = TDT;
195   rtptheorapay->payload_pkts = 0;
196 }
197
198 static void
199 gst_rtp_theora_pay_init_packet (GstRtpTheoraPay * rtptheorapay, guint8 TDT,
200     GstClockTime timestamp)
201 {
202   GST_DEBUG_OBJECT (rtptheorapay, "starting new packet, TDT: %d", TDT);
203
204   if (rtptheorapay->packet)
205     gst_buffer_unref (rtptheorapay->packet);
206
207   /* new packet allocate max packet size */
208   rtptheorapay->packet =
209       gst_rtp_buffer_new_allocate_len (GST_RTP_BASE_PAYLOAD_MTU
210       (rtptheorapay), 0, 0);
211   gst_rtp_theora_pay_reset_packet (rtptheorapay, TDT);
212
213   GST_BUFFER_TIMESTAMP (rtptheorapay->packet) = timestamp;
214 }
215
216 static GstFlowReturn
217 gst_rtp_theora_pay_flush_packet (GstRtpTheoraPay * rtptheorapay)
218 {
219   GstFlowReturn ret;
220   guint8 *payload;
221   guint hlen;
222   GstRTPBuffer rtp = { NULL };
223
224   /* check for empty packet */
225   if (!rtptheorapay->packet || rtptheorapay->payload_pos <= 4)
226     return GST_FLOW_OK;
227
228   GST_DEBUG_OBJECT (rtptheorapay, "flushing packet");
229
230   gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp);
231
232   /* fix header */
233   payload = gst_rtp_buffer_get_payload (&rtp);
234   /*
235    *  0                   1                   2                   3
236    *  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
237    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
238    * |                     Ident                     | F |TDT|# pkts.|
239    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
240    *
241    * F: Fragment type (0=none, 1=start, 2=cont, 3=end)
242    * TDT: Theora data type (0=theora, 1=config, 2=comment, 3=reserved)
243    * pkts: number of packets.
244    */
245   payload[0] = (rtptheorapay->payload_ident >> 16) & 0xff;
246   payload[1] = (rtptheorapay->payload_ident >> 8) & 0xff;
247   payload[2] = (rtptheorapay->payload_ident) & 0xff;
248   payload[3] = (rtptheorapay->payload_F & 0x3) << 6 |
249       (rtptheorapay->payload_TDT & 0x3) << 4 |
250       (rtptheorapay->payload_pkts & 0xf);
251
252   gst_rtp_buffer_unmap (&rtp);
253
254   /* shrink the buffer size to the last written byte */
255   hlen = gst_rtp_buffer_calc_header_len (0);
256   gst_buffer_resize (rtptheorapay->packet, 0, hlen + rtptheorapay->payload_pos);
257
258   GST_BUFFER_DURATION (rtptheorapay->packet) = rtptheorapay->payload_duration;
259
260   /* push, this gives away our ref to the packet, so clear it. */
261   ret =
262       gst_rtp_base_payload_push (GST_RTP_BASE_PAYLOAD (rtptheorapay),
263       rtptheorapay->packet);
264   rtptheorapay->packet = NULL;
265
266   return ret;
267 }
268
269 static gboolean
270 gst_rtp_theora_pay_finish_headers (GstRTPBasePayload * basepayload)
271 {
272   GstRtpTheoraPay *rtptheorapay = GST_RTP_THEORA_PAY (basepayload);
273   GList *walk;
274   guint length, size, n_headers, configlen, extralen;
275   gchar *wstr, *hstr, *configuration;
276   guint8 *data, *config;
277   guint32 ident;
278   gboolean res;
279
280   GST_DEBUG_OBJECT (rtptheorapay, "finish headers");
281
282   if (!rtptheorapay->headers) {
283     GST_DEBUG_OBJECT (rtptheorapay, "We need 2 headers but have none");
284     goto no_headers;
285   }
286
287   /* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
288    * |                     Number of packed headers                  |
289    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
290    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
291    * |                          Packed header                        |
292    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
293    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
294    * |                          Packed header                        |
295    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
296    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
297    * |                          ....                                 |
298    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
299    *
300    * We only construct a config containing 1 packed header like this:
301    *
302    *  0                   1                   2                   3
303    *  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
304    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
305    * |                   Ident                       | length       ..
306    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
307    * ..              | n. of headers |    length1    |    length2   ..
308    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
309    * ..              |             Identification Header            ..
310    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
311    * .................................................................
312    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
313    * ..              |         Comment Header                       ..
314    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
315    * .................................................................
316    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
317    * ..                        Comment Header                        |
318    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
319    * |                          Setup Header                        ..
320    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
321    * .................................................................
322    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
323    * ..                         Setup Header                         |
324    * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
325    */
326
327   /* we need 4 bytes for the number of headers (which is always 1), 3 bytes for
328    * the ident, 2 bytes for length, 1 byte for n. of headers. */
329   size = 4 + 3 + 2 + 1;
330
331   /* count the size of the headers first and update the hash */
332   length = 0;
333   n_headers = 0;
334   ident = fnv1_hash_32_new ();
335   extralen = 1;
336   for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) {
337     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
338     GstMapInfo map;
339     guint bsize;
340
341     bsize = gst_buffer_get_size (buf);
342     length += bsize;
343     n_headers++;
344
345     /* count number of bytes needed for length fields, we don't need this for
346      * the last header. */
347     if (g_list_next (walk)) {
348       do {
349         size++;
350         extralen++;
351         bsize >>= 7;
352       } while (bsize);
353     }
354     /* update hash */
355     gst_buffer_map (buf, &map, GST_MAP_READ);
356     ident = fnv1_hash_32_update (ident, map.data, map.size);
357     gst_buffer_unmap (buf, &map);
358   }
359
360   /* packet length is header size + packet length */
361   configlen = size + length;
362   config = data = g_malloc (configlen);
363
364   /* number of packed headers, we only pack 1 header */
365   data[0] = 0;
366   data[1] = 0;
367   data[2] = 0;
368   data[3] = 1;
369
370   ident = fnv1_hash_32_to_24 (ident);
371   rtptheorapay->payload_ident = ident;
372   GST_DEBUG_OBJECT (rtptheorapay, "ident 0x%08x", ident);
373
374   /* take lower 3 bytes */
375   data[4] = (ident >> 16) & 0xff;
376   data[5] = (ident >> 8) & 0xff;
377   data[6] = ident & 0xff;
378
379   /* store length of all theora headers */
380   data[7] = ((length) >> 8) & 0xff;
381   data[8] = (length) & 0xff;
382
383   /* store number of headers minus one. */
384   data[9] = n_headers - 1;
385   data += 10;
386
387   /* store length for each header */
388   for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) {
389     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
390
391     guint bsize, size, temp;
392     guint flag;
393
394     /* only need to store the length when it's not the last header */
395     if (!g_list_next (walk))
396       break;
397
398     bsize = gst_buffer_get_size (buf);
399
400     /* calc size */
401     size = 0;
402     do {
403       size++;
404       bsize >>= 7;
405     } while (bsize);
406     temp = size;
407
408     bsize = gst_buffer_get_size (buf);
409     /* write the size backwards */
410     flag = 0;
411     while (size) {
412       size--;
413       data[size] = (bsize & 0x7f) | flag;
414       bsize >>= 7;
415       flag = 0x80;
416     }
417     data += temp;
418   }
419
420   /* copy header data */
421   for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) {
422     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
423     GstMapInfo map;
424
425     gst_buffer_map (buf, &map, GST_MAP_READ);
426     memcpy (data, map.data, map.size);
427     gst_buffer_unmap (buf, &map);
428     data += map.size;
429   }
430
431   /* serialize to base64 */
432   configuration = g_base64_encode (config, configlen);
433
434   /* store for later re-sending */
435   rtptheorapay->config_size = configlen - 4 - 3 - 2;
436   rtptheorapay->config_data = g_malloc (rtptheorapay->config_size);
437   rtptheorapay->config_extra_len = extralen;
438   memcpy (rtptheorapay->config_data, config + 4 + 3 + 2,
439       rtptheorapay->config_size);
440
441   g_free (config);
442
443   /* configure payloader settings */
444   wstr = g_strdup_printf ("%d", rtptheorapay->width);
445   hstr = g_strdup_printf ("%d", rtptheorapay->height);
446   gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "THEORA",
447       90000);
448   res =
449       gst_rtp_base_payload_set_outcaps (basepayload, "sampling", G_TYPE_STRING,
450       "YCbCr-4:2:0", "width", G_TYPE_STRING, wstr, "height", G_TYPE_STRING,
451       hstr, "configuration", G_TYPE_STRING, configuration, "delivery-method",
452       G_TYPE_STRING, "inline",
453       /* don't set the other defaults 
454        */
455       NULL);
456   g_free (wstr);
457   g_free (hstr);
458   g_free (configuration);
459
460   return res;
461
462   /* ERRORS */
463 no_headers:
464   {
465     GST_DEBUG_OBJECT (rtptheorapay, "finish headers");
466     return FALSE;
467   }
468 }
469
470 static gboolean
471 gst_rtp_theora_pay_parse_id (GstRTPBasePayload * basepayload, guint8 * data,
472     guint size)
473 {
474   GstRtpTheoraPay *rtptheorapay;
475   gint width, height;
476
477   rtptheorapay = GST_RTP_THEORA_PAY (basepayload);
478
479   if (G_UNLIKELY (size < 42))
480     goto too_short;
481
482   if (G_UNLIKELY (memcmp (data, "\200theora", 7)))
483     goto invalid_start;
484   data += 7;
485
486   if (G_UNLIKELY (data[0] != 3))
487     goto invalid_version;
488   if (G_UNLIKELY (data[1] != 2))
489     goto invalid_version;
490   data += 3;
491
492   width = GST_READ_UINT16_BE (data) << 4;
493   data += 2;
494   height = GST_READ_UINT16_BE (data) << 4;
495   data += 2;
496
497   /* FIXME, parse pixel format */
498
499   /* store values */
500   rtptheorapay->width = width;
501   rtptheorapay->height = height;
502
503   return TRUE;
504
505   /* ERRORS */
506 too_short:
507   {
508     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
509         (NULL),
510         ("Identification packet is too short, need at least 42, got %d", size));
511     return FALSE;
512   }
513 invalid_start:
514   {
515     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
516         (NULL), ("Invalid header start in identification packet"));
517     return FALSE;
518   }
519 invalid_version:
520   {
521     GST_ELEMENT_ERROR (basepayload, STREAM, DECODE,
522         (NULL), ("Invalid version"));
523     return FALSE;
524   }
525 }
526
527 static GstFlowReturn
528 gst_rtp_theora_pay_payload_buffer (GstRtpTheoraPay * rtptheorapay, guint8 TDT,
529     guint8 * data, guint size, GstClockTime timestamp, GstClockTime duration,
530     guint not_in_length)
531 {
532   GstFlowReturn ret = GST_FLOW_OK;
533   guint newsize;
534   guint packet_len;
535   GstClockTime newduration;
536   gboolean flush;
537   guint plen;
538   guint8 *ppos, *payload;
539   gboolean fragmented;
540   GstRTPBuffer rtp = { NULL };
541
542   /* size increases with packet length and 2 bytes size eader. */
543   newduration = rtptheorapay->payload_duration;
544   if (duration != GST_CLOCK_TIME_NONE)
545     newduration += duration;
546
547   newsize = rtptheorapay->payload_pos + 2 + size;
548   packet_len = gst_rtp_buffer_calc_packet_len (newsize, 0, 0);
549
550   /* check buffer filled against length and max latency */
551   flush = gst_rtp_base_payload_is_filled (GST_RTP_BASE_PAYLOAD (rtptheorapay),
552       packet_len, newduration);
553   /* we can store up to 15 theora packets in one RTP packet. */
554   flush |= (rtptheorapay->payload_pkts == 15);
555   /* flush if we have a new TDT */
556   if (rtptheorapay->packet)
557     flush |= (rtptheorapay->payload_TDT != TDT);
558   if (flush)
559     ret = gst_rtp_theora_pay_flush_packet (rtptheorapay);
560
561   /* create new packet if we must */
562   if (!rtptheorapay->packet) {
563     gst_rtp_theora_pay_init_packet (rtptheorapay, TDT, timestamp);
564   }
565
566   gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp);
567   payload = gst_rtp_buffer_get_payload (&rtp);
568   ppos = payload + rtptheorapay->payload_pos;
569   fragmented = FALSE;
570
571   /* put buffer in packet, it either fits completely or needs to be fragmented
572    * over multiple RTP packets. */
573   do {
574     plen = MIN (rtptheorapay->payload_left - 2, size);
575
576     GST_DEBUG_OBJECT (rtptheorapay, "append %u bytes", plen);
577
578     /* data is copied in the payload with a 2 byte length header */
579     ppos[0] = ((plen - not_in_length) >> 8) & 0xff;
580     ppos[1] = ((plen - not_in_length) & 0xff);
581     if (plen)
582       memcpy (&ppos[2], data, plen);
583
584     /* only first (only) configuration cuts length field */
585     /* NOTE: spec (if any) is not clear on this ... */
586     not_in_length = 0;
587
588     size -= plen;
589     data += plen;
590
591     rtptheorapay->payload_pos += plen + 2;
592     rtptheorapay->payload_left -= plen + 2;
593
594     if (fragmented) {
595       if (size == 0)
596         /* last fragment, set F to 0x3. */
597         rtptheorapay->payload_F = 0x3;
598       else
599         /* fragment continues, set F to 0x2. */
600         rtptheorapay->payload_F = 0x2;
601     } else {
602       if (size > 0) {
603         /* fragmented packet starts, set F to 0x1, mark ourselves as
604          * fragmented. */
605         rtptheorapay->payload_F = 0x1;
606         fragmented = TRUE;
607       }
608     }
609     if (fragmented) {
610       /* fragmented packets are always flushed and have ptks of 0 */
611       rtptheorapay->payload_pkts = 0;
612       gst_rtp_buffer_unmap (&rtp);
613       ret = gst_rtp_theora_pay_flush_packet (rtptheorapay);
614
615       if (size > 0) {
616         /* start new packet and get pointers. TDT stays the same. */
617         gst_rtp_theora_pay_init_packet (rtptheorapay,
618             rtptheorapay->payload_TDT, timestamp);
619         gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp);
620         payload = gst_rtp_buffer_get_payload (&rtp);
621         ppos = payload + rtptheorapay->payload_pos;
622       }
623     } else {
624       /* unfragmented packet, update stats for next packet, size == 0 and we
625        * exit the while loop */
626       rtptheorapay->payload_pkts++;
627       if (duration != GST_CLOCK_TIME_NONE)
628         rtptheorapay->payload_duration += duration;
629     }
630   } while (size);
631
632   if (rtp.buffer)
633     gst_rtp_buffer_unmap (&rtp);
634
635   return ret;
636 }
637
638 static GstFlowReturn
639 gst_rtp_theora_pay_handle_buffer (GstRTPBasePayload * basepayload,
640     GstBuffer * buffer)
641 {
642   GstRtpTheoraPay *rtptheorapay;
643   GstFlowReturn ret;
644   GstMapInfo map;
645   gsize size;
646   guint8 *data;
647   GstClockTime duration, timestamp;
648   guint8 TDT;
649   gboolean keyframe = FALSE;
650
651   rtptheorapay = GST_RTP_THEORA_PAY (basepayload);
652
653   gst_buffer_map (buffer, &map, GST_MAP_READ);
654   data = map.data;
655   size = map.size;
656   duration = GST_BUFFER_DURATION (buffer);
657   timestamp = GST_BUFFER_TIMESTAMP (buffer);
658
659   GST_DEBUG_OBJECT (rtptheorapay, "size %" G_GSIZE_FORMAT
660       ", duration %" GST_TIME_FORMAT, size, GST_TIME_ARGS (duration));
661
662   if (G_UNLIKELY (size > 0xffff))
663     goto wrong_size;
664
665   /* find packet type */
666   if (size == 0) {
667     TDT = 0;
668     keyframe = FALSE;
669   } else if (data[0] & 0x80) {
670     /* header */
671     if (data[0] == 0x80) {
672       /* identification, we need to parse this in order to get the clock rate.
673        */
674       if (G_UNLIKELY (!gst_rtp_theora_pay_parse_id (basepayload, data, size)))
675         goto parse_id_failed;
676       TDT = 1;
677     } else if (data[0] == 0x81) {
678       /* comment */
679       TDT = 2;
680     } else if (data[0] == 0x82) {
681       /* setup */
682       TDT = 1;
683     } else
684       goto unknown_header;
685   } else {
686     /* data */
687     TDT = 0;
688     keyframe = ((data[0] & 0x40) == 0);
689   }
690
691   if (rtptheorapay->need_headers) {
692     /* we need to collect the headers and construct a config string from them */
693     if (TDT != 0) {
694       GST_DEBUG_OBJECT (rtptheorapay, "collecting header, buffer %p", buffer);
695       /* append header to the list of headers */
696       gst_buffer_unmap (buffer, &map);
697       rtptheorapay->headers = g_list_append (rtptheorapay->headers, buffer);
698       ret = GST_FLOW_OK;
699       goto done;
700     } else {
701       if (!gst_rtp_theora_pay_finish_headers (basepayload))
702         goto header_error;
703       rtptheorapay->need_headers = FALSE;
704     }
705   }
706
707   /* there is a config request, see if we need to insert it */
708   if (keyframe && (rtptheorapay->config_interval > 0) &&
709       rtptheorapay->config_data) {
710     gboolean send_config = FALSE;
711
712     if (rtptheorapay->last_config != -1) {
713       guint64 diff;
714
715       GST_LOG_OBJECT (rtptheorapay,
716           "now %" GST_TIME_FORMAT ", last VOP-I %" GST_TIME_FORMAT,
717           GST_TIME_ARGS (timestamp), GST_TIME_ARGS (rtptheorapay->last_config));
718
719       /* calculate diff between last config in milliseconds */
720       if (timestamp > rtptheorapay->last_config) {
721         diff = timestamp - rtptheorapay->last_config;
722       } else {
723         diff = 0;
724       }
725
726       GST_DEBUG_OBJECT (rtptheorapay,
727           "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff));
728
729       /* bigger than interval, queue config */
730       /* FIXME should convert timestamps to running time */
731       if (GST_TIME_AS_SECONDS (diff) >= rtptheorapay->config_interval) {
732         GST_DEBUG_OBJECT (rtptheorapay, "time to send config");
733         send_config = TRUE;
734       }
735     } else {
736       /* no known previous config time, send now */
737       GST_DEBUG_OBJECT (rtptheorapay, "no previous config time, send now");
738       send_config = TRUE;
739     }
740
741     if (send_config) {
742       /* we need to send config now first */
743       /* different TDT type forces flush */
744       gst_rtp_theora_pay_payload_buffer (rtptheorapay, 1,
745           rtptheorapay->config_data, rtptheorapay->config_size,
746           timestamp, GST_CLOCK_TIME_NONE, rtptheorapay->config_extra_len);
747
748       if (timestamp != -1) {
749         rtptheorapay->last_config = timestamp;
750       }
751     }
752   }
753
754   ret = gst_rtp_theora_pay_payload_buffer (rtptheorapay, TDT, data, size,
755       timestamp, duration, 0);
756
757   gst_buffer_unmap (buffer, &map);
758   gst_buffer_unref (buffer);
759
760 done:
761   return ret;
762
763   /* ERRORS */
764 wrong_size:
765   {
766     GST_ELEMENT_WARNING (rtptheorapay, STREAM, DECODE,
767         ("Invalid packet size (%" G_GSIZE_FORMAT " <= 0xffff)", size), (NULL));
768     gst_buffer_unmap (buffer, &map);
769     gst_buffer_unref (buffer);
770     return GST_FLOW_OK;
771   }
772 parse_id_failed:
773   {
774     gst_buffer_unmap (buffer, &map);
775     gst_buffer_unref (buffer);
776     return GST_FLOW_ERROR;
777   }
778 unknown_header:
779   {
780     GST_ELEMENT_WARNING (rtptheorapay, STREAM, DECODE,
781         (NULL), ("Ignoring unknown header received"));
782     gst_buffer_unmap (buffer, &map);
783     gst_buffer_unref (buffer);
784     return GST_FLOW_OK;
785   }
786 header_error:
787   {
788     GST_ELEMENT_WARNING (rtptheorapay, STREAM, DECODE,
789         (NULL), ("Error initializing header config"));
790     gst_buffer_unmap (buffer, &map);
791     gst_buffer_unref (buffer);
792     return GST_FLOW_OK;
793   }
794 }
795
796 static gboolean
797 gst_rtp_theora_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
798 {
799   GstRtpTheoraPay *rtptheorapay = GST_RTP_THEORA_PAY (payload);
800
801   switch (GST_EVENT_TYPE (event)) {
802     case GST_EVENT_FLUSH_STOP:
803       gst_rtp_theora_pay_clear_packet (rtptheorapay);
804       break;
805     default:
806       break;
807   }
808   /* false to let parent handle event as well */
809   return GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
810 }
811
812 static GstStateChangeReturn
813 gst_rtp_theora_pay_change_state (GstElement * element,
814     GstStateChange transition)
815 {
816   GstRtpTheoraPay *rtptheorapay;
817
818   GstStateChangeReturn ret;
819
820   rtptheorapay = GST_RTP_THEORA_PAY (element);
821
822   switch (transition) {
823     default:
824       break;
825   }
826
827   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
828
829   switch (transition) {
830     case GST_STATE_CHANGE_PAUSED_TO_READY:
831       gst_rtp_theora_pay_cleanup (rtptheorapay);
832       break;
833     default:
834       break;
835   }
836   return ret;
837 }
838
839 static void
840 gst_rtp_theora_pay_set_property (GObject * object, guint prop_id,
841     const GValue * value, GParamSpec * pspec)
842 {
843   GstRtpTheoraPay *rtptheorapay;
844
845   rtptheorapay = GST_RTP_THEORA_PAY (object);
846
847   switch (prop_id) {
848     case PROP_CONFIG_INTERVAL:
849       rtptheorapay->config_interval = g_value_get_uint (value);
850       break;
851     default:
852       break;
853   }
854 }
855
856 static void
857 gst_rtp_theora_pay_get_property (GObject * object, guint prop_id,
858     GValue * value, GParamSpec * pspec)
859 {
860   GstRtpTheoraPay *rtptheorapay;
861
862   rtptheorapay = GST_RTP_THEORA_PAY (object);
863
864   switch (prop_id) {
865     case PROP_CONFIG_INTERVAL:
866       g_value_set_uint (value, rtptheorapay->config_interval);
867       break;
868     default:
869       break;
870   }
871 }
872
873 gboolean
874 gst_rtp_theora_pay_plugin_init (GstPlugin * plugin)
875 {
876   return gst_element_register (plugin, "rtptheorapay",
877       GST_RANK_SECONDARY, GST_TYPE_RTP_THEORA_PAY);
878 }