Merge remote-tracking branch 'origin/master' into 0.11
[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., 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/rtp/gstrtpbuffer.h>
28 #include "gstrtph264depay.h"
29
30 GST_DEBUG_CATEGORY_STATIC (rtph264depay_debug);
31 #define GST_CAT_DEFAULT (rtph264depay_debug)
32
33 #define DEFAULT_BYTE_STREAM     TRUE
34 #define DEFAULT_ACCESS_UNIT     FALSE
35
36 enum
37 {
38   PROP_0,
39   PROP_BYTE_STREAM,
40   PROP_ACCESS_UNIT,
41   PROP_LAST
42 };
43
44
45 /* 3 zero bytes syncword */
46 static const guint8 sync_bytes[] = { 0, 0, 0, 1 };
47
48 static GstStaticPadTemplate gst_rtp_h264_depay_src_template =
49     GST_STATIC_PAD_TEMPLATE ("src",
50     GST_PAD_SRC,
51     GST_PAD_ALWAYS,
52     GST_STATIC_CAPS ("video/x-h264, "
53         "stream-format = (string) avc, alignment = (string) au; "
54         "video/x-h264, "
55         "stream-format = (string) byte-stream, alignment = (string) { nal, au }")
56     );
57
58 static GstStaticPadTemplate gst_rtp_h264_depay_sink_template =
59 GST_STATIC_PAD_TEMPLATE ("sink",
60     GST_PAD_SINK,
61     GST_PAD_ALWAYS,
62     GST_STATIC_CAPS ("application/x-rtp, "
63         "media = (string) \"video\", "
64         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
65         "clock-rate = (int) 90000, " "encoding-name = (string) \"H264\"")
66         /** optional parameters **/
67     /* "profile-level-id = (string) ANY, " */
68     /* "max-mbps = (string) ANY, " */
69     /* "max-fs = (string) ANY, " */
70     /* "max-cpb = (string) ANY, " */
71     /* "max-dpb = (string) ANY, " */
72     /* "max-br = (string) ANY, " */
73     /* "redundant-pic-cap = (string) { \"0\", \"1\" }, " */
74     /* "sprop-parameter-sets = (string) ANY, " */
75     /* "parameter-add = (string) { \"0\", \"1\" }, " */
76     /* "packetization-mode = (string) { \"0\", \"1\", \"2\" }, " */
77     /* "sprop-interleaving-depth = (string) ANY, " */
78     /* "sprop-deint-buf-req = (string) ANY, " */
79     /* "deint-buf-cap = (string) ANY, " */
80     /* "sprop-init-buf-time = (string) ANY, " */
81     /* "sprop-max-don-diff = (string) ANY, " */
82     /* "max-rcmd-nalu-size = (string) ANY " */
83     );
84
85 #define gst_rtp_h264_depay_parent_class parent_class
86 G_DEFINE_TYPE (GstRtpH264Depay, gst_rtp_h264_depay,
87     GST_TYPE_RTP_BASE_DEPAYLOAD);
88
89 static void gst_rtp_h264_depay_finalize (GObject * object);
90 static void gst_rtp_h264_depay_set_property (GObject * object, guint prop_id,
91     const GValue * value, GParamSpec * pspec);
92 static void gst_rtp_h264_depay_get_property (GObject * object, guint prop_id,
93     GValue * value, GParamSpec * pspec);
94
95 static GstStateChangeReturn gst_rtp_h264_depay_change_state (GstElement *
96     element, GstStateChange transition);
97
98 static GstBuffer *gst_rtp_h264_depay_process (GstRTPBaseDepayload * depayload,
99     GstBuffer * buf);
100 static gboolean gst_rtp_h264_depay_setcaps (GstRTPBaseDepayload * filter,
101     GstCaps * caps);
102 static gboolean gst_rtp_h264_depay_handle_event (GstRTPBaseDepayload * depay,
103     GstEvent * event);
104
105 static void
106 gst_rtp_h264_depay_class_init (GstRtpH264DepayClass * klass)
107 {
108   GObjectClass *gobject_class;
109   GstElementClass *gstelement_class;
110   GstRTPBaseDepayloadClass *gstrtpbasedepayload_class;
111
112   gobject_class = (GObjectClass *) klass;
113   gstelement_class = (GstElementClass *) klass;
114   gstrtpbasedepayload_class = (GstRTPBaseDepayloadClass *) klass;
115
116   gobject_class->finalize = gst_rtp_h264_depay_finalize;
117
118   gobject_class->set_property = gst_rtp_h264_depay_set_property;
119   gobject_class->get_property = gst_rtp_h264_depay_get_property;
120
121   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BYTE_STREAM,
122       g_param_spec_boolean ("byte-stream", "Byte Stream",
123           "Generate byte stream format of NALU (deprecated; use caps)",
124           DEFAULT_BYTE_STREAM, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
125   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ACCESS_UNIT,
126       g_param_spec_boolean ("access-unit", "Access Unit",
127           "Merge NALU into AU (picture) (deprecated; use caps)",
128           DEFAULT_ACCESS_UNIT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
129
130   gst_element_class_add_pad_template (gstelement_class,
131       gst_static_pad_template_get (&gst_rtp_h264_depay_src_template));
132   gst_element_class_add_pad_template (gstelement_class,
133       gst_static_pad_template_get (&gst_rtp_h264_depay_sink_template));
134
135   gst_element_class_set_details_simple (gstelement_class,
136       "RTP H264 depayloader", "Codec/Depayloader/Network/RTP",
137       "Extracts H264 video from RTP packets (RFC 3984)",
138       "Wim Taymans <wim.taymans@gmail.com>");
139   gstelement_class->change_state = gst_rtp_h264_depay_change_state;
140
141   gstrtpbasedepayload_class->process = gst_rtp_h264_depay_process;
142   gstrtpbasedepayload_class->set_caps = gst_rtp_h264_depay_setcaps;
143   gstrtpbasedepayload_class->handle_event = gst_rtp_h264_depay_handle_event;
144
145   GST_DEBUG_CATEGORY_INIT (rtph264depay_debug, "rtph264depay", 0,
146       "H264 Video RTP Depayloader");
147 }
148
149 static void
150 gst_rtp_h264_depay_init (GstRtpH264Depay * rtph264depay)
151 {
152   rtph264depay->adapter = gst_adapter_new ();
153   rtph264depay->picture_adapter = gst_adapter_new ();
154   rtph264depay->byte_stream = DEFAULT_BYTE_STREAM;
155   rtph264depay->merge = DEFAULT_ACCESS_UNIT;
156 }
157
158 static void
159 gst_rtp_h264_depay_reset (GstRtpH264Depay * rtph264depay)
160 {
161   gst_adapter_clear (rtph264depay->adapter);
162   rtph264depay->wait_start = TRUE;
163   gst_adapter_clear (rtph264depay->picture_adapter);
164   rtph264depay->picture_start = FALSE;
165   rtph264depay->last_keyframe = FALSE;
166   rtph264depay->last_ts = 0;
167   rtph264depay->current_fu_type = 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_OBJECT_CLASS (parent_class)->finalize (object);
184 }
185
186 static void
187 gst_rtp_h264_depay_set_property (GObject * object, guint prop_id,
188     const GValue * value, GParamSpec * pspec)
189 {
190   GstRtpH264Depay *rtph264depay;
191
192   rtph264depay = GST_RTP_H264_DEPAY (object);
193
194   switch (prop_id) {
195     case PROP_BYTE_STREAM:
196       rtph264depay->byte_stream = g_value_get_boolean (value);
197       break;
198     case PROP_ACCESS_UNIT:
199       rtph264depay->merge = g_value_get_boolean (value);
200       break;
201     default:
202       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
203       break;
204   }
205 }
206
207 static void
208 gst_rtp_h264_depay_get_property (GObject * object, guint prop_id,
209     GValue * value, GParamSpec * pspec)
210 {
211   GstRtpH264Depay *rtph264depay;
212
213   rtph264depay = GST_RTP_H264_DEPAY (object);
214
215   switch (prop_id) {
216     case PROP_BYTE_STREAM:
217       g_value_set_boolean (value, rtph264depay->byte_stream);
218       break;
219     case PROP_ACCESS_UNIT:
220       g_value_set_boolean (value, rtph264depay->merge);
221       break;
222     default:
223       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
224       break;
225   }
226 }
227
228 static void
229 gst_rtp_h264_depay_negotiate (GstRtpH264Depay * rtph264depay)
230 {
231   GstCaps *caps;
232   gint byte_stream = -1;
233   gint merge = -1;
234
235   caps =
236       gst_pad_get_allowed_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph264depay));
237
238   GST_DEBUG_OBJECT (rtph264depay, "allowed caps: %" GST_PTR_FORMAT, caps);
239
240   if (caps) {
241     if (gst_caps_get_size (caps) > 0) {
242       GstStructure *s = gst_caps_get_structure (caps, 0);
243       const gchar *str = NULL;
244
245       if ((str = gst_structure_get_string (s, "stream-format"))) {
246         if (strcmp (str, "avc") == 0) {
247           byte_stream = FALSE;
248         } else if (strcmp (str, "byte-stream") == 0) {
249           byte_stream = TRUE;
250         } else {
251           GST_DEBUG_OBJECT (rtph264depay, "unknown stream-format: %s", str);
252         }
253       }
254
255       if ((str = gst_structure_get_string (s, "alignment"))) {
256         if (strcmp (str, "au") == 0) {
257           merge = TRUE;
258         } else if (strcmp (str, "nal") == 0) {
259           merge = FALSE;
260         } else {
261           GST_DEBUG_OBJECT (rtph264depay, "unknown alignment: %s", str);
262         }
263       }
264     }
265     gst_caps_unref (caps);
266   }
267
268   if (byte_stream >= 0) {
269     GST_DEBUG_OBJECT (rtph264depay, "downstream requires byte-stream %d",
270         byte_stream);
271     if (rtph264depay->byte_stream != byte_stream) {
272       GST_WARNING_OBJECT (rtph264depay,
273           "overriding property setting based on caps");
274       rtph264depay->byte_stream = byte_stream;
275     }
276   }
277   if (merge >= 0) {
278     GST_DEBUG_OBJECT (rtph264depay, "downstream requires merge %d", merge);
279     if (rtph264depay->merge != merge) {
280       GST_WARNING_OBJECT (rtph264depay,
281           "overriding property setting based on caps");
282       rtph264depay->merge = merge;
283     }
284   }
285 }
286
287 static gboolean
288 gst_rtp_h264_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
289 {
290   GstCaps *srccaps;
291   gint clock_rate;
292   GstStructure *structure = gst_caps_get_structure (caps, 0);
293   GstRtpH264Depay *rtph264depay;
294   const gchar *ps, *profile;
295   GstBuffer *codec_data;
296   GstMapInfo map;
297   guint8 *ptr;
298   gboolean res;
299
300   rtph264depay = GST_RTP_H264_DEPAY (depayload);
301
302   if (!gst_structure_get_int (structure, "clock-rate", &clock_rate))
303     clock_rate = 90000;
304   depayload->clock_rate = clock_rate;
305
306   srccaps = gst_caps_new_empty_simple ("video/x-h264");
307
308   /* Base64 encoded, comma separated config NALs */
309   ps = gst_structure_get_string (structure, "sprop-parameter-sets");
310   /* hex: AVCProfileIndication:8 | profile_compat:8 | AVCLevelIndication:8 */
311   profile = gst_structure_get_string (structure, "profile-level-id");
312
313   /* negotiate with downstream w.r.t. output format and alignment */
314   gst_rtp_h264_depay_negotiate (rtph264depay);
315
316   if (rtph264depay->byte_stream && ps != NULL) {
317     /* for bytestream we only need the parameter sets but we don't error out
318      * when they are not there, we assume they are in the stream. */
319     gchar **params;
320     guint len, total;
321     gint i;
322
323     params = g_strsplit (ps, ",", 0);
324
325     /* count total number of bytes in base64. Also include the sync bytes in
326      * front of the params. */
327     len = 0;
328     for (i = 0; params[i]; i++) {
329       len += strlen (params[i]);
330       len += sizeof (sync_bytes);
331     }
332     /* we seriously overshoot the length, but it's fine. */
333     codec_data = gst_buffer_new_and_alloc (len);
334
335     gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
336     ptr = map.data;
337     total = 0;
338     for (i = 0; params[i]; i++) {
339       guint save = 0;
340       gint state = 0;
341
342       GST_DEBUG_OBJECT (depayload, "decoding param %d (%s)", i, params[i]);
343       memcpy (ptr, sync_bytes, sizeof (sync_bytes));
344       ptr += sizeof (sync_bytes);
345       len =
346           g_base64_decode_step (params[i], strlen (params[i]), ptr, &state,
347           &save);
348       GST_DEBUG_OBJECT (depayload, "decoded %d bytes", len);
349       total += len + sizeof (sync_bytes);
350       ptr += len;
351     }
352     gst_buffer_unmap (codec_data, &map);
353     gst_buffer_resize (codec_data, 0, total);
354     g_strfreev (params);
355
356     /* keep the codec_data, we need to send it as the first buffer. We cannot
357      * push it in the adapter because the adapter might be flushed on discont.
358      */
359     if (rtph264depay->codec_data)
360       gst_buffer_unref (rtph264depay->codec_data);
361     rtph264depay->codec_data = codec_data;
362   } else if (!rtph264depay->byte_stream) {
363     gchar **params;
364     guint8 **sps, **pps;
365     guint len, num_sps, num_pps;
366     gint i;
367
368     if (ps == NULL)
369       goto incomplete_caps;
370
371     params = g_strsplit (ps, ",", 0);
372     len = g_strv_length (params);
373
374     GST_DEBUG_OBJECT (depayload, "we have %d params", len);
375
376     sps = g_new0 (guint8 *, len + 1);
377     pps = g_new0 (guint8 *, len + 1);
378     num_sps = num_pps = 0;
379
380     /* start with 7 bytes header */
381     len = 7;
382     for (i = 0; params[i]; i++) {
383       gsize nal_len;
384       guint8 *nalp;
385       guint save = 0;
386       gint state = 0;
387
388       nal_len = strlen (params[i]);
389       nalp = g_malloc (nal_len + 2);
390
391       nal_len =
392           g_base64_decode_step (params[i], nal_len, nalp + 2, &state, &save);
393       nalp[0] = (nal_len >> 8) & 0xff;
394       nalp[1] = nal_len & 0xff;
395       len += nal_len + 2;
396
397       /* copy to the right list */
398       if ((nalp[2] & 0x1f) == 7) {
399         GST_DEBUG_OBJECT (depayload, "adding param %d as SPS %d", i, num_sps);
400         sps[num_sps++] = nalp;
401       } else {
402         GST_DEBUG_OBJECT (depayload, "adding param %d as PPS %d", i, num_pps);
403         pps[num_pps++] = nalp;
404       }
405     }
406     g_strfreev (params);
407
408     if (num_sps == 0 || (GST_READ_UINT16_BE (sps[0]) < 3) || num_pps == 0) {
409       g_strfreev ((gchar **) pps);
410       g_strfreev ((gchar **) sps);
411       goto incomplete_caps;
412     }
413
414     codec_data = gst_buffer_new_and_alloc (len);
415
416     gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
417     ptr = map.data;
418
419     /* 8 bits version == 1 */
420     *ptr++ = 1;
421     if (profile) {
422       guint32 profile_id;
423
424       /* hex: AVCProfileIndication:8 | profile_compat:8 | AVCLevelIndication:8 */
425       sscanf (profile, "%6x", &profile_id);
426       *ptr++ = (profile_id >> 16) & 0xff;
427       *ptr++ = (profile_id >> 8) & 0xff;
428       *ptr++ = profile_id & 0xff;
429     } else {
430       /* extract from SPS */
431       *ptr++ = sps[0][3];
432       *ptr++ = sps[0][4];
433       *ptr++ = sps[0][5];
434     }
435     /* 6 bits reserved | 2 bits lengthSizeMinusOn */
436     *ptr++ = 0xff;
437     /* 3 bits reserved | 5 bits numOfSequenceParameterSets */
438     *ptr++ = 0xe0 | (num_sps & 0x1f);
439
440     /* copy all SPS */
441     for (i = 0; sps[i]; i++) {
442       len = ((sps[i][0] << 8) | sps[i][1]) + 2;
443       GST_DEBUG_OBJECT (depayload, "copy SPS %d of length %d", i, len);
444       memcpy (ptr, sps[i], len);
445       g_free (sps[i]);
446       ptr += len;
447     }
448     g_free (sps);
449     /* 8 bits numOfPictureParameterSets */
450     *ptr++ = num_pps;
451     /* copy all PPS */
452     for (i = 0; pps[i]; i++) {
453       len = ((pps[i][0] << 8) | pps[i][1]) + 2;
454       GST_DEBUG_OBJECT (depayload, "copy PPS %d of length %d", i, len);
455       memcpy (ptr, pps[i], len);
456       g_free (pps[i]);
457       ptr += len;
458     }
459     g_free (pps);
460     gst_buffer_resize (codec_data, 0, ptr - map.data);
461     gst_buffer_unmap (codec_data, &map);
462
463     gst_caps_set_simple (srccaps,
464         "codec_data", GST_TYPE_BUFFER, codec_data, NULL);
465     gst_buffer_unref (codec_data);
466   }
467
468   gst_caps_set_simple (srccaps, "stream-format", G_TYPE_STRING,
469       rtph264depay->byte_stream ? "byte-stream" : "avc",
470       "alignment", G_TYPE_STRING, rtph264depay->merge ? "au" : "nal", NULL);
471
472   res = gst_pad_set_caps (depayload->srcpad, srccaps);
473   gst_caps_unref (srccaps);
474
475   return res;
476
477   /* ERRORS */
478 incomplete_caps:
479   {
480     GST_DEBUG_OBJECT (depayload, "we have incomplete caps");
481     gst_caps_unref (srccaps);
482     return FALSE;
483   }
484 }
485
486 static GstBuffer *
487 gst_rtp_h264_complete_au (GstRtpH264Depay * rtph264depay,
488     GstClockTime * out_timestamp, gboolean * out_keyframe)
489 {
490   guint outsize;
491   GstBuffer *outbuf;
492
493   /* we had a picture in the adapter and we completed it */
494   GST_DEBUG_OBJECT (rtph264depay, "taking completed AU");
495   outsize = gst_adapter_available (rtph264depay->picture_adapter);
496   outbuf = gst_adapter_take_buffer (rtph264depay->picture_adapter, outsize);
497
498   *out_timestamp = rtph264depay->last_ts;
499   *out_keyframe = rtph264depay->last_keyframe;
500
501   rtph264depay->last_keyframe = FALSE;
502   rtph264depay->picture_start = FALSE;
503
504   return outbuf;
505 }
506
507 /* SPS/PPS/IDR considered key, all others DELTA;
508  * so downstream waiting for keyframe can pick up at SPS/PPS/IDR */
509 #define NAL_TYPE_IS_KEY(nt) (((nt) == 5) || ((nt) == 7) || ((nt) == 8))
510
511 static GstBuffer *
512 gst_rtp_h264_depay_handle_nal (GstRtpH264Depay * rtph264depay, GstBuffer * nal,
513     GstClockTime in_timestamp, gboolean marker)
514 {
515   GstRTPBaseDepayload *depayload = GST_RTP_BASE_DEPAYLOAD (rtph264depay);
516   gint nal_type;
517   GstMapInfo map;
518   GstBuffer *outbuf = NULL;
519   GstClockTime out_timestamp;
520   gboolean keyframe, out_keyframe;
521
522   gst_buffer_map (nal, &map, GST_MAP_READ);
523   if (G_UNLIKELY (map.size < 5))
524     goto short_nal;
525
526   nal_type = map.data[4] & 0x1f;
527   GST_DEBUG_OBJECT (rtph264depay, "handle NAL type %d", nal_type);
528
529   keyframe = NAL_TYPE_IS_KEY (nal_type);
530
531   out_keyframe = keyframe;
532   out_timestamp = in_timestamp;
533
534   if (rtph264depay->merge) {
535     gboolean start = FALSE, complete = FALSE;
536
537     /* consider a coded slices (IDR or not) to start a picture,
538      * (so ending the previous one) if first_mb_in_slice == 0
539      * (non-0 is part of previous one) */
540     /* NOTE this is not entirely according to Access Unit specs in 7.4.1.2.4,
541      * but in practice it works in sane cases, needs not much parsing,
542      * and also works with broken frame_num in NAL (where spec-wise would fail) */
543     if (nal_type == 1 || nal_type == 2 || nal_type == 5) {
544       /* we have a picture start */
545       start = TRUE;
546       if (map.data[5] & 0x80) {
547         /* first_mb_in_slice == 0 completes a picture */
548         complete = TRUE;
549       }
550     } else if (nal_type >= 6 && nal_type <= 9) {
551       /* SEI, SPS, PPS, AU terminate picture */
552       complete = TRUE;
553     }
554     GST_DEBUG_OBJECT (depayload, "start %d, complete %d", start, complete);
555
556     if (complete && rtph264depay->picture_start)
557       outbuf = gst_rtp_h264_complete_au (rtph264depay, &out_timestamp,
558           &out_keyframe);
559
560     /* add to adapter */
561     GST_DEBUG_OBJECT (depayload, "adding NAL to picture adapter");
562     gst_adapter_push (rtph264depay->picture_adapter, nal);
563     rtph264depay->last_ts = in_timestamp;
564     rtph264depay->last_keyframe |= keyframe;
565     rtph264depay->picture_start |= start;
566
567     if (marker)
568       outbuf = gst_rtp_h264_complete_au (rtph264depay, &out_timestamp,
569           &out_keyframe);
570   } else {
571     /* no merge, output is input nal */
572     GST_DEBUG_OBJECT (depayload, "using NAL as output");
573     outbuf = nal;
574   }
575   gst_buffer_unmap (nal, &map);
576
577   if (outbuf) {
578     /* prepend codec_data */
579     if (rtph264depay->codec_data) {
580       GST_DEBUG_OBJECT (depayload, "prepending codec_data");
581       outbuf = gst_buffer_join (rtph264depay->codec_data, outbuf);
582       rtph264depay->codec_data = NULL;
583       out_keyframe = TRUE;
584     }
585     outbuf = gst_buffer_make_writable (outbuf);
586
587     GST_BUFFER_TIMESTAMP (outbuf) = out_timestamp;
588
589     if (out_keyframe)
590       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
591     else
592       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
593   }
594
595   return outbuf;
596
597   /* ERRORS */
598 short_nal:
599   {
600     GST_WARNING_OBJECT (depayload, "dropping short NAL");
601     gst_buffer_unmap (nal, &map);
602     gst_buffer_unref (nal);
603     return NULL;
604   }
605 }
606
607 static GstBuffer *
608 gst_rtp_h264_push_fragmentation_unit (GstRtpH264Depay * rtph264depay,
609     gboolean send)
610 {
611   guint outsize;
612   GstMapInfo map;
613   GstBuffer *outbuf;
614
615   outsize = gst_adapter_available (rtph264depay->adapter);
616   outbuf = gst_adapter_take_buffer (rtph264depay->adapter, outsize);
617
618   gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
619   GST_DEBUG_OBJECT (rtph264depay, "output %d bytes", outsize);
620
621   if (rtph264depay->byte_stream) {
622     memcpy (map.data, sync_bytes, sizeof (sync_bytes));
623   } else {
624     outsize -= 4;
625     map.data[0] = (outsize >> 24);
626     map.data[1] = (outsize >> 16);
627     map.data[2] = (outsize >> 8);
628     map.data[3] = (outsize);
629   }
630   gst_buffer_unmap (outbuf, &map);
631
632   rtph264depay->current_fu_type = 0;
633
634   if (send) {
635     outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf,
636         rtph264depay->fu_timestamp, rtph264depay->fu_marker);
637     if (outbuf)
638       gst_rtp_base_depayload_push (GST_RTP_BASE_DEPAYLOAD (rtph264depay),
639           outbuf);
640     return NULL;
641   } else {
642     return gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf,
643         rtph264depay->fu_timestamp, rtph264depay->fu_marker);
644   }
645 }
646
647 static GstBuffer *
648 gst_rtp_h264_depay_process (GstRTPBaseDepayload * depayload, GstBuffer * buf)
649 {
650   GstRtpH264Depay *rtph264depay;
651   GstBuffer *outbuf = NULL;
652   guint8 nal_unit_type;
653   GstRTPBuffer rtp = { NULL };
654
655   rtph264depay = GST_RTP_H264_DEPAY (depayload);
656
657   /* flush remaining data on discont */
658   if (GST_BUFFER_IS_DISCONT (buf)) {
659     gst_adapter_clear (rtph264depay->adapter);
660     rtph264depay->wait_start = TRUE;
661     rtph264depay->current_fu_type = 0;
662   }
663
664   {
665     gint payload_len;
666     guint8 *payload;
667     guint header_len;
668     guint8 nal_ref_idc;
669     GstMapInfo map;
670     guint outsize, nalu_size;
671     GstClockTime timestamp;
672     gboolean marker;
673
674     timestamp = GST_BUFFER_TIMESTAMP (buf);
675
676     gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp);
677
678     payload_len = gst_rtp_buffer_get_payload_len (&rtp);
679     payload = gst_rtp_buffer_get_payload (&rtp);
680     marker = gst_rtp_buffer_get_marker (&rtp);
681
682     GST_DEBUG_OBJECT (rtph264depay, "receiving %d bytes", payload_len);
683
684     if (payload_len == 0)
685       return NULL;
686
687     /* +---------------+
688      * |0|1|2|3|4|5|6|7|
689      * +-+-+-+-+-+-+-+-+
690      * |F|NRI|  Type   |
691      * +---------------+
692      *
693      * F must be 0.
694      */
695     nal_ref_idc = (payload[0] & 0x60) >> 5;
696     nal_unit_type = payload[0] & 0x1f;
697
698     /* at least one byte header with type */
699     header_len = 1;
700
701     GST_DEBUG_OBJECT (rtph264depay, "NRI %d, Type %d", nal_ref_idc,
702         nal_unit_type);
703
704     /* If FU unit was being processed, but the current nal is of a different
705      * type.  Assume that the remote payloader is buggy (didn't set the end bit
706      * when the FU ended) and send out what we gathered thusfar */
707     if (G_UNLIKELY (rtph264depay->current_fu_type != 0 &&
708             nal_unit_type != rtph264depay->current_fu_type))
709       gst_rtp_h264_push_fragmentation_unit (rtph264depay, TRUE);
710
711     switch (nal_unit_type) {
712       case 0:
713       case 30:
714       case 31:
715         /* undefined */
716         goto undefined_type;
717       case 25:
718         /* STAP-B    Single-time aggregation packet     5.7.1 */
719         /* 2 byte extra header for DON */
720         header_len += 2;
721         /* fallthrough */
722       case 24:
723       {
724         /* strip headers */
725         payload += header_len;
726         payload_len -= header_len;
727
728         rtph264depay->wait_start = FALSE;
729
730
731         /* STAP-A    Single-time aggregation packet     5.7.1 */
732         while (payload_len > 2) {
733           /*                      1          
734            *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 
735            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
736            * |         NALU Size             |
737            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
738            */
739           nalu_size = (payload[0] << 8) | payload[1];
740
741           /* dont include nalu_size */
742           if (nalu_size > (payload_len - 2))
743             nalu_size = payload_len - 2;
744
745           outsize = nalu_size + sizeof (sync_bytes);
746           outbuf = gst_buffer_new_and_alloc (outsize);
747
748           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
749           if (rtph264depay->byte_stream) {
750             memcpy (map.data, sync_bytes, sizeof (sync_bytes));
751           } else {
752             map.data[0] = map.data[1] = 0;
753             map.data[2] = payload[0];
754             map.data[3] = payload[1];
755           }
756
757           /* strip NALU size */
758           payload += 2;
759           payload_len -= 2;
760
761           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
762           gst_buffer_unmap (outbuf, &map);
763
764           gst_adapter_push (rtph264depay->adapter, outbuf);
765
766           payload += nalu_size;
767           payload_len -= nalu_size;
768         }
769
770         outsize = gst_adapter_available (rtph264depay->adapter);
771         outbuf = gst_adapter_take_buffer (rtph264depay->adapter, outsize);
772
773         outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf, timestamp,
774             marker);
775         break;
776       }
777       case 26:
778         /* MTAP16    Multi-time aggregation packet      5.7.2 */
779         header_len = 5;
780         /* fallthrough, not implemented */
781       case 27:
782         /* MTAP24    Multi-time aggregation packet      5.7.2 */
783         header_len = 6;
784         goto not_implemented;
785         break;
786       case 28:
787       case 29:
788       {
789         /* FU-A      Fragmentation unit                 5.8 */
790         /* FU-B      Fragmentation unit                 5.8 */
791         gboolean S, E;
792
793         /* +---------------+
794          * |0|1|2|3|4|5|6|7|
795          * +-+-+-+-+-+-+-+-+
796          * |S|E|R|  Type   |
797          * +---------------+
798          *
799          * R is reserved and always 0
800          */
801         S = (payload[1] & 0x80) == 0x80;
802         E = (payload[1] & 0x40) == 0x40;
803
804         GST_DEBUG_OBJECT (rtph264depay, "S %d, E %d", S, E);
805
806         if (rtph264depay->wait_start && !S)
807           goto waiting_start;
808
809         if (S) {
810           /* NAL unit starts here */
811           guint8 nal_header;
812
813           /* If a new FU unit started, while still processing an older one.
814            * Assume that the remote payloader is buggy (doesn't set the end
815            * bit) and send out what we've gathered thusfar */
816           if (G_UNLIKELY (rtph264depay->current_fu_type != 0))
817             gst_rtp_h264_push_fragmentation_unit (rtph264depay, TRUE);
818
819           rtph264depay->current_fu_type = nal_unit_type;
820           rtph264depay->fu_timestamp = timestamp;
821
822           rtph264depay->wait_start = FALSE;
823
824           /* reconstruct NAL header */
825           nal_header = (payload[0] & 0xe0) | (payload[1] & 0x1f);
826
827           /* strip type header, keep FU header, we'll reuse it to reconstruct
828            * the NAL header. */
829           payload += 1;
830           payload_len -= 1;
831
832           nalu_size = payload_len;
833           outsize = nalu_size + sizeof (sync_bytes);
834           outbuf = gst_buffer_new_and_alloc (outsize);
835
836           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
837           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
838           map.data[sizeof (sync_bytes)] = nal_header;
839           gst_buffer_unmap (outbuf, &map);
840
841           GST_DEBUG_OBJECT (rtph264depay, "queueing %d bytes", outsize);
842
843           /* and assemble in the adapter */
844           gst_adapter_push (rtph264depay->adapter, outbuf);
845         } else {
846           /* strip off FU indicator and FU header bytes */
847           payload += 2;
848           payload_len -= 2;
849
850           outsize = payload_len;
851           outbuf = gst_buffer_new_and_alloc (outsize);
852           gst_buffer_fill (outbuf, 0, payload, outsize);
853
854           GST_DEBUG_OBJECT (rtph264depay, "queueing %d bytes", outsize);
855
856           /* and assemble in the adapter */
857           gst_adapter_push (rtph264depay->adapter, outbuf);
858         }
859
860         outbuf = NULL;
861         rtph264depay->fu_marker = marker;
862
863         /* if NAL unit ends, flush the adapter */
864         if (E)
865           outbuf = gst_rtp_h264_push_fragmentation_unit (rtph264depay, FALSE);
866         break;
867       }
868       default:
869       {
870         rtph264depay->wait_start = FALSE;
871
872         /* 1-23   NAL unit  Single NAL unit packet per H.264   5.6 */
873         /* the entire payload is the output buffer */
874         nalu_size = payload_len;
875         outsize = nalu_size + sizeof (sync_bytes);
876         outbuf = gst_buffer_new_and_alloc (outsize);
877
878         gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
879         if (rtph264depay->byte_stream) {
880           memcpy (map.data, sync_bytes, sizeof (sync_bytes));
881         } else {
882           map.data[0] = map.data[1] = 0;
883           map.data[2] = nalu_size >> 8;
884           map.data[3] = nalu_size & 0xff;
885         }
886         memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
887         gst_buffer_unmap (outbuf, &map);
888
889         outbuf = gst_rtp_h264_depay_handle_nal (rtph264depay, outbuf, timestamp,
890             marker);
891         break;
892       }
893     }
894     gst_rtp_buffer_unmap (&rtp);
895   }
896
897   return outbuf;
898
899   /* ERRORS */
900 undefined_type:
901   {
902     GST_ELEMENT_WARNING (rtph264depay, STREAM, DECODE,
903         (NULL), ("Undefined packet type"));
904     gst_rtp_buffer_unmap (&rtp);
905     return NULL;
906   }
907 waiting_start:
908   {
909     GST_DEBUG_OBJECT (rtph264depay, "waiting for start");
910     gst_rtp_buffer_unmap (&rtp);
911     return NULL;
912   }
913 not_implemented:
914   {
915     GST_ELEMENT_ERROR (rtph264depay, STREAM, FORMAT,
916         (NULL), ("NAL unit type %d not supported yet", nal_unit_type));
917     gst_rtp_buffer_unmap (&rtp);
918     return NULL;
919   }
920 }
921
922 static gboolean
923 gst_rtp_h264_depay_handle_event (GstRTPBaseDepayload * depay, GstEvent * event)
924 {
925   GstRtpH264Depay *rtph264depay;
926
927   rtph264depay = GST_RTP_H264_DEPAY (depay);
928
929   switch (GST_EVENT_TYPE (event)) {
930     case GST_EVENT_FLUSH_STOP:
931       gst_rtp_h264_depay_reset (rtph264depay);
932       break;
933     default:
934       break;
935   }
936
937   return
938       GST_RTP_BASE_DEPAYLOAD_CLASS (parent_class)->handle_event (depay, event);
939 }
940
941 static GstStateChangeReturn
942 gst_rtp_h264_depay_change_state (GstElement * element,
943     GstStateChange transition)
944 {
945   GstRtpH264Depay *rtph264depay;
946   GstStateChangeReturn ret;
947
948   rtph264depay = GST_RTP_H264_DEPAY (element);
949
950   switch (transition) {
951     case GST_STATE_CHANGE_NULL_TO_READY:
952       break;
953     case GST_STATE_CHANGE_READY_TO_PAUSED:
954       gst_rtp_h264_depay_reset (rtph264depay);
955       break;
956     default:
957       break;
958   }
959
960   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
961
962   switch (transition) {
963     case GST_STATE_CHANGE_READY_TO_NULL:
964       break;
965     default:
966       break;
967   }
968   return ret;
969 }
970
971 gboolean
972 gst_rtp_h264_depay_plugin_init (GstPlugin * plugin)
973 {
974   return gst_element_register (plugin, "rtph264depay",
975       GST_RANK_SECONDARY, GST_TYPE_RTP_H264_DEPAY);
976 }