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