Revert "rtph264pay/depay: Add optional framerate caps for use in SDP"
[platform/upstream/gstreamer.git] / gst / rtp / gstrtph264depay.c
1 /* GStreamer
2  * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <stdio.h>
25 #include <string.h>
26
27 #include <gst/base/gstbitreader.h>
28 #include <gst/rtp/gstrtpbuffer.h>
29 #include "gstrtph264depay.h"
30
31 GST_DEBUG_CATEGORY_STATIC (rtph264depay_debug);
32 #define GST_CAT_DEFAULT (rtph264depay_debug)
33
34 /* This is what we'll default to when downstream hasn't
35  * expressed a restriction or preference via caps */
36 #define DEFAULT_BYTE_STREAM   TRUE
37 #define DEFAULT_ACCESS_UNIT   FALSE
38
39 /* 3 zero bytes syncword */
40 static const guint8 sync_bytes[] = { 0, 0, 0, 1 };
41
42 static GstStaticPadTemplate gst_rtp_h264_depay_src_template =
43     GST_STATIC_PAD_TEMPLATE ("src",
44     GST_PAD_SRC,
45     GST_PAD_ALWAYS,
46     GST_STATIC_CAPS ("video/x-h264, "
47         "stream-format = (string) avc, alignment = (string) au; "
48         /** optional parameters **/
49     /* "width = (int) [ 1, MAX ], " */
50     /* "height = (int) [ 1, MAX ], " */
51         "video/x-h264, "
52         "stream-format = (string) byte-stream, alignment = (string) { nal, au }")
53         /** optional parameters **/
54     /* "width = (int) [ 1, MAX ], " */
55     /* "height = (int) [ 1, MAX ], " */
56     );
57
58 static GstStaticPadTemplate gst_rtp_h264_depay_sink_template =
59 GST_STATIC_PAD_TEMPLATE ("sink",
60     GST_PAD_SINK,
61     GST_PAD_ALWAYS,
62     GST_STATIC_CAPS ("application/x-rtp, "
63         "media = (string) \"video\", "
64         "clock-rate = (int) 90000, "
65         "encoding-name = (string) \"H264\"")
66         /** optional parameters **/
67     /* "profile-level-id = (string) ANY, " */
68     /* "max-mbps = (string) ANY, " */
69     /* "max-fs = (string) ANY, " */
70     /* "max-cpb = (string) ANY, " */
71     /* "max-dpb = (string) ANY, " */
72     /* "max-br = (string) ANY, " */
73     /* "redundant-pic-cap = (string) { \"0\", \"1\" }, " */
74     /* "sprop-parameter-sets = (string) ANY, " */
75     /* "parameter-add = (string) { \"0\", \"1\" }, " */
76     /* "packetization-mode = (string) { \"0\", \"1\", \"2\" }, " */
77     /* "sprop-interleaving-depth = (string) ANY, " */
78     /* "sprop-deint-buf-req = (string) ANY, " */
79     /* "deint-buf-cap = (string) ANY, " */
80     /* "sprop-init-buf-time = (string) ANY, " */
81     /* "sprop-max-don-diff = (string) ANY, " */
82     /* "max-rcmd-nalu-size = (string) ANY, " */
83     /* "width = (int) [ 1, MAX ], " */
84     /* "height = (int) [ 1, MAX ], " */
85     );
86
87 #define gst_rtp_h264_depay_parent_class parent_class
88 G_DEFINE_TYPE (GstRtpH264Depay, gst_rtp_h264_depay,
89     GST_TYPE_RTP_BASE_DEPAYLOAD);
90
91 static void gst_rtp_h264_depay_finalize (GObject * object);
92
93 static GstStateChangeReturn gst_rtp_h264_depay_change_state (GstElement *
94     element, GstStateChange transition);
95
96 static GstBuffer *gst_rtp_h264_depay_process (GstRTPBaseDepayload * depayload,
97     GstBuffer * buf);
98 static gboolean gst_rtp_h264_depay_setcaps (GstRTPBaseDepayload * filter,
99     GstCaps * caps);
100 static gboolean gst_rtp_h264_depay_handle_event (GstRTPBaseDepayload * depay,
101     GstEvent * event);
102
103 static void
104 gst_rtp_h264_depay_class_init (GstRtpH264DepayClass * klass)
105 {
106   GObjectClass *gobject_class;
107   GstElementClass *gstelement_class;
108   GstRTPBaseDepayloadClass *gstrtpbasedepayload_class;
109
110   gobject_class = (GObjectClass *) klass;
111   gstelement_class = (GstElementClass *) klass;
112   gstrtpbasedepayload_class = (GstRTPBaseDepayloadClass *) klass;
113
114   gobject_class->finalize = gst_rtp_h264_depay_finalize;
115
116   gst_element_class_add_pad_template (gstelement_class,
117       gst_static_pad_template_get (&gst_rtp_h264_depay_src_template));
118   gst_element_class_add_pad_template (gstelement_class,
119       gst_static_pad_template_get (&gst_rtp_h264_depay_sink_template));
120
121   gst_element_class_set_static_metadata (gstelement_class,
122       "RTP H264 depayloader", "Codec/Depayloader/Network/RTP",
123       "Extracts H264 video from RTP packets (RFC 3984)",
124       "Wim Taymans <wim.taymans@gmail.com>");
125   gstelement_class->change_state = gst_rtp_h264_depay_change_state;
126
127   gstrtpbasedepayload_class->process = gst_rtp_h264_depay_process;
128   gstrtpbasedepayload_class->set_caps = gst_rtp_h264_depay_setcaps;
129   gstrtpbasedepayload_class->handle_event = gst_rtp_h264_depay_handle_event;
130
131   GST_DEBUG_CATEGORY_INIT (rtph264depay_debug, "rtph264depay", 0,
132       "H264 Video RTP Depayloader");
133 }
134
135 static void
136 gst_rtp_h264_depay_init (GstRtpH264Depay * rtph264depay)
137 {
138   rtph264depay->adapter = gst_adapter_new ();
139   rtph264depay->picture_adapter = gst_adapter_new ();
140   rtph264depay->byte_stream = DEFAULT_BYTE_STREAM;
141   rtph264depay->merge = DEFAULT_ACCESS_UNIT;
142   rtph264depay->sps = g_ptr_array_new_with_free_func (
143       (GDestroyNotify) gst_buffer_unref);
144   rtph264depay->pps = g_ptr_array_new_with_free_func (
145       (GDestroyNotify) gst_buffer_unref);
146 }
147
148 static void
149 gst_rtp_h264_depay_reset (GstRtpH264Depay * rtph264depay)
150 {
151   gst_adapter_clear (rtph264depay->adapter);
152   rtph264depay->wait_start = TRUE;
153   gst_adapter_clear (rtph264depay->picture_adapter);
154   rtph264depay->picture_start = FALSE;
155   rtph264depay->last_keyframe = FALSE;
156   rtph264depay->last_ts = 0;
157   rtph264depay->current_fu_type = 0;
158   rtph264depay->new_codec_data = FALSE;
159   rtph264depay->width = 0;
160   rtph264depay->height = 0;
161   g_ptr_array_set_size (rtph264depay->sps, 0);
162   g_ptr_array_set_size (rtph264depay->pps, 0);
163 }
164
165 static void
166 gst_rtp_h264_depay_finalize (GObject * object)
167 {
168   GstRtpH264Depay *rtph264depay;
169
170   rtph264depay = GST_RTP_H264_DEPAY (object);
171
172   if (rtph264depay->codec_data)
173     gst_buffer_unref (rtph264depay->codec_data);
174
175   g_object_unref (rtph264depay->adapter);
176   g_object_unref (rtph264depay->picture_adapter);
177
178   g_ptr_array_free (rtph264depay->sps, TRUE);
179   g_ptr_array_free (rtph264depay->pps, TRUE);
180
181   G_OBJECT_CLASS (parent_class)->finalize (object);
182 }
183
184 static void
185 gst_rtp_h264_depay_negotiate (GstRtpH264Depay * rtph264depay)
186 {
187   GstCaps *caps;
188   gint byte_stream = -1;
189   gint merge = -1;
190
191   caps =
192       gst_pad_get_allowed_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph264depay));
193
194   GST_DEBUG_OBJECT (rtph264depay, "allowed caps: %" GST_PTR_FORMAT, caps);
195
196   if (caps) {
197     if (gst_caps_get_size (caps) > 0) {
198       GstStructure *s = gst_caps_get_structure (caps, 0);
199       const gchar *str = NULL;
200
201       if ((str = gst_structure_get_string (s, "stream-format"))) {
202         if (strcmp (str, "avc") == 0) {
203           byte_stream = FALSE;
204         } else if (strcmp (str, "byte-stream") == 0) {
205           byte_stream = TRUE;
206         } else {
207           GST_DEBUG_OBJECT (rtph264depay, "unknown stream-format: %s", str);
208         }
209       }
210
211       if ((str = gst_structure_get_string (s, "alignment"))) {
212         if (strcmp (str, "au") == 0) {
213           merge = TRUE;
214         } else if (strcmp (str, "nal") == 0) {
215           merge = FALSE;
216         } else {
217           GST_DEBUG_OBJECT (rtph264depay, "unknown alignment: %s", str);
218         }
219       }
220     }
221     gst_caps_unref (caps);
222   }
223
224   if (byte_stream != -1) {
225     GST_DEBUG_OBJECT (rtph264depay, "downstream requires byte-stream %d",
226         byte_stream);
227     rtph264depay->byte_stream = byte_stream;
228   } else {
229     GST_DEBUG_OBJECT (rtph264depay, "defaulting to byte-stream %d",
230         DEFAULT_BYTE_STREAM);
231     rtph264depay->byte_stream = DEFAULT_BYTE_STREAM;
232   }
233   if (merge != -1) {
234     GST_DEBUG_OBJECT (rtph264depay, "downstream requires merge %d", merge);
235     rtph264depay->merge = merge;
236   } else {
237     GST_DEBUG_OBJECT (rtph264depay, "defaulting to merge %d",
238         DEFAULT_ACCESS_UNIT);
239     rtph264depay->merge = DEFAULT_ACCESS_UNIT;
240   }
241 }
242
243 /* Stolen from bad/gst/mpegtsdemux/payloader_parsers.c */
244 /* variable length Exp-Golomb parsing according to H.264 spec 9.1*/
245 static gboolean
246 read_golomb (GstBitReader * br, guint32 * value)
247 {
248   guint8 b, leading_zeros = -1;
249   *value = 1;
250
251   for (b = 0; !b; leading_zeros++) {
252     if (!gst_bit_reader_get_bits_uint8 (br, &b, 1))
253       return FALSE;
254     *value *= 2;
255   }
256
257   *value = (*value >> 1) - 1;
258   if (leading_zeros > 0) {
259     guint32 tmp = 0;
260     if (!gst_bit_reader_get_bits_uint32 (br, &tmp, leading_zeros))
261       return FALSE;
262     *value += tmp;
263   }
264
265   return TRUE;
266 }
267
268 static gboolean
269 parse_sps (GstMapInfo * map, guint32 * sps_id)
270 {
271   GstBitReader br = GST_BIT_READER_INIT (map->data + 4,
272       map->size - 4);
273
274   if (map->size < 5)
275     return FALSE;
276
277   if (!read_golomb (&br, sps_id))
278     return FALSE;
279
280   return TRUE;
281 }
282
283 static gboolean
284 parse_pps (GstMapInfo * map, guint32 * sps_id, guint32 * pps_id)
285 {
286   GstBitReader br = GST_BIT_READER_INIT (map->data + 1,
287       map->size - 1);
288
289   if (map->size < 2)
290     return FALSE;
291
292   if (!read_golomb (&br, pps_id))
293     return FALSE;
294   if (!read_golomb (&br, sps_id))
295     return FALSE;
296
297   return TRUE;
298 }
299
300
301 static gboolean
302 gst_rtp_h264_set_src_caps (GstRtpH264Depay * rtph264depay)
303 {
304   gboolean res;
305   GstCaps *srccaps;
306   guchar level = 0;
307   guchar profile_compat = G_MAXUINT8;
308
309   if (!rtph264depay->byte_stream &&
310       (!rtph264depay->new_codec_data ||
311           rtph264depay->sps->len == 0 || rtph264depay->pps->len == 0))
312     return TRUE;
313
314   srccaps = gst_caps_new_simple ("video/x-h264",
315       "stream-format", G_TYPE_STRING,
316       rtph264depay->byte_stream ? "byte-stream" : "avc",
317       "alignment", G_TYPE_STRING, rtph264depay->merge ? "au" : "nal", NULL);
318
319   if  (rtph264depay->width > 0 && rtph264depay->height > 0) {
320     gst_caps_set_simple (srccaps, "width", G_TYPE_INT, rtph264depay->width,
321         "height", G_TYPE_INT, rtph264depay->height, NULL);
322   }
323
324   if (!rtph264depay->byte_stream) {
325     GstBuffer *codec_data;
326     GstMapInfo map;
327     GstMapInfo nalmap;
328     guint8 *data;
329     guint len;
330     guint new_size;
331     guint i;
332
333     /* start with 7 bytes header */
334     len = 7;
335     /* count sps & pps */
336     for (i = 0; i < rtph264depay->sps->len; i++)
337       len += 2 + gst_buffer_get_size (g_ptr_array_index (rtph264depay->sps, i));
338     for (i = 0; i < rtph264depay->pps->len; i++)
339       len += 2 + gst_buffer_get_size (g_ptr_array_index (rtph264depay->pps, i));
340
341     codec_data = gst_buffer_new_and_alloc (len);
342     g_debug ("alloc_len: %u", len);
343     gst_buffer_map (codec_data, &map, GST_MAP_READWRITE);
344     data = map.data;
345
346     /* 8 bits version == 1 */
347     *data++ = 1;
348
349     /* According to: ISO/IEC 14496-15:2004(E) section 5.2.4.1
350      * The level is the max level of all SPSes
351      * A profile compat bit can only be set if all SPSes include that bit
352      */
353     for (i = 0; i < rtph264depay->sps->len; i++) {
354       gst_buffer_map (g_ptr_array_index (rtph264depay->sps, i), &nalmap,
355           GST_MAP_READ);
356       profile_compat &= nalmap.data[2];
357       level = MAX (level, nalmap.data[3]);
358       gst_buffer_unmap (g_ptr_array_index (rtph264depay->sps, i), &nalmap);
359     }
360
361     /* Assume all SPSes use the same profile, so extract from the first SPS */
362     gst_buffer_map (g_ptr_array_index (rtph264depay->sps, 0), &nalmap,
363         GST_MAP_READ);
364     *data++ = nalmap.data[1];
365     gst_buffer_unmap (g_ptr_array_index (rtph264depay->sps, 0), &nalmap);
366     *data++ = profile_compat;
367     *data++ = level;
368
369     /* 6 bits reserved | 2 bits lengthSizeMinusOn */
370     *data++ = 0xff;
371     /* 3 bits reserved | 5 bits numOfSequenceParameterSets */
372     *data++ = 0xe0 | (rtph264depay->sps->len & 0x1f);
373
374     /* copy all SPS */
375     for (i = 0; i < rtph264depay->sps->len; i++) {
376       gst_buffer_map (g_ptr_array_index (rtph264depay->sps, i), &nalmap,
377           GST_MAP_READ);
378
379       GST_DEBUG_OBJECT (rtph264depay, "copy SPS %d of length %u", i,
380           (guint) nalmap.size);
381       GST_WRITE_UINT16_BE (data, nalmap.size);
382       data += 2;
383       memcpy (data, nalmap.data, nalmap.size);
384       data += nalmap.size;
385       gst_buffer_unmap (g_ptr_array_index (rtph264depay->sps, i), &nalmap);
386     }
387
388     /* 8 bits numOfPictureParameterSets */
389     *data++ = rtph264depay->pps->len;
390     /* copy all PPS */
391     for (i = 0; i < rtph264depay->pps->len; i++) {
392       gst_buffer_map (g_ptr_array_index (rtph264depay->pps, i), &nalmap,
393           GST_MAP_READ);
394
395       GST_DEBUG_OBJECT (rtph264depay, "copy PPS %d of length %u", i,
396           (guint) nalmap.size);
397       GST_WRITE_UINT16_BE (data, nalmap.size);
398       data += 2;
399       memcpy (data, nalmap.data, nalmap.size);
400       data += nalmap.size;
401       gst_buffer_unmap (g_ptr_array_index (rtph264depay->pps, i), &nalmap);
402     }
403
404     new_size = data - map.data;
405     gst_buffer_unmap (codec_data, &map);
406     gst_buffer_set_size (codec_data, new_size);
407
408
409     gst_caps_set_simple (srccaps,
410         "codec_data", GST_TYPE_BUFFER, codec_data, NULL);
411     gst_buffer_unref (codec_data);
412   }
413
414   res = gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph264depay),
415       srccaps);
416   gst_caps_unref (srccaps);
417
418   if (res)
419     rtph264depay->new_codec_data = FALSE;
420
421   return res;
422 }
423
424 static gboolean
425 gst_rtp_h264_add_sps_pps (GstRtpH264Depay * rtph264depay, GstBuffer * nal)
426 {
427   GstMapInfo map;
428   guchar type;
429   guint i;
430
431   gst_buffer_map (nal, &map, GST_MAP_READ);
432
433   type = map.data[0] & 0x1f;
434
435   if (type == 7) {
436     guint32 sps_id;
437
438     if (!parse_sps (&map, &sps_id)) {
439       GST_WARNING_OBJECT (rtph264depay, "Invalid SPS,"
440           " can't parse seq_parameter_set_id");
441       goto drop;
442     }
443
444     for (i = 0; i < rtph264depay->sps->len; i++) {
445       GstBuffer *sps = g_ptr_array_index (rtph264depay->sps, i);
446       GstMapInfo spsmap;
447       guint32 tmp_sps_id;
448
449       gst_buffer_map (sps, &spsmap, GST_MAP_READ);
450       parse_sps (&spsmap, &tmp_sps_id);
451
452       if (sps_id == tmp_sps_id) {
453         if (map.size == spsmap.size &&
454             memcmp (map.data, spsmap.data, spsmap.size) == 0) {
455           GST_LOG_OBJECT (rtph264depay, "Unchanged SPS %u, not updating",
456               sps_id);
457           gst_buffer_unmap (sps, &spsmap);
458           goto drop;
459         } else {
460           gst_buffer_unmap (sps, &spsmap);
461           g_ptr_array_remove_index_fast (rtph264depay->sps, i);
462           g_ptr_array_add (rtph264depay->sps, nal);
463           GST_LOG_OBJECT (rtph264depay, "Modified SPS %u, replacing", sps_id);
464           goto done;
465         }
466       }
467       gst_buffer_unmap (sps, &spsmap);
468     }
469     GST_LOG_OBJECT (rtph264depay, "Adding new SPS %u", sps_id);
470     g_ptr_array_add (rtph264depay->sps, nal);
471   } else if (type == 8) {
472     guint32 sps_id;
473     guint32 pps_id;
474
475     if (!parse_pps (&map, &sps_id, &pps_id)) {
476       GST_WARNING_OBJECT (rtph264depay, "Invalid PPS,"
477           " can't parse seq_parameter_set_id or pic_parameter_set_id");
478       goto drop;
479     }
480
481     for (i = 0; i < rtph264depay->pps->len; i++) {
482       GstBuffer *pps = g_ptr_array_index (rtph264depay->pps, i);
483       GstMapInfo ppsmap;
484       guint32 tmp_sps_id;
485       guint32 tmp_pps_id;
486
487
488       gst_buffer_map (pps, &ppsmap, GST_MAP_READ);
489       parse_pps (&ppsmap, &tmp_sps_id, &tmp_pps_id);
490
491       if (sps_id == tmp_sps_id && pps_id == tmp_pps_id) {
492         if (map.size == ppsmap.size &&
493             memcmp (map.data, ppsmap.data, ppsmap.size) == 0) {
494           GST_LOG_OBJECT (rtph264depay, "Unchanged PPS %u:%u, not updating",
495               sps_id, pps_id);
496           gst_buffer_unmap (pps, &ppsmap);
497           goto drop;
498         } else {
499           gst_buffer_unmap (pps, &ppsmap);
500           g_ptr_array_remove_index_fast (rtph264depay->pps, i);
501           g_ptr_array_add (rtph264depay->pps, nal);
502           GST_LOG_OBJECT (rtph264depay, "Modified PPS %u:%u, replacing",
503               sps_id, pps_id);
504           goto done;
505         }
506       }
507       gst_buffer_unmap (pps, &ppsmap);
508     }
509     GST_LOG_OBJECT (rtph264depay, "Adding new PPS %u:%i", sps_id, pps_id);
510     g_ptr_array_add (rtph264depay->pps, nal);
511   } else {
512     goto drop;
513   }
514
515 done:
516   gst_buffer_unmap (nal, &map);
517   rtph264depay->new_codec_data = TRUE;
518
519   return TRUE;
520
521 drop:
522   gst_buffer_unmap (nal, &map);
523   gst_buffer_unref (nal);
524
525   return FALSE;
526 }
527
528 static gboolean
529 gst_rtp_h264_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
530 {
531   gint clock_rate;
532   GstStructure *structure = gst_caps_get_structure (caps, 0);
533   GstRtpH264Depay *rtph264depay;
534   const gchar *ps;
535   GstBuffer *codec_data;
536   GstMapInfo map;
537   guint8 *ptr;
538   gint width = 0, height = 0;
539
540   rtph264depay = GST_RTP_H264_DEPAY (depayload);
541
542   if (!gst_structure_get_int (structure, "clock-rate", &clock_rate))
543     clock_rate = 90000;
544   depayload->clock_rate = clock_rate;
545
546   /* Base64 encoded, comma separated config NALs */
547   ps = gst_structure_get_string (structure, "sprop-parameter-sets");
548
549   /* negotiate with downstream w.r.t. output format and alignment */
550   gst_rtp_h264_depay_negotiate (rtph264depay);
551
552   if (rtph264depay->byte_stream && ps != NULL) {
553     /* for bytestream we only need the parameter sets but we don't error out
554      * when they are not there, we assume they are in the stream. */
555     gchar **params;
556     guint len, total;
557     gint i;
558
559     params = g_strsplit (ps, ",", 0);
560
561     /* count total number of bytes in base64. Also include the sync bytes in
562      * front of the params. */
563     len = 0;
564     for (i = 0; params[i]; i++) {
565       len += strlen (params[i]);
566       len += sizeof (sync_bytes);
567     }
568     /* we seriously overshoot the length, but it's fine. */
569     codec_data = gst_buffer_new_and_alloc (len);
570
571     gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
572     ptr = map.data;
573     total = 0;
574     for (i = 0; params[i]; i++) {
575       guint save = 0;
576       gint state = 0;
577
578       GST_DEBUG_OBJECT (depayload, "decoding param %d (%s)", i, params[i]);
579       memcpy (ptr, sync_bytes, sizeof (sync_bytes));
580       ptr += sizeof (sync_bytes);
581       len =
582           g_base64_decode_step (params[i], strlen (params[i]), ptr, &state,
583           &save);
584       GST_DEBUG_OBJECT (depayload, "decoded %d bytes", len);
585       total += len + sizeof (sync_bytes);
586       ptr += len;
587     }
588     gst_buffer_unmap (codec_data, &map);
589     gst_buffer_resize (codec_data, 0, total);
590     g_strfreev (params);
591
592     /* keep the codec_data, we need to send it as the first buffer. We cannot
593      * push it in the adapter because the adapter might be flushed on discont.
594      */
595     if (rtph264depay->codec_data)
596       gst_buffer_unref (rtph264depay->codec_data);
597     rtph264depay->codec_data = codec_data;
598   } else if (!rtph264depay->byte_stream) {
599     gchar **params;
600     gint i;
601
602     if (ps == NULL)
603       goto incomplete_caps;
604
605     params = g_strsplit (ps, ",", 0);
606
607     GST_DEBUG_OBJECT (depayload, "we have %d params", g_strv_length (params));
608
609     /* start with 7 bytes header */
610     for (i = 0; params[i]; i++) {
611       GstBuffer *nal;
612       GstMapInfo nalmap;
613       gsize nal_len;
614       guint save = 0;
615       gint state = 0;
616
617       nal_len = strlen (params[i]);
618       nal = gst_buffer_new_and_alloc (nal_len);
619       gst_buffer_map (nal, &nalmap, GST_MAP_READWRITE);
620
621       nal_len =
622           g_base64_decode_step (params[i], nal_len, nalmap.data, &state, &save);
623
624       GST_DEBUG_OBJECT (depayload, "adding param %d as %s", i,
625           ((nalmap.data[0] & 0x1f) == 7) ? "SPS" : "PPS");
626
627       gst_buffer_unmap (nal, &nalmap);
628       gst_buffer_set_size (nal, nal_len);
629
630       gst_rtp_h264_add_sps_pps (rtph264depay, nal);
631     }
632     g_strfreev (params);
633
634     if (rtph264depay->sps->len == 0 || rtph264depay->pps->len == 0)
635       goto incomplete_caps;
636   }
637
638   if (gst_structure_get_int (structure, "width", &width) && width <= 0) {
639     goto invalid_dimension;
640   }
641   if (gst_structure_get_int (structure, "height", &height) && height <= 0) {
642     goto invalid_dimension;
643   }
644
645   rtph264depay->width = width;
646   rtph264depay->height = height;
647
648   return gst_rtp_h264_set_src_caps (rtph264depay);
649
650   /* ERRORS */
651 incomplete_caps:
652   {
653     GST_DEBUG_OBJECT (depayload, "we have incomplete caps,"
654         " doing setcaps later");
655     return TRUE;
656   }
657 invalid_dimension:
658   {
659     GST_ERROR_OBJECT (depayload, "invalid width/height from caps");
660     return FALSE;
661   }
662 }
663
664 static GstBuffer *
665 gst_rtp_h264_complete_au (GstRtpH264Depay * rtph264depay,
666     GstClockTime * out_timestamp, gboolean * out_keyframe)
667 {
668   guint outsize;
669   GstBuffer *outbuf;
670
671   /* we had a picture in the adapter and we completed it */
672   GST_DEBUG_OBJECT (rtph264depay, "taking completed AU");
673   outsize = gst_adapter_available (rtph264depay->picture_adapter);
674   outbuf = gst_adapter_take_buffer (rtph264depay->picture_adapter, outsize);
675
676   *out_timestamp = rtph264depay->last_ts;
677   *out_keyframe = rtph264depay->last_keyframe;
678
679   rtph264depay->last_keyframe = FALSE;
680   rtph264depay->picture_start = FALSE;
681
682   return outbuf;
683 }
684
685 /* SPS/PPS/IDR considered key, all others DELTA;
686  * so downstream waiting for keyframe can pick up at SPS/PPS/IDR */
687 #define NAL_TYPE_IS_KEY(nt) (((nt) == 5) || ((nt) == 7) || ((nt) == 8))
688
689 static GstBuffer *
690 gst_rtp_h264_depay_handle_nal (GstRtpH264Depay * rtph264depay, GstBuffer * nal,
691     GstClockTime in_timestamp, gboolean marker)
692 {
693   GstRTPBaseDepayload *depayload = GST_RTP_BASE_DEPAYLOAD (rtph264depay);
694   gint nal_type;
695   GstMapInfo map;
696   GstBuffer *outbuf = NULL;
697   GstClockTime out_timestamp;
698   gboolean keyframe, out_keyframe;
699
700   gst_buffer_map (nal, &map, GST_MAP_READ);
701   if (G_UNLIKELY (map.size < 5))
702     goto short_nal;
703
704   nal_type = map.data[4] & 0x1f;
705   GST_DEBUG_OBJECT (rtph264depay, "handle NAL type %d", nal_type);
706
707   keyframe = NAL_TYPE_IS_KEY (nal_type);
708
709   out_keyframe = keyframe;
710   out_timestamp = in_timestamp;
711
712   if (!rtph264depay->byte_stream) {
713     if (nal_type == 7 || nal_type == 8) {
714       gst_rtp_h264_add_sps_pps (rtph264depay,
715           gst_buffer_copy_region (nal, GST_BUFFER_COPY_ALL,
716               4, gst_buffer_get_size (nal) - 4));
717       gst_buffer_unmap (nal, &map);
718       gst_buffer_unref (nal);
719       return NULL;
720     } else if (rtph264depay->sps->len == 0 || rtph264depay->pps->len == 0) {
721       /* Down push down any buffer in non-bytestream mode if the SPS/PPS haven't
722        * go through yet
723        */
724       gst_pad_push_event (GST_RTP_BASE_DEPAYLOAD_SINKPAD (depayload),
725           gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
726               gst_structure_new ("GstForceKeyUnit",
727                   "all-headers", G_TYPE_BOOLEAN, TRUE, NULL)));
728       gst_buffer_unmap (nal, &map);
729       gst_buffer_unref (nal);
730       return NULL;
731     }
732
733     if (rtph264depay->new_codec_data &&
734         rtph264depay->sps->len > 0 && rtph264depay->pps->len > 0)
735       gst_rtp_h264_set_src_caps (rtph264depay);
736   }
737
738
739   if (rtph264depay->merge) {
740     gboolean start = FALSE, complete = FALSE;
741
742     /* consider a coded slices (IDR or not) to start a picture,
743      * (so ending the previous one) if first_mb_in_slice == 0
744      * (non-0 is part of previous one) */
745     /* NOTE this is not entirely according to Access Unit specs in 7.4.1.2.4,
746      * but in practice it works in sane cases, needs not much parsing,
747      * and also works with broken frame_num in NAL (where spec-wise would fail) */
748     if (nal_type == 1 || nal_type == 2 || nal_type == 5) {
749       /* we have a picture start */
750       start = TRUE;
751       if (map.data[5] & 0x80) {
752         /* first_mb_in_slice == 0 completes a picture */
753         complete = TRUE;
754       }
755     } else if (nal_type >= 6 && nal_type <= 9) {
756       /* SEI, SPS, PPS, AU terminate picture */
757       complete = TRUE;
758     }
759     GST_DEBUG_OBJECT (depayload, "start %d, complete %d", start, complete);
760
761     if (complete && rtph264depay->picture_start)
762       outbuf = gst_rtp_h264_complete_au (rtph264depay, &out_timestamp,
763           &out_keyframe);
764
765     /* add to adapter */
766     gst_buffer_unmap (nal, &map);
767
768     GST_DEBUG_OBJECT (depayload, "adding NAL to picture adapter");
769     gst_adapter_push (rtph264depay->picture_adapter, nal);
770     rtph264depay->last_ts = in_timestamp;
771     rtph264depay->last_keyframe |= keyframe;
772     rtph264depay->picture_start |= start;
773
774     if (marker)
775       outbuf = gst_rtp_h264_complete_au (rtph264depay, &out_timestamp,
776           &out_keyframe);
777   } else {
778     /* no merge, output is input nal */
779     GST_DEBUG_OBJECT (depayload, "using NAL as output");
780     outbuf = nal;
781     gst_buffer_unmap (nal, &map);
782   }
783
784   if (outbuf) {
785     /* prepend codec_data */
786     if (rtph264depay->codec_data) {
787       GST_DEBUG_OBJECT (depayload, "prepending codec_data");
788       outbuf = gst_buffer_append (rtph264depay->codec_data, outbuf);
789       rtph264depay->codec_data = NULL;
790       out_keyframe = TRUE;
791     }
792     outbuf = gst_buffer_make_writable (outbuf);
793
794     GST_BUFFER_TIMESTAMP (outbuf) = out_timestamp;
795
796     if (out_keyframe)
797       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
798     else
799       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
800   }
801
802   return outbuf;
803
804   /* ERRORS */
805 short_nal:
806   {
807     GST_WARNING_OBJECT (depayload, "dropping short NAL");
808     gst_buffer_unmap (nal, &map);
809     gst_buffer_unref (nal);
810     return NULL;
811   }
812 }
813
814 static GstBuffer *
815 gst_rtp_h264_push_fragmentation_unit (GstRtpH264Depay * rtph264depay,
816     gboolean send)
817 {
818   guint outsize;
819   GstMapInfo map;
820   GstBuffer *outbuf;
821
822   outsize = gst_adapter_available (rtph264depay->adapter);
823   outbuf = gst_adapter_take_buffer (rtph264depay->adapter, outsize);
824
825   gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
826   GST_DEBUG_OBJECT (rtph264depay, "output %d bytes", outsize);
827
828   if (rtph264depay->byte_stream) {
829     memcpy (map.data, sync_bytes, sizeof (sync_bytes));
830   } else {
831     outsize -= 4;
832     map.data[0] = (outsize >> 24);
833     map.data[1] = (outsize >> 16);
834     map.data[2] = (outsize >> 8);
835     map.data[3] = (outsize);
836   }
837   gst_buffer_unmap (outbuf, &map);
838
839   rtph264depay->current_fu_type = 0;
840
841   outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf,
842       rtph264depay->fu_timestamp, rtph264depay->fu_marker);
843
844   if (send && outbuf) {
845     gst_rtp_base_depayload_push (GST_RTP_BASE_DEPAYLOAD (rtph264depay), outbuf);
846     outbuf = NULL;
847   }
848   return outbuf;
849 }
850
851 static GstBuffer *
852 gst_rtp_h264_depay_process (GstRTPBaseDepayload * depayload, GstBuffer * buf)
853 {
854   GstRtpH264Depay *rtph264depay;
855   GstBuffer *outbuf = NULL;
856   guint8 nal_unit_type;
857   GstRTPBuffer rtp = { NULL };
858
859   rtph264depay = GST_RTP_H264_DEPAY (depayload);
860
861   /* flush remaining data on discont */
862   if (GST_BUFFER_IS_DISCONT (buf)) {
863     gst_adapter_clear (rtph264depay->adapter);
864     rtph264depay->wait_start = TRUE;
865     rtph264depay->current_fu_type = 0;
866   }
867
868   {
869     gint payload_len;
870     guint8 *payload;
871     guint header_len;
872     guint8 nal_ref_idc;
873     GstMapInfo map;
874     guint outsize, nalu_size;
875     GstClockTime timestamp;
876     gboolean marker;
877
878     timestamp = GST_BUFFER_TIMESTAMP (buf);
879
880     gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp);
881
882     payload_len = gst_rtp_buffer_get_payload_len (&rtp);
883     payload = gst_rtp_buffer_get_payload (&rtp);
884     marker = gst_rtp_buffer_get_marker (&rtp);
885
886     GST_DEBUG_OBJECT (rtph264depay, "receiving %d bytes", payload_len);
887
888     if (payload_len == 0)
889       goto empty_packet;
890
891     /* +---------------+
892      * |0|1|2|3|4|5|6|7|
893      * +-+-+-+-+-+-+-+-+
894      * |F|NRI|  Type   |
895      * +---------------+
896      *
897      * F must be 0.
898      */
899     nal_ref_idc = (payload[0] & 0x60) >> 5;
900     nal_unit_type = payload[0] & 0x1f;
901
902     /* at least one byte header with type */
903     header_len = 1;
904
905     GST_DEBUG_OBJECT (rtph264depay, "NRI %d, Type %d", nal_ref_idc,
906         nal_unit_type);
907
908     /* If FU unit was being processed, but the current nal is of a different
909      * type.  Assume that the remote payloader is buggy (didn't set the end bit
910      * when the FU ended) and send out what we gathered thusfar */
911     if (G_UNLIKELY (rtph264depay->current_fu_type != 0 &&
912             nal_unit_type != rtph264depay->current_fu_type))
913       gst_rtp_h264_push_fragmentation_unit (rtph264depay, TRUE);
914
915     switch (nal_unit_type) {
916       case 0:
917       case 30:
918       case 31:
919         /* undefined */
920         goto undefined_type;
921       case 25:
922         /* STAP-B    Single-time aggregation packet     5.7.1 */
923         /* 2 byte extra header for DON */
924         header_len += 2;
925         /* fallthrough */
926       case 24:
927       {
928         /* strip headers */
929         payload += header_len;
930         payload_len -= header_len;
931
932         rtph264depay->wait_start = FALSE;
933
934
935         /* STAP-A    Single-time aggregation packet     5.7.1 */
936         while (payload_len > 2) {
937           /*                      1          
938            *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 
939            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
940            * |         NALU Size             |
941            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
942            */
943           nalu_size = (payload[0] << 8) | payload[1];
944
945           /* dont include nalu_size */
946           if (nalu_size > (payload_len - 2))
947             nalu_size = payload_len - 2;
948
949           outsize = nalu_size + sizeof (sync_bytes);
950           outbuf = gst_buffer_new_and_alloc (outsize);
951
952           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
953           if (rtph264depay->byte_stream) {
954             memcpy (map.data, sync_bytes, sizeof (sync_bytes));
955           } else {
956             map.data[0] = map.data[1] = 0;
957             map.data[2] = payload[0];
958             map.data[3] = payload[1];
959           }
960
961           /* strip NALU size */
962           payload += 2;
963           payload_len -= 2;
964
965           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
966           gst_buffer_unmap (outbuf, &map);
967
968           gst_adapter_push (rtph264depay->adapter, outbuf);
969
970           payload += nalu_size;
971           payload_len -= nalu_size;
972         }
973
974         outsize = gst_adapter_available (rtph264depay->adapter);
975         outbuf = gst_adapter_take_buffer (rtph264depay->adapter, outsize);
976
977         outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf, timestamp,
978             marker);
979         break;
980       }
981       case 26:
982         /* MTAP16    Multi-time aggregation packet      5.7.2 */
983         header_len = 5;
984         /* fallthrough, not implemented */
985       case 27:
986         /* MTAP24    Multi-time aggregation packet      5.7.2 */
987         header_len = 6;
988         goto not_implemented;
989         break;
990       case 28:
991       case 29:
992       {
993         /* FU-A      Fragmentation unit                 5.8 */
994         /* FU-B      Fragmentation unit                 5.8 */
995         gboolean S, E;
996
997         /* +---------------+
998          * |0|1|2|3|4|5|6|7|
999          * +-+-+-+-+-+-+-+-+
1000          * |S|E|R|  Type   |
1001          * +---------------+
1002          *
1003          * R is reserved and always 0
1004          */
1005         S = (payload[1] & 0x80) == 0x80;
1006         E = (payload[1] & 0x40) == 0x40;
1007
1008         GST_DEBUG_OBJECT (rtph264depay, "S %d, E %d", S, E);
1009
1010         if (rtph264depay->wait_start && !S)
1011           goto waiting_start;
1012
1013         if (S) {
1014           /* NAL unit starts here */
1015           guint8 nal_header;
1016
1017           /* If a new FU unit started, while still processing an older one.
1018            * Assume that the remote payloader is buggy (doesn't set the end
1019            * bit) and send out what we've gathered thusfar */
1020           if (G_UNLIKELY (rtph264depay->current_fu_type != 0))
1021             gst_rtp_h264_push_fragmentation_unit (rtph264depay, TRUE);
1022
1023           rtph264depay->current_fu_type = nal_unit_type;
1024           rtph264depay->fu_timestamp = timestamp;
1025
1026           rtph264depay->wait_start = FALSE;
1027
1028           /* reconstruct NAL header */
1029           nal_header = (payload[0] & 0xe0) | (payload[1] & 0x1f);
1030
1031           /* strip type header, keep FU header, we'll reuse it to reconstruct
1032            * the NAL header. */
1033           payload += 1;
1034           payload_len -= 1;
1035
1036           nalu_size = payload_len;
1037           outsize = nalu_size + sizeof (sync_bytes);
1038           outbuf = gst_buffer_new_and_alloc (outsize);
1039
1040           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1041           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
1042           map.data[sizeof (sync_bytes)] = nal_header;
1043           gst_buffer_unmap (outbuf, &map);
1044
1045           GST_DEBUG_OBJECT (rtph264depay, "queueing %d bytes", outsize);
1046
1047           /* and assemble in the adapter */
1048           gst_adapter_push (rtph264depay->adapter, outbuf);
1049         } else {
1050           /* strip off FU indicator and FU header bytes */
1051           payload += 2;
1052           payload_len -= 2;
1053
1054           outsize = payload_len;
1055           outbuf = gst_buffer_new_and_alloc (outsize);
1056           gst_buffer_fill (outbuf, 0, payload, outsize);
1057
1058           GST_DEBUG_OBJECT (rtph264depay, "queueing %d bytes", outsize);
1059
1060           /* and assemble in the adapter */
1061           gst_adapter_push (rtph264depay->adapter, outbuf);
1062         }
1063
1064         outbuf = NULL;
1065         rtph264depay->fu_marker = marker;
1066
1067         /* if NAL unit ends, flush the adapter */
1068         if (E)
1069           outbuf = gst_rtp_h264_push_fragmentation_unit (rtph264depay, FALSE);
1070         break;
1071       }
1072       default:
1073       {
1074         rtph264depay->wait_start = FALSE;
1075
1076         /* 1-23   NAL unit  Single NAL unit packet per H.264   5.6 */
1077         /* the entire payload is the output buffer */
1078         nalu_size = payload_len;
1079         outsize = nalu_size + sizeof (sync_bytes);
1080         outbuf = gst_buffer_new_and_alloc (outsize);
1081
1082         gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1083         if (rtph264depay->byte_stream) {
1084           memcpy (map.data, sync_bytes, sizeof (sync_bytes));
1085         } else {
1086           map.data[0] = map.data[1] = 0;
1087           map.data[2] = nalu_size >> 8;
1088           map.data[3] = nalu_size & 0xff;
1089         }
1090         memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
1091         gst_buffer_unmap (outbuf, &map);
1092
1093         outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf, timestamp,
1094             marker);
1095         break;
1096       }
1097     }
1098     gst_rtp_buffer_unmap (&rtp);
1099   }
1100
1101   return outbuf;
1102
1103   /* ERRORS */
1104 empty_packet:
1105   {
1106     GST_DEBUG_OBJECT (rtph264depay, "empty packet");
1107     gst_rtp_buffer_unmap (&rtp);
1108     return NULL;
1109   }
1110 undefined_type:
1111   {
1112     GST_ELEMENT_WARNING (rtph264depay, STREAM, DECODE,
1113         (NULL), ("Undefined packet type"));
1114     gst_rtp_buffer_unmap (&rtp);
1115     return NULL;
1116   }
1117 waiting_start:
1118   {
1119     GST_DEBUG_OBJECT (rtph264depay, "waiting for start");
1120     gst_rtp_buffer_unmap (&rtp);
1121     return NULL;
1122   }
1123 not_implemented:
1124   {
1125     GST_ELEMENT_ERROR (rtph264depay, STREAM, FORMAT,
1126         (NULL), ("NAL unit type %d not supported yet", nal_unit_type));
1127     gst_rtp_buffer_unmap (&rtp);
1128     return NULL;
1129   }
1130 }
1131
1132 static gboolean
1133 gst_rtp_h264_depay_handle_event (GstRTPBaseDepayload * depay, GstEvent * event)
1134 {
1135   GstRtpH264Depay *rtph264depay;
1136
1137   rtph264depay = GST_RTP_H264_DEPAY (depay);
1138
1139   switch (GST_EVENT_TYPE (event)) {
1140     case GST_EVENT_FLUSH_STOP:
1141       gst_rtp_h264_depay_reset (rtph264depay);
1142       break;
1143     default:
1144       break;
1145   }
1146
1147   return
1148       GST_RTP_BASE_DEPAYLOAD_CLASS (parent_class)->handle_event (depay, event);
1149 }
1150
1151 static GstStateChangeReturn
1152 gst_rtp_h264_depay_change_state (GstElement * element,
1153     GstStateChange transition)
1154 {
1155   GstRtpH264Depay *rtph264depay;
1156   GstStateChangeReturn ret;
1157
1158   rtph264depay = GST_RTP_H264_DEPAY (element);
1159
1160   switch (transition) {
1161     case GST_STATE_CHANGE_NULL_TO_READY:
1162       break;
1163     case GST_STATE_CHANGE_READY_TO_PAUSED:
1164       gst_rtp_h264_depay_reset (rtph264depay);
1165       break;
1166     default:
1167       break;
1168   }
1169
1170   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1171
1172   switch (transition) {
1173     case GST_STATE_CHANGE_READY_TO_NULL:
1174       break;
1175     default:
1176       break;
1177   }
1178   return ret;
1179 }
1180
1181 gboolean
1182 gst_rtp_h264_depay_plugin_init (GstPlugin * plugin)
1183 {
1184   return gst_element_register (plugin, "rtph264depay",
1185       GST_RANK_SECONDARY, GST_TYPE_RTP_H264_DEPAY);
1186 }