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