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