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