upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.git] / gst / rtp / gstrtph264pay.c
1 /* ex: set tabstop=2 shiftwidth=2 expandtab: */
2 /* GStreamer
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 "gstrtph264pay.h"
29
30
31 #define IDR_TYPE_ID  5
32 #define SPS_TYPE_ID  7
33 #define PPS_TYPE_ID  8
34 #define USE_MEMCMP
35
36
37 GST_DEBUG_CATEGORY_STATIC (rtph264pay_debug);
38 #define GST_CAT_DEFAULT (rtph264pay_debug)
39
40 /* references:
41  *
42  * RFC 3984
43  */
44
45 static GstStaticPadTemplate gst_rtp_h264_pay_sink_template =
46 GST_STATIC_PAD_TEMPLATE ("sink",
47     GST_PAD_SINK,
48     GST_PAD_ALWAYS,
49     GST_STATIC_CAPS ("video/x-h264")
50     );
51
52 static GstStaticPadTemplate gst_rtp_h264_pay_src_template =
53 GST_STATIC_PAD_TEMPLATE ("src",
54     GST_PAD_SRC,
55     GST_PAD_ALWAYS,
56     GST_STATIC_CAPS ("application/x-rtp, "
57         "media = (string) \"video\", "
58         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
59         "clock-rate = (int) 90000, " "encoding-name = (string) \"H264\"")
60     );
61
62 #define GST_TYPE_H264_SCAN_MODE (gst_h264_scan_mode_get_type())
63 static GType
64 gst_h264_scan_mode_get_type (void)
65 {
66   static GType h264_scan_mode_type = 0;
67   static const GEnumValue h264_scan_modes[] = {
68     {GST_H264_SCAN_MODE_BYTESTREAM,
69           "Scan complete bytestream for NALUs",
70         "bytestream"},
71     {GST_H264_SCAN_MODE_MULTI_NAL, "Buffers contain multiple complete NALUs",
72         "multiple"},
73     {GST_H264_SCAN_MODE_SINGLE_NAL, "Buffers contain a single complete NALU",
74         "single"},
75     {0, NULL, NULL},
76   };
77
78   if (!h264_scan_mode_type) {
79     h264_scan_mode_type =
80         g_enum_register_static ("GstH264PayScanMode", h264_scan_modes);
81   }
82   return h264_scan_mode_type;
83 }
84
85 #define DEFAULT_PROFILE_LEVEL_ID        NULL
86 #define DEFAULT_SPROP_PARAMETER_SETS    NULL
87 #define DEFAULT_SCAN_MODE               GST_H264_SCAN_MODE_MULTI_NAL
88 #define DEFAULT_BUFFER_LIST             FALSE
89 #define DEFAULT_CONFIG_INTERVAL               0
90
91 enum
92 {
93   PROP_0,
94   PROP_PROFILE_LEVEL_ID,
95   PROP_SPROP_PARAMETER_SETS,
96   PROP_SCAN_MODE,
97   PROP_BUFFER_LIST,
98   PROP_CONFIG_INTERVAL,
99   PROP_LAST
100 };
101
102 #define IS_ACCESS_UNIT(x) (((x) > 0x00) && ((x) < 0x06))
103
104 static void gst_rtp_h264_pay_finalize (GObject * object);
105
106 static void gst_rtp_h264_pay_set_property (GObject * object, guint prop_id,
107     const GValue * value, GParamSpec * pspec);
108 static void gst_rtp_h264_pay_get_property (GObject * object, guint prop_id,
109     GValue * value, GParamSpec * pspec);
110
111 static gboolean gst_rtp_h264_pay_setcaps (GstBaseRTPPayload * basepayload,
112     GstCaps * caps);
113 static GstFlowReturn gst_rtp_h264_pay_handle_buffer (GstBaseRTPPayload * pad,
114     GstBuffer * buffer);
115 static gboolean gst_rtp_h264_pay_handle_event (GstPad * pad, GstEvent * event);
116 static GstStateChangeReturn gst_basertppayload_change_state (GstElement *
117     element, GstStateChange transition);
118
119 GST_BOILERPLATE (GstRtpH264Pay, gst_rtp_h264_pay, GstBaseRTPPayload,
120     GST_TYPE_BASE_RTP_PAYLOAD);
121
122 static void
123 gst_rtp_h264_pay_base_init (gpointer klass)
124 {
125   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
126
127   gst_element_class_add_pad_template (element_class,
128       gst_static_pad_template_get (&gst_rtp_h264_pay_src_template));
129   gst_element_class_add_pad_template (element_class,
130       gst_static_pad_template_get (&gst_rtp_h264_pay_sink_template));
131
132   gst_element_class_set_details_simple (element_class, "RTP H264 payloader",
133       "Codec/Payloader/Network/RTP",
134       "Payload-encode H264 video into RTP packets (RFC 3984)",
135       "Laurent Glayal <spglegle@yahoo.fr>");
136 }
137
138 static void
139 gst_rtp_h264_pay_class_init (GstRtpH264PayClass * klass)
140 {
141   GObjectClass *gobject_class;
142   GstElementClass *gstelement_class;
143   GstBaseRTPPayloadClass *gstbasertppayload_class;
144
145   gobject_class = (GObjectClass *) klass;
146   gstelement_class = (GstElementClass *) klass;
147   gstbasertppayload_class = (GstBaseRTPPayloadClass *) klass;
148
149   gobject_class->set_property = gst_rtp_h264_pay_set_property;
150   gobject_class->get_property = gst_rtp_h264_pay_get_property;
151
152   g_object_class_install_property (G_OBJECT_CLASS (klass),
153       PROP_PROFILE_LEVEL_ID, g_param_spec_string ("profile-level-id",
154           "profile-level-id",
155           "The base64 profile-level-id to set in the sink caps (deprecated)",
156           DEFAULT_PROFILE_LEVEL_ID,
157           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
158
159   g_object_class_install_property (G_OBJECT_CLASS (klass),
160       PROP_SPROP_PARAMETER_SETS, g_param_spec_string ("sprop-parameter-sets",
161           "sprop-parameter-sets",
162           "The base64 sprop-parameter-sets to set in out caps (set to NULL to "
163           "extract from stream)",
164           DEFAULT_SPROP_PARAMETER_SETS,
165           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
166
167   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SCAN_MODE,
168       g_param_spec_enum ("scan-mode", "Scan Mode",
169           "How to scan the input buffers for NAL units. Performance can be "
170           "increased when certain assumptions are made about the input buffers",
171           GST_TYPE_H264_SCAN_MODE, DEFAULT_SCAN_MODE,
172           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
173
174   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BUFFER_LIST,
175       g_param_spec_boolean ("buffer-list", "Buffer List",
176           "Use Buffer Lists",
177           DEFAULT_BUFFER_LIST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
178
179   g_object_class_install_property (G_OBJECT_CLASS (klass),
180       PROP_CONFIG_INTERVAL,
181       g_param_spec_uint ("config-interval",
182           "SPS PPS Send Interval",
183           "Send SPS and PPS Insertion Interval in seconds (sprop parameter sets "
184           "will be multiplexed in the data stream when detected.) (0 = disabled)",
185           0, 3600, DEFAULT_CONFIG_INTERVAL,
186           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
187       );
188
189   gobject_class->finalize = gst_rtp_h264_pay_finalize;
190
191   gstelement_class->change_state =
192       GST_DEBUG_FUNCPTR (gst_basertppayload_change_state);
193
194   gstbasertppayload_class->set_caps = gst_rtp_h264_pay_setcaps;
195   gstbasertppayload_class->handle_buffer = gst_rtp_h264_pay_handle_buffer;
196   gstbasertppayload_class->handle_event = gst_rtp_h264_pay_handle_event;
197
198   GST_DEBUG_CATEGORY_INIT (rtph264pay_debug, "rtph264pay", 0,
199       "H264 RTP Payloader");
200 }
201
202 static void
203 gst_rtp_h264_pay_init (GstRtpH264Pay * rtph264pay, GstRtpH264PayClass * klass)
204 {
205   rtph264pay->queue = g_array_new (FALSE, FALSE, sizeof (guint));
206   rtph264pay->profile = 0;
207   rtph264pay->sps = NULL;
208   rtph264pay->pps = NULL;
209   rtph264pay->last_spspps = -1;
210   rtph264pay->scan_mode = GST_H264_SCAN_MODE_MULTI_NAL;
211   rtph264pay->buffer_list = DEFAULT_BUFFER_LIST;
212   rtph264pay->spspps_interval = DEFAULT_CONFIG_INTERVAL;
213
214   rtph264pay->adapter = gst_adapter_new ();
215 }
216
217 static void
218 gst_rtp_h264_pay_clear_sps_pps (GstRtpH264Pay * rtph264pay)
219 {
220   g_list_foreach (rtph264pay->sps, (GFunc) gst_mini_object_unref, NULL);
221   g_list_free (rtph264pay->sps);
222   rtph264pay->sps = NULL;
223   g_list_foreach (rtph264pay->pps, (GFunc) gst_mini_object_unref, NULL);
224   g_list_free (rtph264pay->pps);
225   rtph264pay->pps = NULL;
226 }
227
228 static void
229 gst_rtp_h264_pay_finalize (GObject * object)
230 {
231   GstRtpH264Pay *rtph264pay;
232
233   rtph264pay = GST_RTP_H264_PAY (object);
234
235   g_array_free (rtph264pay->queue, TRUE);
236
237   gst_rtp_h264_pay_clear_sps_pps (rtph264pay);
238
239   g_free (rtph264pay->sprop_parameter_sets);
240
241   g_object_unref (rtph264pay->adapter);
242
243   G_OBJECT_CLASS (parent_class)->finalize (object);
244 }
245
246 /* take the currently configured SPS and PPS lists and set them on the caps as
247  * sprop-parameter-sets */
248 static gboolean
249 gst_rtp_h264_pay_set_sps_pps (GstBaseRTPPayload * basepayload)
250 {
251   GstRtpH264Pay *payloader = GST_RTP_H264_PAY (basepayload);
252   gchar *profile;
253   gchar *set;
254   GList *walk;
255   GString *sprops;
256   guint count;
257   gboolean res;
258
259   sprops = g_string_new ("");
260   count = 0;
261
262   /* build the sprop-parameter-sets */
263   for (walk = payloader->sps; walk; walk = g_list_next (walk)) {
264     GstBuffer *sps_buf = GST_BUFFER_CAST (walk->data);
265
266     set =
267         g_base64_encode (GST_BUFFER_DATA (sps_buf), GST_BUFFER_SIZE (sps_buf));
268     g_string_append_printf (sprops, "%s%s", count ? "," : "", set);
269     g_free (set);
270     count++;
271   }
272   for (walk = payloader->pps; walk; walk = g_list_next (walk)) {
273     GstBuffer *pps_buf = GST_BUFFER_CAST (walk->data);
274
275     set =
276         g_base64_encode (GST_BUFFER_DATA (pps_buf), GST_BUFFER_SIZE (pps_buf));
277     g_string_append_printf (sprops, "%s%s", count ? "," : "", set);
278     g_free (set);
279     count++;
280   }
281
282   /* profile is 24 bit. Force it to respect the limit */
283   profile = g_strdup_printf ("%06x", payloader->profile & 0xffffff);
284   /* combine into output caps */
285   res = gst_basertppayload_set_outcaps (basepayload,
286       "sprop-parameter-sets", G_TYPE_STRING, sprops->str, NULL);
287   g_string_free (sprops, TRUE);
288   g_free (profile);
289
290   return res;
291 }
292
293 static gboolean
294 gst_rtp_h264_pay_setcaps (GstBaseRTPPayload * basepayload, GstCaps * caps)
295 {
296   GstRtpH264Pay *rtph264pay;
297   GstStructure *str;
298   const GValue *value;
299   guint8 *data;
300   guint size;
301
302   rtph264pay = GST_RTP_H264_PAY (basepayload);
303
304   str = gst_caps_get_structure (caps, 0);
305
306   /* we can only set the output caps when we found the sprops and profile
307    * NALs */
308   gst_basertppayload_set_options (basepayload, "video", TRUE, "H264", 90000);
309
310 #if 0 // yoserb yi - not to check sps/pps when savsenc_h264 and rtph264pay are linked
311   /* packetized AVC video has a codec_data */
312   if ((value = gst_structure_get_value (str, "codec_data"))) {
313     GstBuffer *buffer;
314     guint num_sps, num_pps;
315     gint i, nal_size;
316
317     GST_DEBUG_OBJECT (rtph264pay, "have packetized h264");
318     rtph264pay->packetized = TRUE;
319
320     buffer = gst_value_get_buffer (value);
321     data = GST_BUFFER_DATA (buffer);
322     size = GST_BUFFER_SIZE (buffer);
323
324     /* parse the avcC data */
325     if (size < 7)
326       goto avcc_too_small;
327     /* parse the version, this must be 1 */
328     if (data[0] != 1)
329       goto wrong_version;
330
331     /* AVCProfileIndication */
332     /* profile_compat */
333     /* AVCLevelIndication */
334     rtph264pay->profile = (data[1] << 16) | (data[2] << 8) | data[3];
335     GST_DEBUG_OBJECT (rtph264pay, "profile %06x", rtph264pay->profile);
336
337     /* 6 bits reserved | 2 bits lengthSizeMinusOne */
338     /* this is the number of bytes in front of the NAL units to mark their
339      * length */
340     rtph264pay->nal_length_size = (data[4] & 0x03) + 1;
341     GST_DEBUG_OBJECT (rtph264pay, "nal length %u", rtph264pay->nal_length_size);
342     /* 3 bits reserved | 5 bits numOfSequenceParameterSets */
343     num_sps = data[5] & 0x1f;
344     GST_DEBUG_OBJECT (rtph264pay, "num SPS %u", num_sps);
345
346     data += 6;
347     size -= 6;
348
349     /* create the sprop-parameter-sets */
350     for (i = 0; i < num_sps; i++) {
351       GstBuffer *sps_buf;
352
353       if (size < 2)
354         goto avcc_error;
355
356       nal_size = (data[0] << 8) | data[1];
357       data += 2;
358       size -= 2;
359
360       GST_LOG_OBJECT (rtph264pay, "SPS %d size %d", i, nal_size);
361
362       if (size < nal_size)
363         goto avcc_error;
364
365       /* make a buffer out of it and add to SPS list */
366       sps_buf = gst_buffer_new_and_alloc (nal_size);
367       memcpy (GST_BUFFER_DATA (sps_buf), data, nal_size);
368       rtph264pay->sps = g_list_append (rtph264pay->sps, sps_buf);
369
370       data += nal_size;
371       size -= nal_size;
372     }
373     if (size < 1)
374       goto avcc_error;
375
376     /* 8 bits numOfPictureParameterSets */
377     num_pps = data[0];
378     data += 1;
379     size -= 1;
380
381     GST_DEBUG_OBJECT (rtph264pay, "num PPS %u", num_pps);
382     for (i = 0; i < num_pps; i++) {
383       GstBuffer *pps_buf;
384
385       if (size < 2)
386         goto avcc_error;
387
388       nal_size = (data[0] << 8) | data[1];
389       data += 2;
390       size -= 2;
391
392       GST_LOG_OBJECT (rtph264pay, "PPS %d size %d", i, nal_size);
393
394       if (size < nal_size)
395         goto avcc_error;
396
397       /* make a buffer out of it and add to PPS list */
398       pps_buf = gst_buffer_new_and_alloc (nal_size);
399       memcpy (GST_BUFFER_DATA (pps_buf), data, nal_size);
400       rtph264pay->pps = g_list_append (rtph264pay->pps, pps_buf);
401
402       data += nal_size;
403       size -= nal_size;
404     }
405     /* and update the caps with the collected data */
406     if (!gst_rtp_h264_pay_set_sps_pps (basepayload))
407       return FALSE;
408   } else {
409     GST_DEBUG_OBJECT (rtph264pay, "have bytestream h264");
410     rtph264pay->packetized = FALSE;
411   }
412 #else
413     GST_DEBUG_OBJECT (rtph264pay, "have bytestream h264");
414     rtph264pay->packetized = FALSE;
415 #endif
416
417   return TRUE;
418
419 avcc_too_small:
420   {
421     GST_ERROR_OBJECT (rtph264pay, "avcC size %u < 7", size);
422     return FALSE;
423   }
424 wrong_version:
425   {
426     GST_ERROR_OBJECT (rtph264pay, "wrong avcC version");
427     return FALSE;
428   }
429 avcc_error:
430   {
431     GST_ERROR_OBJECT (rtph264pay, "avcC too small ");
432     return FALSE;
433   }
434 }
435
436 static void
437 gst_rtp_h264_pay_parse_sprop_parameter_sets (GstRtpH264Pay * rtph264pay)
438 {
439   const gchar *ps;
440   gchar **params;
441   guint len, num_sps, num_pps;
442   gint i;
443   GstBuffer *buf;
444
445   ps = rtph264pay->sprop_parameter_sets;
446   if (ps == NULL)
447     return;
448
449   gst_rtp_h264_pay_clear_sps_pps (rtph264pay);
450
451   params = g_strsplit (ps, ",", 0);
452   len = g_strv_length (params);
453
454   GST_DEBUG_OBJECT (rtph264pay, "we have %d params", len);
455
456   num_sps = num_pps = 0;
457
458   for (i = 0; params[i]; i++) {
459     gsize nal_len;
460     guint8 *nalp;
461     guint save = 0;
462     gint state = 0;
463
464     nal_len = strlen (params[i]);
465     buf = gst_buffer_new_and_alloc (nal_len);
466     nalp = GST_BUFFER_DATA (buf);
467
468     nal_len = g_base64_decode_step (params[i], nal_len, nalp, &state, &save);
469     GST_BUFFER_SIZE (buf) = nal_len;
470
471     if (!nal_len) {
472       gst_buffer_unref (buf);
473       continue;
474     }
475
476     /* append to the right list */
477     if ((nalp[0] & 0x1f) == 7) {
478       GST_DEBUG_OBJECT (rtph264pay, "adding param %d as SPS %d", i, num_sps);
479       rtph264pay->sps = g_list_append (rtph264pay->sps, buf);
480       num_sps++;
481     } else {
482       GST_DEBUG_OBJECT (rtph264pay, "adding param %d as PPS %d", i, num_pps);
483       rtph264pay->pps = g_list_append (rtph264pay->pps, buf);
484       num_pps++;
485     }
486   }
487   g_strfreev (params);
488 }
489
490 static guint
491 next_start_code (const guint8 * data, guint size)
492 {
493   /* Boyer-Moore string matching algorithm, in a degenerative
494    * sense because our search 'alphabet' is binary - 0 & 1 only.
495    * This allow us to simplify the general BM algorithm to a very
496    * simple form. */
497   /* assume 1 is in the 3th byte */
498   guint offset = 2;
499
500   while (offset < size) {
501     if (1 == data[offset]) {
502       unsigned int shift = offset;
503
504       if (0 == data[--shift]) {
505         if (0 == data[--shift]) {
506           return shift;
507         }
508       }
509       /* The jump is always 3 because of the 1 previously matched.
510        * All the 0's must be after this '1' matched at offset */
511       offset += 3;
512     } else if (0 == data[offset]) {
513       /* maybe next byte is 1? */
514       offset++;
515     } else {
516       /* can jump 3 bytes forward */
517       offset += 3;
518     }
519     /* at each iteration, we rescan in a backward manner until
520      * we match 0.0.1 in reverse order. Since our search string
521      * has only 2 'alpabets' (i.e. 0 & 1), we know that any
522      * mismatch will force us to shift a fixed number of steps */
523   }
524   GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
525
526   return size;
527 }
528
529 static gboolean
530 gst_rtp_h264_pay_decode_nal (GstRtpH264Pay * payloader,
531     const guint8 * data, guint size, GstClockTime timestamp)
532 {
533   const guint8 *sps = NULL, *pps = NULL;
534   guint sps_len = 0, pps_len = 0;
535   guint8 header, type;
536   guint len;
537   gboolean updated;
538
539   /* default is no update */
540   updated = FALSE;
541
542   GST_DEBUG ("NAL payload len=%u", size);
543
544   len = size;
545   header = data[0];
546   type = header & 0x1f;
547
548   /* keep sps & pps separately so that we can update either one 
549    * independently. We also record the timestamp of the last SPS/PPS so 
550    * that we can insert them at regular intervals and when needed. */
551   if (SPS_TYPE_ID == type) {
552     /* encode the entire SPS NAL in base64 */
553     GST_DEBUG ("Found SPS %x %x %x Len=%u", (header >> 7),
554         (header >> 5) & 3, type, len);
555
556     sps = data;
557     sps_len = len;
558     /* remember when we last saw SPS */
559     if (timestamp != -1)
560       payloader->last_spspps = timestamp;
561   } else if (PPS_TYPE_ID == type) {
562     /* encoder the entire PPS NAL in base64 */
563     GST_DEBUG ("Found PPS %x %x %x Len = %u",
564         (header >> 7), (header >> 5) & 3, type, len);
565
566     pps = data;
567     pps_len = len;
568     /* remember when we last saw PPS */
569     if (timestamp != -1)
570       payloader->last_spspps = timestamp;
571   } else {
572     GST_DEBUG ("NAL: %x %x %x Len = %u", (header >> 7),
573         (header >> 5) & 3, type, len);
574   }
575
576   /* If we encountered an SPS and/or a PPS, check if it's the
577    * same as the one we have. If not, update our version and
578    * set updated to TRUE
579    */
580   if (sps_len > 0) {
581     GstBuffer *sps_buf;
582
583     if (payloader->sps != NULL) {
584       sps_buf = GST_BUFFER_CAST (payloader->sps->data);
585
586       if ((GST_BUFFER_SIZE (sps_buf) != sps_len)
587           || memcmp (GST_BUFFER_DATA (sps_buf), sps, sps_len)) {
588         /* something changed, update */
589         payloader->profile = (sps[1] << 16) + (sps[2] << 8) + sps[3];
590         GST_DEBUG ("Profile level IDC = %06x", payloader->profile);
591         updated = TRUE;
592       }
593     } else {
594       /* no previous SPS, update */
595       updated = TRUE;
596     }
597
598     if (updated) {
599       sps_buf = gst_buffer_new_and_alloc (sps_len);
600       memcpy (GST_BUFFER_DATA (sps_buf), sps, sps_len);
601
602       if (payloader->sps) {
603         /* replace old buffer */
604         gst_buffer_unref (payloader->sps->data);
605         payloader->sps->data = sps_buf;
606       } else {
607         /* add new buffer */
608         payloader->sps = g_list_prepend (payloader->sps, sps_buf);
609       }
610     }
611   }
612
613   if (pps_len > 0) {
614     GstBuffer *pps_buf;
615
616     if (payloader->pps != NULL) {
617       pps_buf = GST_BUFFER_CAST (payloader->pps->data);
618
619       if ((GST_BUFFER_SIZE (pps_buf) != pps_len)
620           || memcmp (GST_BUFFER_DATA (pps_buf), pps, pps_len)) {
621         /* something changed, update */
622         updated = TRUE;
623       }
624     } else {
625       /* no previous SPS, update */
626       updated = TRUE;
627     }
628
629     if (updated) {
630       pps_buf = gst_buffer_new_and_alloc (pps_len);
631       memcpy (GST_BUFFER_DATA (pps_buf), pps, pps_len);
632
633       if (payloader->pps) {
634         /* replace old buffer */
635         gst_buffer_unref (payloader->pps->data);
636         payloader->pps->data = pps_buf;
637       } else {
638         /* add new buffer */
639         payloader->pps = g_list_prepend (payloader->pps, pps_buf);
640       }
641     }
642   }
643   return updated;
644 }
645
646 static GstFlowReturn
647 gst_rtp_h264_pay_payload_nal (GstBaseRTPPayload * basepayload,
648     const guint8 * data, guint size, GstClockTime timestamp,
649     GstBuffer * buffer_orig);
650
651 static GstFlowReturn
652 gst_rtp_h264_pay_send_sps_pps (GstBaseRTPPayload * basepayload,
653     GstRtpH264Pay * rtph264pay, GstClockTime timestamp)
654 {
655   GstFlowReturn ret = GST_FLOW_OK;
656   GList *walk;
657
658   for (walk = rtph264pay->sps; walk; walk = g_list_next (walk)) {
659     GstBuffer *sps_buf = GST_BUFFER_CAST (walk->data);
660
661     GST_DEBUG_OBJECT (rtph264pay, "inserting SPS in the stream");
662     /* resend SPS */
663     ret = gst_rtp_h264_pay_payload_nal (basepayload,
664         GST_BUFFER_DATA (sps_buf), GST_BUFFER_SIZE (sps_buf), timestamp,
665         sps_buf);
666     /* Not critical here; but throw a warning */
667     if (ret != GST_FLOW_OK)
668       GST_WARNING ("Problem pushing SPS");
669   }
670   for (walk = rtph264pay->pps; walk; walk = g_list_next (walk)) {
671     GstBuffer *pps_buf = GST_BUFFER_CAST (walk->data);
672
673     GST_DEBUG_OBJECT (rtph264pay, "inserting PPS in the stream");
674     /* resend PPS */
675     ret = gst_rtp_h264_pay_payload_nal (basepayload,
676         GST_BUFFER_DATA (pps_buf), GST_BUFFER_SIZE (pps_buf), timestamp,
677         pps_buf);
678     /* Not critical here; but throw a warning */
679     if (ret != GST_FLOW_OK)
680       GST_WARNING ("Problem pushing PPS");
681   }
682
683   if (timestamp != -1)
684     rtph264pay->last_spspps = timestamp;
685
686   return ret;
687 }
688
689 static GstFlowReturn
690 gst_rtp_h264_pay_payload_nal (GstBaseRTPPayload * basepayload,
691     const guint8 * data, guint size, GstClockTime timestamp,
692     GstBuffer * buffer_orig)
693 {
694   GstRtpH264Pay *rtph264pay;
695   GstFlowReturn ret;
696   guint8 nalType;
697   guint packet_len, payload_len, mtu;
698   GstBuffer *outbuf;
699   guint8 *payload;
700   GstBufferList *list = NULL;
701   GstBufferListIterator *it = NULL;
702   gboolean send_spspps;
703
704   rtph264pay = GST_RTP_H264_PAY (basepayload);
705   mtu = GST_BASE_RTP_PAYLOAD_MTU (rtph264pay);
706
707   nalType = data[0] & 0x1f;
708   GST_DEBUG_OBJECT (rtph264pay, "Processing Buffer with NAL TYPE=%d", nalType);
709
710   send_spspps = FALSE;
711
712   /* check if we need to emit an SPS/PPS now */
713   if (nalType == IDR_TYPE_ID && rtph264pay->spspps_interval > 0) {
714     if (rtph264pay->last_spspps != -1) {
715       guint64 diff;
716
717       GST_LOG_OBJECT (rtph264pay,
718           "now %" GST_TIME_FORMAT ", last SPS/PPS %" GST_TIME_FORMAT,
719           GST_TIME_ARGS (timestamp), GST_TIME_ARGS (rtph264pay->last_spspps));
720
721       /* calculate diff between last SPS/PPS in milliseconds */
722       if (timestamp > rtph264pay->last_spspps)
723         diff = timestamp - rtph264pay->last_spspps;
724       else
725         diff = 0;
726
727       GST_DEBUG_OBJECT (rtph264pay,
728           "interval since last SPS/PPS %" GST_TIME_FORMAT,
729           GST_TIME_ARGS (diff));
730
731       /* bigger than interval, queue SPS/PPS */
732       if (GST_TIME_AS_SECONDS (diff) >= rtph264pay->spspps_interval) {
733         GST_DEBUG_OBJECT (rtph264pay, "time to send SPS/PPS");
734         send_spspps = TRUE;
735       }
736     } else {
737       /* no know previous SPS/PPS time, send now */
738       GST_DEBUG_OBJECT (rtph264pay, "no previous SPS/PPS time, send now");
739       send_spspps = TRUE;
740     }
741   }
742
743   if (send_spspps || rtph264pay->send_spspps) {
744     /* we need to send SPS/PPS now first. FIXME, don't use the timestamp for
745      * checking when we need to send SPS/PPS but convert to running_time first. */
746     rtph264pay->send_spspps = FALSE;
747     ret = gst_rtp_h264_pay_send_sps_pps (basepayload, rtph264pay, timestamp);
748     if (ret != GST_FLOW_OK)
749       return ret;
750   }
751
752   packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
753
754   if (packet_len < mtu) {
755     GST_DEBUG_OBJECT (basepayload,
756         "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
757     /* will fit in one packet */
758
759     if (rtph264pay->buffer_list) {
760       /* use buffer lists
761        * first create buffer without payload containing only the RTP header
762        * and then another buffer containing the payload. both buffers will
763        * be then added to the list */
764       outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
765     } else {
766       /* use the old-fashioned way with a single buffer and memcpy */
767       outbuf = gst_rtp_buffer_new_allocate (size, 0, 0);
768     }
769
770     /* only set the marker bit on packets containing access units */
771     if (IS_ACCESS_UNIT (nalType)) {
772       gst_rtp_buffer_set_marker (outbuf, 1);
773     }
774
775     /* timestamp the outbuffer */
776     GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
777
778     if (rtph264pay->buffer_list) {
779       GstBuffer *paybuf;
780
781       /* create another buffer with the payload. */
782       if (buffer_orig)
783         paybuf = gst_buffer_create_sub (buffer_orig, data -
784             GST_BUFFER_DATA (buffer_orig), size);
785       else {
786         paybuf = gst_buffer_new_and_alloc (size);
787         memcpy (GST_BUFFER_DATA (paybuf), data, size);
788       }
789
790       list = gst_buffer_list_new ();
791       it = gst_buffer_list_iterate (list);
792
793       /* add both buffers to the buffer list */
794       gst_buffer_list_iterator_add_group (it);
795       gst_buffer_list_iterator_add (it, outbuf);
796       gst_buffer_list_iterator_add (it, paybuf);
797
798       gst_buffer_list_iterator_free (it);
799
800       /* push the list to the next element in the pipe */
801       ret = gst_basertppayload_push_list (basepayload, list);
802     } else {
803       payload = gst_rtp_buffer_get_payload (outbuf);
804       GST_DEBUG_OBJECT (basepayload, "Copying %d bytes to outbuf", size);
805       memcpy (payload, data, size);
806
807       ret = gst_basertppayload_push (basepayload, outbuf);
808     }
809   } else {
810     /* fragmentation Units FU-A */
811     guint8 nalHeader;
812     guint limitedSize;
813     int ii = 0, start = 1, end = 0, pos = 0;
814
815     GST_DEBUG_OBJECT (basepayload,
816         "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
817
818     nalHeader = *data;
819     pos++;
820     size--;
821
822     ret = GST_FLOW_OK;
823
824     GST_DEBUG_OBJECT (basepayload, "Using FU-A fragmentation for data size=%d",
825         size);
826
827     /* We keep 2 bytes for FU indicator and FU Header */
828     payload_len = gst_rtp_buffer_calc_payload_len (mtu - 2, 0, 0);
829
830     if (rtph264pay->buffer_list) {
831       list = gst_buffer_list_new ();
832       it = gst_buffer_list_iterate (list);
833     }
834
835     while (end == 0) {
836       limitedSize = size < payload_len ? size : payload_len;
837       GST_DEBUG_OBJECT (basepayload,
838           "Inside  FU-A fragmentation limitedSize=%d iteration=%d", limitedSize,
839           ii);
840
841       if (rtph264pay->buffer_list) {
842         /* use buffer lists
843          * first create buffer without payload containing only the RTP header
844          * and then another buffer containing the payload. both buffers will
845          * be then added to the list */
846         outbuf = gst_rtp_buffer_new_allocate (2, 0, 0);
847       } else {
848         /* use the old-fashioned way with a single buffer and memcpy
849          * first create buffer to hold the payload */
850         outbuf = gst_rtp_buffer_new_allocate (limitedSize + 2, 0, 0);
851       }
852
853       GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
854       payload = gst_rtp_buffer_get_payload (outbuf);
855
856       if (limitedSize == size) {
857         GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
858         end = 1;
859       }
860       if (IS_ACCESS_UNIT (nalType)) {
861         gst_rtp_buffer_set_marker (outbuf, end);
862       }
863
864       /* FU indicator */
865       payload[0] = (nalHeader & 0x60) | 28;
866
867       /* FU Header */
868       payload[1] = (start << 7) | (end << 6) | (nalHeader & 0x1f);
869
870       if (rtph264pay->buffer_list) {
871         GstBuffer *paybuf;
872
873         /* create another buffer to hold the payload */
874         if (buffer_orig)
875           paybuf = gst_buffer_create_sub (buffer_orig, data -
876               GST_BUFFER_DATA (buffer_orig) + pos, limitedSize);
877         else {
878           paybuf = gst_buffer_new_and_alloc (limitedSize);
879           memcpy (GST_BUFFER_DATA (paybuf), data + pos, limitedSize);
880         }
881
882         /* create a new group to hold the header and the payload */
883         gst_buffer_list_iterator_add_group (it);
884
885         /* add both buffers to the buffer list */
886         gst_buffer_list_iterator_add (it, outbuf);
887         gst_buffer_list_iterator_add (it, paybuf);
888
889       } else {
890         memcpy (&payload[2], data + pos, limitedSize);
891         GST_DEBUG_OBJECT (basepayload,
892             "recorded %d payload bytes into packet iteration=%d",
893             limitedSize + 2, ii);
894
895         ret = gst_basertppayload_push (basepayload, outbuf);
896         if (ret != GST_FLOW_OK)
897           break;
898       }
899
900       size -= limitedSize;
901       pos += limitedSize;
902       ii++;
903       start = 0;
904     }
905
906     if (rtph264pay->buffer_list) {
907       /* free iterator and push the whole buffer list at once */
908       gst_buffer_list_iterator_free (it);
909       ret = gst_basertppayload_push_list (basepayload, list);
910     }
911   }
912   return ret;
913 }
914
915 static GstFlowReturn
916 gst_rtp_h264_pay_handle_buffer (GstBaseRTPPayload * basepayload,
917     GstBuffer * buffer)
918 {
919   GstRtpH264Pay *rtph264pay;
920   GstFlowReturn ret;
921   guint size, nal_len, i;
922   const guint8 *data, *nal_data;
923   GstClockTime timestamp;
924   GArray *nal_queue;
925   guint pushed = 0;
926
927   rtph264pay = GST_RTP_H264_PAY (basepayload);
928
929   /* the input buffer contains one or more NAL units */
930
931   if (rtph264pay->scan_mode == GST_H264_SCAN_MODE_BYTESTREAM) {
932     timestamp = gst_adapter_prev_timestamp (rtph264pay->adapter, NULL);
933     gst_adapter_push (rtph264pay->adapter, buffer);
934     size = gst_adapter_available (rtph264pay->adapter);
935     data = gst_adapter_peek (rtph264pay->adapter, size);
936     GST_DEBUG_OBJECT (basepayload, "got %d bytes (%d)", size,
937         GST_BUFFER_SIZE (buffer));
938
939     if (!GST_CLOCK_TIME_IS_VALID (timestamp))
940       timestamp = GST_BUFFER_TIMESTAMP (buffer);
941   } else {
942     size = GST_BUFFER_SIZE (buffer);
943     data = GST_BUFFER_DATA (buffer);
944     timestamp = GST_BUFFER_TIMESTAMP (buffer);
945     GST_DEBUG_OBJECT (basepayload, "got %d bytes", size);
946   }
947
948   ret = GST_FLOW_OK;
949
950   /* now loop over all NAL units and put them in a packet
951    * FIXME, we should really try to pack multiple NAL units into one RTP packet
952    * if we can, especially for the config packets that wont't cause decoder 
953    * latency. */
954   if (rtph264pay->packetized) {
955     guint nal_length_size;
956
957     nal_length_size = rtph264pay->nal_length_size;
958
959     while (size > nal_length_size) {
960       gint i;
961
962       nal_len = 0;
963       for (i = 0; i < nal_length_size; i++) {
964         nal_len = ((nal_len << 8) + data[i]);
965       }
966
967       /* skip the length bytes, make sure we don't run past the buffer size */
968       data += nal_length_size;
969       size -= nal_length_size;
970
971       if (size >= nal_len) {
972         GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
973       } else {
974         nal_len = size;
975         GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
976             nal_len);
977       }
978
979       ret =
980           gst_rtp_h264_pay_payload_nal (basepayload, data, nal_len, timestamp,
981           buffer);
982       if (ret != GST_FLOW_OK)
983         break;
984
985       data += nal_len;
986       size -= nal_len;
987     }
988   } else {
989     guint next;
990     gboolean update = FALSE;
991
992     /* get offset of first start code */
993     next = next_start_code (data, size);
994
995     /* skip to start code, if no start code is found, next will be size and we
996      * will not collect data. */
997     data += next;
998     size -= next;
999     nal_data = data;
1000     nal_queue = rtph264pay->queue;
1001
1002     /* array must be empty when we get here */
1003     g_assert (nal_queue->len == 0);
1004
1005     GST_DEBUG_OBJECT (basepayload, "found first start at %u, bytes left %u",
1006         next, size);
1007
1008     /* first pass to locate NALs and parse SPS/PPS */
1009     while (size > 4) {
1010       /* skip start code */
1011       data += 3;
1012       size -= 3;
1013
1014       if (rtph264pay->scan_mode == GST_H264_SCAN_MODE_SINGLE_NAL) {
1015         /* we are told that there is only a single NAL in this packet so that we
1016          * can avoid scanning for the next NAL. */
1017         next = size;
1018       } else {
1019         /* use next_start_code() to scan buffer.
1020          * next_start_code() returns the offset in data, 
1021          * starting from zero to the first byte of 0.0.0.1
1022          * If no start code is found, it returns the value of the 
1023          * 'size' parameter. 
1024          * data is unchanged by the call to next_start_code()
1025          */
1026         next = next_start_code (data, size);
1027
1028         if (next == size
1029             && rtph264pay->scan_mode == GST_H264_SCAN_MODE_BYTESTREAM) {
1030           /* Didn't find the start of next NAL, handle it next time */
1031           break;
1032         }
1033       }
1034
1035       /* nal length is distance to next start code */
1036       nal_len = next;
1037
1038       GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1039           nal_len);
1040
1041       if (rtph264pay->sprop_parameter_sets != NULL) {
1042         /* explicitly set profile and sprop, use those */
1043         if (rtph264pay->update_caps) {
1044           if (!gst_basertppayload_set_outcaps (basepayload,
1045                   "sprop-parameter-sets", G_TYPE_STRING,
1046                   rtph264pay->sprop_parameter_sets, NULL))
1047             goto caps_rejected;
1048
1049           /* parse SPS and PPS from provided parameter set (for insertion) */
1050           gst_rtp_h264_pay_parse_sprop_parameter_sets (rtph264pay);
1051
1052           rtph264pay->update_caps = FALSE;
1053
1054           GST_DEBUG ("outcaps update: sprop-parameter-sets=%s",
1055               rtph264pay->sprop_parameter_sets);
1056         }
1057       } else {
1058         /* We know our stream is a valid H264 NAL packet,
1059          * go parse it for SPS/PPS to enrich the caps */
1060         /* order: make sure to check nal */
1061         update =
1062             gst_rtp_h264_pay_decode_nal (rtph264pay, data, nal_len, timestamp)
1063             || update;
1064       }
1065       /* move to next NAL packet */
1066       data += nal_len;
1067       size -= nal_len;
1068
1069       g_array_append_val (nal_queue, nal_len);
1070     }
1071
1072     /* if has new SPS & PPS, update the output caps */
1073     if (G_UNLIKELY (update))
1074       if (!gst_rtp_h264_pay_set_sps_pps (basepayload))
1075         goto caps_rejected;
1076
1077     /* second pass to payload and push */
1078     data = nal_data;
1079     pushed = 0;
1080
1081     for (i = 0; i < nal_queue->len; i++) {
1082       guint size;
1083
1084       nal_len = g_array_index (nal_queue, guint, i);
1085       /* skip start code */
1086       data += 3;
1087
1088       /* Trim the end unless we're the last NAL in the buffer.
1089        * In case we're not at the end of the buffer we know the next block
1090        * starts with 0x000001 so all the 0x00 bytes at the end of this one are
1091        * trailing 0x0 that can be discarded */
1092       size = nal_len;
1093       if (i + 1 != nal_queue->len
1094           || rtph264pay->scan_mode == GST_H264_SCAN_MODE_BYTESTREAM)
1095         for (; size > 1 && data[size - 1] == 0x0; size--)
1096           /* skip */ ;
1097
1098       /* put the data in one or more RTP packets */
1099       ret =
1100           gst_rtp_h264_pay_payload_nal (basepayload, data, size, timestamp,
1101           buffer);
1102       if (ret != GST_FLOW_OK) {
1103         break;
1104       }
1105
1106       /* move to next NAL packet */
1107       data += nal_len;
1108       size -= nal_len;
1109       pushed += nal_len + 3;
1110     }
1111     g_array_set_size (nal_queue, 0);
1112   }
1113
1114   if (rtph264pay->scan_mode == GST_H264_SCAN_MODE_BYTESTREAM)
1115     gst_adapter_flush (rtph264pay->adapter, pushed);
1116   else
1117     gst_buffer_unref (buffer);
1118
1119   return ret;
1120
1121 caps_rejected:
1122   {
1123     GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1124     g_array_set_size (nal_queue, 0);
1125     gst_buffer_unref (buffer);
1126     return GST_FLOW_NOT_NEGOTIATED;
1127   }
1128 }
1129
1130 static gboolean
1131 gst_rtp_h264_pay_handle_event (GstPad * pad, GstEvent * event)
1132 {
1133   const GstStructure *s;
1134   GstRtpH264Pay *rtph264pay = GST_RTP_H264_PAY (GST_PAD_PARENT (pad));
1135
1136   switch (GST_EVENT_TYPE (event)) {
1137     case GST_EVENT_FLUSH_STOP:
1138       gst_adapter_clear (rtph264pay->adapter);
1139       break;
1140     case GST_EVENT_CUSTOM_DOWNSTREAM:
1141       s = gst_event_get_structure (event);
1142       if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1143         gboolean resend_codec_data;
1144
1145         if (gst_structure_get_boolean (s, "all-headers",
1146                 &resend_codec_data) && resend_codec_data)
1147           rtph264pay->send_spspps = TRUE;
1148       }
1149       break;
1150     default:
1151       break;
1152   }
1153
1154   return FALSE;
1155 }
1156
1157 static GstStateChangeReturn
1158 gst_basertppayload_change_state (GstElement * element,
1159     GstStateChange transition)
1160 {
1161   GstStateChangeReturn ret;
1162   GstRtpH264Pay *rtph264pay = GST_RTP_H264_PAY (element);
1163
1164   switch (transition) {
1165     case GST_STATE_CHANGE_READY_TO_PAUSED:
1166       rtph264pay->send_spspps = FALSE;
1167       gst_adapter_clear (rtph264pay->adapter);
1168       break;
1169     default:
1170       break;
1171   }
1172
1173   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1174
1175   return ret;
1176 }
1177
1178 static void
1179 gst_rtp_h264_pay_set_property (GObject * object, guint prop_id,
1180     const GValue * value, GParamSpec * pspec)
1181 {
1182   GstRtpH264Pay *rtph264pay;
1183
1184   rtph264pay = GST_RTP_H264_PAY (object);
1185
1186   switch (prop_id) {
1187     case PROP_PROFILE_LEVEL_ID:
1188       break;
1189     case PROP_SPROP_PARAMETER_SETS:
1190       g_free (rtph264pay->sprop_parameter_sets);
1191       rtph264pay->sprop_parameter_sets = g_value_dup_string (value);
1192       rtph264pay->update_caps = TRUE;
1193       break;
1194     case PROP_SCAN_MODE:
1195       rtph264pay->scan_mode = g_value_get_enum (value);
1196       break;
1197     case PROP_BUFFER_LIST:
1198       rtph264pay->buffer_list = g_value_get_boolean (value);
1199       break;
1200     case PROP_CONFIG_INTERVAL:
1201       rtph264pay->spspps_interval = g_value_get_uint (value);
1202       break;
1203     default:
1204       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1205       break;
1206   }
1207 }
1208
1209 static void
1210 gst_rtp_h264_pay_get_property (GObject * object, guint prop_id,
1211     GValue * value, GParamSpec * pspec)
1212 {
1213   GstRtpH264Pay *rtph264pay;
1214
1215   rtph264pay = GST_RTP_H264_PAY (object);
1216
1217   switch (prop_id) {
1218     case PROP_PROFILE_LEVEL_ID:
1219       break;
1220     case PROP_SPROP_PARAMETER_SETS:
1221       g_value_set_string (value, rtph264pay->sprop_parameter_sets);
1222       break;
1223     case PROP_SCAN_MODE:
1224       g_value_set_enum (value, rtph264pay->scan_mode);
1225       break;
1226     case PROP_BUFFER_LIST:
1227       g_value_set_boolean (value, rtph264pay->buffer_list);
1228       break;
1229     case PROP_CONFIG_INTERVAL:
1230       g_value_set_uint (value, rtph264pay->spspps_interval);
1231       break;
1232     default:
1233       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1234       break;
1235   }
1236 }
1237
1238 gboolean
1239 gst_rtp_h264_pay_plugin_init (GstPlugin * plugin)
1240 {
1241   return gst_element_register (plugin, "rtph264pay",
1242       GST_RANK_SECONDARY, GST_TYPE_RTP_H264_PAY);
1243 }