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