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