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