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