rtph265depay: make sure we call handle_nal for each NAL
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtph265depay.c
1 /* GStreamer
2  * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C) <2014> Jurgen Slowack <jurgenslowack@gmail.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <stdio.h>
26 #include <string.h>
27
28 #include <gst/base/gstbitreader.h>
29 #include <gst/rtp/gstrtpbuffer.h>
30 #include <gst/video/video.h>
31 #include "gstrtph265depay.h"
32
33 GST_DEBUG_CATEGORY_STATIC (rtph265depay_debug);
34 #define GST_CAT_DEFAULT (rtph265depay_debug)
35
36 /* This is what we'll default to when downstream hasn't
37  * expressed a restriction or preference via caps */
38 #define DEFAULT_BYTE_STREAM   TRUE
39 #define DEFAULT_ACCESS_UNIT   FALSE
40
41 /* 3 zero bytes syncword */
42 static const guint8 sync_bytes[] = { 0, 0, 0, 1 };
43
44 static GstStaticPadTemplate gst_rtp_h265_depay_src_template =
45     GST_STATIC_PAD_TEMPLATE ("src",
46     GST_PAD_SRC,
47     GST_PAD_ALWAYS,
48     GST_STATIC_CAPS (
49         /* FIXME - hvc1 and hev1 formats are not supported yet */
50         /*"video/x-h265, "
51            "stream-format = (string) hvc1, alignment = (string) au; "
52            "video/x-h265, "
53            "stream-format = (string) hev1, alignment = (string) au; " */
54         "video/x-h265, "
55         "stream-format = (string) byte-stream, alignment = (string) { nal, au }")
56     );
57
58 static GstStaticPadTemplate gst_rtp_h265_depay_sink_template =
59 GST_STATIC_PAD_TEMPLATE ("sink",
60     GST_PAD_SINK,
61     GST_PAD_ALWAYS,
62     GST_STATIC_CAPS ("application/x-rtp, "
63         "media = (string) \"video\", "
64         "clock-rate = (int) 90000, " "encoding-name = (string) \"H265\"")
65         /** optional parameters **/
66     /* "profile-space = (int) [ 0, 3 ], " */
67     /* "profile-id = (int) [ 0, 31 ], " */
68     /* "tier-flag = (int) [ 0, 1 ], " */
69     /* "level-id = (int) [ 0, 255 ], " */
70     /* "interop-constraints = (string) ANY, " */
71     /* "profile-compatibility-indicator = (string) ANY, " */
72     /* "sprop-sub-layer-id = (int) [ 0, 6 ], " */
73     /* "recv-sub-layer-id = (int) [ 0, 6 ], " */
74     /* "max-recv-level-id = (int) [ 0, 255 ], " */
75     /* "tx-mode = (string) {MST , SST}, " */
76     /* "sprop-vps = (string) ANY, " */
77     /* "sprop-sps = (string) ANY, " */
78     /* "sprop-pps = (string) ANY, " */
79     /* "sprop-sei = (string) ANY, " */
80     /* "max-lsr = (int) ANY, " *//* MUST be in the range of MaxLumaSR to 16 * MaxLumaSR, inclusive */
81     /* "max-lps = (int) ANY, " *//* MUST be in the range of MaxLumaPS to 16 * MaxLumaPS, inclusive */
82     /* "max-cpb = (int) ANY, " *//* MUST be in the range of MaxCPB to 16 * MaxCPB, inclusive */
83     /* "max-dpb = (int) [1, 16], " */
84     /* "max-br = (int) ANY, " *//* MUST be in the range of MaxBR to 16 * MaxBR, inclusive, for the highest level */
85     /* "max-tr = (int) ANY, " *//* MUST be in the range of MaxTileRows to 16 * MaxTileRows, inclusive, for the highest level */
86     /* "max-tc = (int) ANY, " *//* MUST be in the range of MaxTileCols to 16 * MaxTileCols, inclusive, for the highest level */
87     /* "max-fps = (int) ANY, " */
88     /* "sprop-max-don-diff = (int) [0, 32767], " */
89     /* "sprop-depack-buf-nalus = (int) [0, 32767], " */
90     /* "sprop-depack-buf-nalus = (int) [0, 4294967295], " */
91     /* "depack-buf-cap = (int) [1, 4294967295], " */
92     /* "sprop-segmentation-id = (int) [0, 3], " */
93     /* "sprop-spatial-segmentation-idc = (string) ANY, " */
94     /* "dec-parallel-cap = (string) ANY, " */
95     );
96
97 #define gst_rtp_h265_depay_parent_class parent_class
98 G_DEFINE_TYPE (GstRtpH265Depay, gst_rtp_h265_depay,
99     GST_TYPE_RTP_BASE_DEPAYLOAD);
100
101 static void gst_rtp_h265_depay_finalize (GObject * object);
102
103 static GstStateChangeReturn gst_rtp_h265_depay_change_state (GstElement *
104     element, GstStateChange transition);
105
106 static GstBuffer *gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload,
107     GstRTPBuffer * rtp);
108 static gboolean gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * filter,
109     GstCaps * caps);
110 static gboolean gst_rtp_h265_depay_handle_event (GstRTPBaseDepayload * depay,
111     GstEvent * event);
112
113 static void
114 gst_rtp_h265_depay_class_init (GstRtpH265DepayClass * klass)
115 {
116   GObjectClass *gobject_class;
117   GstElementClass *gstelement_class;
118   GstRTPBaseDepayloadClass *gstrtpbasedepayload_class;
119
120   gobject_class = (GObjectClass *) klass;
121   gstelement_class = (GstElementClass *) klass;
122   gstrtpbasedepayload_class = (GstRTPBaseDepayloadClass *) klass;
123
124   gobject_class->finalize = gst_rtp_h265_depay_finalize;
125
126   gst_element_class_add_pad_template (gstelement_class,
127       gst_static_pad_template_get (&gst_rtp_h265_depay_src_template));
128   gst_element_class_add_pad_template (gstelement_class,
129       gst_static_pad_template_get (&gst_rtp_h265_depay_sink_template));
130
131   gst_element_class_set_static_metadata (gstelement_class,
132       "RTP H265 depayloader", "Codec/Depayloader/Network/RTP",
133       "Extracts H265 video from RTP packets (draft-ietf-payload-rtp-h265-03.txt)",
134       "Jurgen Slowack <jurgenslowack@gmail.com>");
135   gstelement_class->change_state = gst_rtp_h265_depay_change_state;
136
137   gstrtpbasedepayload_class->process_rtp_packet = gst_rtp_h265_depay_process;
138   gstrtpbasedepayload_class->set_caps = gst_rtp_h265_depay_setcaps;
139   gstrtpbasedepayload_class->handle_event = gst_rtp_h265_depay_handle_event;
140 }
141
142 static void
143 gst_rtp_h265_depay_init (GstRtpH265Depay * rtph265depay)
144 {
145   rtph265depay->adapter = gst_adapter_new ();
146   rtph265depay->picture_adapter = gst_adapter_new ();
147   rtph265depay->byte_stream = DEFAULT_BYTE_STREAM;
148   rtph265depay->stream_format = (gchar *) g_malloc (10);
149   rtph265depay->merge = DEFAULT_ACCESS_UNIT;
150   rtph265depay->vps = g_ptr_array_new_with_free_func (
151       (GDestroyNotify) gst_buffer_unref);
152   rtph265depay->sps = g_ptr_array_new_with_free_func (
153       (GDestroyNotify) gst_buffer_unref);
154   rtph265depay->pps = g_ptr_array_new_with_free_func (
155       (GDestroyNotify) gst_buffer_unref);
156 }
157
158 static void
159 gst_rtp_h265_depay_reset (GstRtpH265Depay * rtph265depay)
160 {
161   gst_adapter_clear (rtph265depay->adapter);
162   rtph265depay->wait_start = TRUE;
163   gst_adapter_clear (rtph265depay->picture_adapter);
164   rtph265depay->picture_start = FALSE;
165   rtph265depay->last_keyframe = FALSE;
166   rtph265depay->last_ts = 0;
167   rtph265depay->current_fu_type = 0;
168   rtph265depay->new_codec_data = FALSE;
169   g_ptr_array_set_size (rtph265depay->vps, 0);
170   g_ptr_array_set_size (rtph265depay->sps, 0);
171   g_ptr_array_set_size (rtph265depay->pps, 0);
172 }
173
174 static void
175 gst_rtp_h265_depay_finalize (GObject * object)
176 {
177   GstRtpH265Depay *rtph265depay;
178
179   rtph265depay = GST_RTP_H265_DEPAY (object);
180
181   if (rtph265depay->codec_data)
182     gst_buffer_unref (rtph265depay->codec_data);
183
184   g_free (rtph265depay->stream_format);
185
186   g_object_unref (rtph265depay->adapter);
187   g_object_unref (rtph265depay->picture_adapter);
188
189   g_ptr_array_free (rtph265depay->vps, TRUE);
190   g_ptr_array_free (rtph265depay->sps, TRUE);
191   g_ptr_array_free (rtph265depay->pps, TRUE);
192
193   G_OBJECT_CLASS (parent_class)->finalize (object);
194 }
195
196 static void
197 gst_rtp_h265_depay_negotiate (GstRtpH265Depay * rtph265depay)
198 {
199   GstCaps *caps;
200   gint byte_stream = -1;
201   gint merge = -1;
202
203   caps =
204       gst_pad_get_allowed_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay));
205
206   GST_DEBUG_OBJECT (rtph265depay, "allowed caps: %" GST_PTR_FORMAT, caps);
207
208   if (caps) {
209     if (gst_caps_get_size (caps) > 0) {
210       GstStructure *s = gst_caps_get_structure (caps, 0);
211       const gchar *str = NULL;
212
213       if ((str = gst_structure_get_string (s, "stream-format"))) {
214
215         strcpy (rtph265depay->stream_format, str);
216
217         if (strcmp (str, "hev1") == 0) {
218           byte_stream = FALSE;
219         } else if (strcmp (str, "hvc1") == 0) {
220           byte_stream = FALSE;
221         } else if (strcmp (str, "byte-stream") == 0) {
222           byte_stream = TRUE;
223         } else {
224           GST_DEBUG_OBJECT (rtph265depay, "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 (rtph265depay, "unknown alignment: %s", str);
235         }
236       }
237     }
238     gst_caps_unref (caps);
239   }
240
241   if (byte_stream != -1) {
242     GST_DEBUG_OBJECT (rtph265depay, "downstream requires byte-stream %d",
243         byte_stream);
244     rtph265depay->byte_stream = byte_stream;
245   } else {
246     GST_DEBUG_OBJECT (rtph265depay, "defaulting to byte-stream %d",
247         DEFAULT_BYTE_STREAM);
248     strcpy (rtph265depay->stream_format, "byte-stream");
249     rtph265depay->byte_stream = DEFAULT_BYTE_STREAM;
250   }
251   if (merge != -1) {
252     GST_DEBUG_OBJECT (rtph265depay, "downstream requires merge %d", merge);
253     rtph265depay->merge = merge;
254   } else {
255     GST_DEBUG_OBJECT (rtph265depay, "defaulting to merge %d",
256         DEFAULT_ACCESS_UNIT);
257     rtph265depay->merge = DEFAULT_ACCESS_UNIT;
258   }
259 }
260
261 /* Stolen from bad/gst/mpegtsdemux/payloader_parsers.c */
262 /* variable length Exp-Golomb parsing according to H.265 spec section 9.2*/
263 static gboolean
264 read_golomb (GstBitReader * br, guint32 * value)
265 {
266   guint8 b, leading_zeros = -1;
267   *value = 1;
268
269   for (b = 0; !b; leading_zeros++) {
270     if (!gst_bit_reader_get_bits_uint8 (br, &b, 1))
271       return FALSE;
272     *value *= 2;
273   }
274
275   *value = (*value >> 1) - 1;
276   if (leading_zeros > 0) {
277     guint32 tmp = 0;
278     if (!gst_bit_reader_get_bits_uint32 (br, &tmp, leading_zeros))
279       return FALSE;
280     *value += tmp;
281   }
282
283   return TRUE;
284 }
285
286 static gboolean
287 parse_sps (GstMapInfo * map, guint32 * sps_id)
288 {                               /* To parse seq_parameter_set_id */
289   GstBitReader br = GST_BIT_READER_INIT (map->data + 15,
290       map->size - 15);
291
292   if (map->size < 16)
293     return FALSE;
294
295   if (!read_golomb (&br, sps_id))
296     return FALSE;
297
298   return TRUE;
299 }
300
301 static gboolean
302 parse_pps (GstMapInfo * map, guint32 * sps_id, guint32 * pps_id)
303 {                               /* To parse picture_parameter_set_id */
304   GstBitReader br = GST_BIT_READER_INIT (map->data + 2,
305       map->size - 2);
306
307   if (map->size < 3)
308     return FALSE;
309
310   if (!read_golomb (&br, pps_id))
311     return FALSE;
312   if (!read_golomb (&br, sps_id))
313     return FALSE;
314
315   return TRUE;
316 }
317
318
319 static gboolean
320 gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
321 {
322   gboolean res;
323   GstCaps *srccaps;
324
325   if (!rtph265depay->byte_stream &&
326       (!rtph265depay->new_codec_data ||
327           rtph265depay->vps->len == 0 || rtph265depay->sps->len == 0
328           || rtph265depay->pps->len == 0))
329     return TRUE;
330
331   srccaps = gst_caps_new_simple ("video/x-h265",
332       "stream-format", G_TYPE_STRING,
333       rtph265depay->stream_format,
334       "alignment", G_TYPE_STRING, rtph265depay->merge ? "au" : "nal", NULL);
335
336   if (!rtph265depay->byte_stream) {
337
338     GstBuffer *codec_data;
339     gint i = 0;
340     gint len;
341     guint num_vps = rtph265depay->vps->len;
342     guint num_sps = rtph265depay->sps->len;
343     guint num_pps = rtph265depay->pps->len;
344     GstMapInfo map, nalmap;
345     guint8 *data;
346     gint nl;
347     guint8 num_arrays = 0;
348     guint new_size;
349     GstBitReader br;
350     guint32 tmp;
351     guint8 tmp8 = 0;
352     guint32 max_sub_layers_minus1, temporal_id_nesting_flag, chroma_format_idc,
353         bit_depth_luma_minus8, bit_depth_chroma_minus8,
354         min_spatial_segmentation_idc;
355
356     /* Fixme: Current implementation is not embedding SEI in codec_data */
357
358     if (num_sps == 0)
359       return FALSE;
360
361     /* start with 23 bytes header */
362     len = 23;
363
364     num_arrays = (num_vps > 0) + (num_sps > 0) + (num_pps > 0);
365     len += num_arrays;
366
367     /* add size of vps, sps & pps */
368     for (i = 0; i < num_vps; i++)
369       len += 2 + gst_buffer_get_size (g_ptr_array_index (rtph265depay->vps, i));
370     for (i = 0; i < num_sps; i++)
371       len += 2 + gst_buffer_get_size (g_ptr_array_index (rtph265depay->sps, i));
372     for (i = 0; i < num_pps; i++)
373       len += 2 + gst_buffer_get_size (g_ptr_array_index (rtph265depay->pps, i));
374
375     GST_DEBUG_OBJECT (rtph265depay,
376         "constructing codec_data: num_vps =%d num_sps=%d, num_pps=%d", num_vps,
377         num_sps, num_pps);
378
379     codec_data = gst_buffer_new_and_alloc (len);
380     g_debug ("alloc_len: %u", len);
381     gst_buffer_map (codec_data, &map, GST_MAP_READWRITE);
382     data = map.data;
383
384     memset (data, 0, map.size);
385
386     /* Parsing sps to get the info required further on */
387
388     gst_buffer_map (g_ptr_array_index (rtph265depay->sps, 0), &nalmap,
389         GST_MAP_READ);
390
391     max_sub_layers_minus1 = ((nalmap.data[2]) >> 1) & 0x07;
392     temporal_id_nesting_flag = nalmap.data[2] & 0x01;
393
394     gst_bit_reader_init (&br, nalmap.data + 15, nalmap.size - 15);
395
396     read_golomb (&br, &tmp);    /* sps_seq_parameter_set_id */
397     read_golomb (&br, &chroma_format_idc);      /* chroma_format_idc */
398
399     if (chroma_format_idc == 3)
400
401       gst_bit_reader_get_bits_uint8 (&br, &tmp8, 1);    /* separate_colour_plane_flag */
402
403     read_golomb (&br, &tmp);    /* pic_width_in_luma_samples */
404     read_golomb (&br, &tmp);    /* pic_height_in_luma_samples */
405
406     gst_bit_reader_get_bits_uint8 (&br, &tmp8, 1);      /* conformance_window_flag */
407     if (tmp8) {
408       read_golomb (&br, &tmp);  /* conf_win_left_offset */
409       read_golomb (&br, &tmp);  /* conf_win_right_offset */
410       read_golomb (&br, &tmp);  /* conf_win_top_offset */
411       read_golomb (&br, &tmp);  /* conf_win_bottom_offset */
412     }
413
414     read_golomb (&br, &bit_depth_luma_minus8);  /* bit_depth_luma_minus8 */
415     read_golomb (&br, &bit_depth_chroma_minus8);        /* bit_depth_chroma_minus8 */
416
417     GST_DEBUG_OBJECT (rtph265depay,
418         "Ignoring min_spatial_segmentation for now (assuming zero)");
419
420     min_spatial_segmentation_idc = 0;   /* NOTE - we ignore this for now, but in a perfect world, we should continue parsing to obtain the real value */
421
422     nl = nalmap.size;
423
424     gst_buffer_unmap (g_ptr_array_index (rtph265depay->sps, 0), &nalmap);
425
426     /* HEVCDecoderConfigurationVersion = 1 */
427     data[0] = 1;
428
429     /* Copy from profile_tier_level (Rec. ITU-T H.265 (04/2013) section 7.3.3
430      *
431      * profile_space | tier_flat | profile_idc |
432      * profile_compatibility_flags | constraint_indicator_flags |
433      * level_idc | progressive_source_flag | interlaced_source_flag
434      * non_packed_constraint_flag | frame_only_constraint_flag
435      * reserved_zero_44bits | level_idc */
436     gst_buffer_map (g_ptr_array_index (rtph265depay->sps, 0), &nalmap,
437         GST_MAP_READ);
438     for (i = 0; i < 12; i++)
439       data[i + 1] = nalmap.data[i];
440     gst_buffer_unmap (g_ptr_array_index (rtph265depay->sps, 0), &nalmap);
441
442     /* min_spatial_segmentation_idc */
443     GST_WRITE_UINT16_BE (data + 13, min_spatial_segmentation_idc);
444     data[13] |= 0xf0;
445     data[15] = 0xfc;            /* keeping parrallelismType as zero (unknown) */
446     data[16] = 0xfc | chroma_format_idc;
447     data[17] = 0xf8 | bit_depth_luma_minus8;
448     data[18] = 0xf8 | bit_depth_chroma_minus8;
449     data[19] = 0x00;            /* keep avgFrameRate as unspecified */
450     data[20] = 0x00;            /* keep avgFrameRate as unspecified */
451     /* constFrameRate(2 bits): 0, stream may or may not be of constant framerate
452      * numTemporalLayers (3 bits): number of temporal layers, value from SPS
453      * TemporalIdNested (1 bit): sps_temporal_id_nesting_flag from SPS
454      * lengthSizeMinusOne (2 bits): plus 1 indicates the length of the NALUnitLength */
455     data[21] =
456         0x00 | ((max_sub_layers_minus1 +
457             1) << 3) | (temporal_id_nesting_flag << 2) | (nl - 1);
458     GST_WRITE_UINT8 (data + 22, num_arrays);    /* numOfArrays */
459
460     data += 23;
461
462     /* copy all VPS */
463     if (num_vps > 0) {
464       /* array_completeness | reserved_zero bit | nal_unit_type */
465       data[0] = 0x00 | 0x20;
466       data++;
467
468       GST_WRITE_UINT16_BE (data, num_vps);
469       data += 2;
470
471       for (i = 0; i < num_vps; i++) {
472         gsize nal_size =
473             gst_buffer_get_size (g_ptr_array_index (rtph265depay->vps, i));
474         GST_WRITE_UINT16_BE (data, nal_size);
475         gst_buffer_extract (g_ptr_array_index (rtph265depay->vps, i), 0,
476             data + 2, nal_size);
477         data += 2 + nal_size;
478         GST_DEBUG_OBJECT (rtph265depay, "Copied VPS %d of length %u", i,
479             (guint) nal_size);
480       }
481     }
482
483     /* copy all SPS */
484     if (num_sps > 0) {
485       /* array_completeness | reserved_zero bit | nal_unit_type */
486       data[0] = 0x00 | 0x21;
487       data++;
488
489       GST_WRITE_UINT16_BE (data, num_sps);
490       data += 2;
491
492       for (i = 0; i < num_sps; i++) {
493         gsize nal_size =
494             gst_buffer_get_size (g_ptr_array_index (rtph265depay->sps, i));
495         GST_WRITE_UINT16_BE (data, nal_size);
496         gst_buffer_extract (g_ptr_array_index (rtph265depay->sps, i), 0,
497             data + 2, nal_size);
498         data += 2 + nal_size;
499         GST_DEBUG_OBJECT (rtph265depay, "Copied SPS %d of length %u", i,
500             (guint) nal_size);
501       }
502     }
503
504     /* copy all PPS */
505     if (num_pps > 0) {
506       /* array_completeness | reserved_zero bit | nal_unit_type */
507       data[0] = 0x00 | 0x22;
508       data++;
509
510       GST_WRITE_UINT16_BE (data, num_pps);
511       data += 2;
512
513       for (i = 0; i < num_pps; i++) {
514         gsize nal_size =
515             gst_buffer_get_size (g_ptr_array_index (rtph265depay->pps, i));
516         GST_WRITE_UINT16_BE (data, nal_size);
517         gst_buffer_extract (g_ptr_array_index (rtph265depay->pps, i), 0,
518             data + 2, nal_size);
519         data += 2 + nal_size;
520         GST_DEBUG_OBJECT (rtph265depay, "Copied PPS %d of length %u", i,
521             (guint) nal_size);
522       }
523     }
524
525     new_size = data - map.data;
526     gst_buffer_unmap (codec_data, &map);
527     gst_buffer_set_size (codec_data, new_size);
528
529     gst_caps_set_simple (srccaps,
530         "codec_data", GST_TYPE_BUFFER, codec_data, NULL);
531     gst_buffer_unref (codec_data);
532   }
533
534   if (gst_pad_has_current_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay))) {
535     GstCaps *old_caps =
536         gst_pad_get_current_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay));
537
538     /* Only update the caps if they are not equal. For
539      * AVC we don't update caps if only the codec_data
540      * changes. This is the same behaviour as in h264parse
541      * and gstrtph264depay
542      */
543     if (rtph265depay->byte_stream) {
544       if (!gst_caps_is_equal (srccaps, old_caps))
545         res =
546             gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
547             srccaps);
548       else
549         res = TRUE;
550     } else {
551       GstCaps *tmp_caps = gst_caps_copy (srccaps);
552       GstStructure *old_s, *tmp_s;
553
554       old_s = gst_caps_get_structure (old_caps, 0);
555       tmp_s = gst_caps_get_structure (tmp_caps, 0);
556       if (gst_structure_has_field (old_s, "codec_data"))
557         gst_structure_set_value (tmp_s, "codec_data",
558             gst_structure_get_value (old_s, "codec_data"));
559
560       if (!gst_caps_is_equal (old_caps, tmp_caps))
561         res =
562             gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
563             srccaps);
564       else
565         res = TRUE;
566
567       gst_caps_unref (tmp_caps);
568     }
569   } else {
570     res =
571         gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
572         srccaps);
573   }
574
575   gst_caps_unref (srccaps);
576
577   /* Insert SPS and PPS into the stream on next opportunity */
578   if (rtph265depay->sps->len > 0 || rtph265depay->pps->len > 0) {
579     gint i;
580     GstBuffer *codec_data;
581     GstMapInfo map;
582     guint8 *data;
583     guint len = 0;
584
585     for (i = 0; i < rtph265depay->sps->len; i++) {
586       len += 4 + gst_buffer_get_size (g_ptr_array_index (rtph265depay->sps, i));
587     }
588
589     for (i = 0; i < rtph265depay->pps->len; i++) {
590       len += 4 + gst_buffer_get_size (g_ptr_array_index (rtph265depay->pps, i));
591     }
592
593     codec_data = gst_buffer_new_and_alloc (len);
594     gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
595     data = map.data;
596
597     for (i = 0; i < rtph265depay->sps->len; i++) {
598       GstBuffer *sps_buf = g_ptr_array_index (rtph265depay->sps, i);
599       guint sps_size = gst_buffer_get_size (sps_buf);
600
601       if (rtph265depay->byte_stream)
602         memcpy (data, sync_bytes, sizeof (sync_bytes));
603       else
604         GST_WRITE_UINT32_BE (data, sps_size);
605       gst_buffer_extract (sps_buf, 0, data + 4, -1);
606       data += 4 + sps_size;
607     }
608
609     for (i = 0; i < rtph265depay->pps->len; i++) {
610       GstBuffer *pps_buf = g_ptr_array_index (rtph265depay->pps, i);
611       guint pps_size = gst_buffer_get_size (pps_buf);
612
613       if (rtph265depay->byte_stream)
614         memcpy (data, sync_bytes, sizeof (sync_bytes));
615       else
616         GST_WRITE_UINT32_BE (data, pps_size);
617       gst_buffer_extract (pps_buf, 0, data + 4, -1);
618       data += 4 + pps_size;
619     }
620
621     gst_buffer_unmap (codec_data, &map);
622     if (rtph265depay->codec_data)
623       gst_buffer_unref (rtph265depay->codec_data);
624     rtph265depay->codec_data = codec_data;
625   }
626
627   if (res)
628     rtph265depay->new_codec_data = FALSE;
629
630   return res;
631 }
632
633 gboolean
634 gst_rtp_h265_add_vps_sps_pps (GstElement * rtph265, GPtrArray * vps_array,
635     GPtrArray * sps_array, GPtrArray * pps_array, GstBuffer * nal)
636 {
637   GstMapInfo map;
638   guchar type;
639   guint i;
640
641   gst_buffer_map (nal, &map, GST_MAP_READ);
642
643   type = (map.data[0] >> 1) & 0x3f;
644
645   if (type == GST_H265_VPS_NUT) {
646     guint32 vps_id = (map.data[2] >> 4) & 0x0f;
647
648     for (i = 0; i < vps_array->len; i++) {
649       GstBuffer *vps = g_ptr_array_index (vps_array, i);
650       GstMapInfo vpsmap;
651       guint32 tmp_vps_id;
652
653       gst_buffer_map (vps, &vpsmap, GST_MAP_READ);
654       tmp_vps_id = (vpsmap.data[2] >> 4) & 0x0f;
655
656       if (vps_id == tmp_vps_id) {
657         if (map.size == vpsmap.size &&
658             memcmp (map.data, vpsmap.data, vpsmap.size) == 0) {
659           GST_LOG_OBJECT (rtph265, "Unchanged VPS %u, not updating", vps_id);
660           gst_buffer_unmap (vps, &vpsmap);
661           goto drop;
662         } else {
663           gst_buffer_unmap (vps, &vpsmap);
664           g_ptr_array_remove_index_fast (vps_array, i);
665           g_ptr_array_add (vps_array, nal);
666           GST_LOG_OBJECT (rtph265, "Modified VPS %u, replacing", vps_id);
667           goto done;
668         }
669       }
670       gst_buffer_unmap (vps, &vpsmap);
671     }
672     GST_LOG_OBJECT (rtph265, "Adding new VPS %u", vps_id);
673     g_ptr_array_add (vps_array, nal);
674   } else if (type == GST_H265_SPS_NUT) {
675     guint32 sps_id;
676
677     if (!parse_sps (&map, &sps_id)) {
678       GST_WARNING_OBJECT (rtph265, "Invalid SPS,"
679           " can't parse seq_parameter_set_id");
680       goto drop;
681     }
682
683     for (i = 0; i < sps_array->len; i++) {
684       GstBuffer *sps = g_ptr_array_index (sps_array, i);
685       GstMapInfo spsmap;
686       guint32 tmp_sps_id;
687
688       gst_buffer_map (sps, &spsmap, GST_MAP_READ);
689       parse_sps (&spsmap, &tmp_sps_id);
690
691       if (sps_id == tmp_sps_id) {
692         if (map.size == spsmap.size &&
693             memcmp (map.data, spsmap.data, spsmap.size) == 0) {
694           GST_LOG_OBJECT (rtph265, "Unchanged SPS %u, not updating", sps_id);
695           gst_buffer_unmap (sps, &spsmap);
696           goto drop;
697         } else {
698           gst_buffer_unmap (sps, &spsmap);
699           g_ptr_array_remove_index_fast (sps_array, i);
700           g_ptr_array_add (sps_array, nal);
701           GST_LOG_OBJECT (rtph265, "Modified SPS %u, replacing", sps_id);
702           goto done;
703         }
704       }
705       gst_buffer_unmap (sps, &spsmap);
706     }
707     GST_LOG_OBJECT (rtph265, "Adding new SPS %u", sps_id);
708     g_ptr_array_add (sps_array, nal);
709   } else if (type == GST_H265_PPS_NUT) {
710     guint32 sps_id;
711     guint32 pps_id;
712
713     if (!parse_pps (&map, &sps_id, &pps_id)) {
714       GST_WARNING_OBJECT (rtph265, "Invalid PPS,"
715           " can't parse seq_parameter_set_id or pic_parameter_set_id");
716       goto drop;
717     }
718
719     for (i = 0; i < pps_array->len; i++) {
720       GstBuffer *pps = g_ptr_array_index (pps_array, i);
721       GstMapInfo ppsmap;
722       guint32 tmp_sps_id;
723       guint32 tmp_pps_id;
724
725
726       gst_buffer_map (pps, &ppsmap, GST_MAP_READ);
727       parse_pps (&ppsmap, &tmp_sps_id, &tmp_pps_id);
728
729       if (pps_id == tmp_pps_id) {
730         if (map.size == ppsmap.size &&
731             memcmp (map.data, ppsmap.data, ppsmap.size) == 0) {
732           GST_LOG_OBJECT (rtph265, "Unchanged PPS %u:%u, not updating", sps_id,
733               pps_id);
734           gst_buffer_unmap (pps, &ppsmap);
735           goto drop;
736         } else {
737           gst_buffer_unmap (pps, &ppsmap);
738           g_ptr_array_remove_index_fast (pps_array, i);
739           g_ptr_array_add (pps_array, nal);
740           GST_LOG_OBJECT (rtph265, "Modified PPS %u:%u, replacing",
741               sps_id, pps_id);
742           goto done;
743         }
744       }
745       gst_buffer_unmap (pps, &ppsmap);
746     }
747     GST_LOG_OBJECT (rtph265, "Adding new PPS %u:%i", sps_id, pps_id);
748     g_ptr_array_add (pps_array, nal);
749   } else {
750     goto drop;
751   }
752
753 done:
754   gst_buffer_unmap (nal, &map);
755
756   return TRUE;
757
758 drop:
759   gst_buffer_unmap (nal, &map);
760   gst_buffer_unref (nal);
761
762   return FALSE;
763 }
764
765
766 static void
767 gst_rtp_h265_depay_add_vps_sps_pps (GstRtpH265Depay * rtph265depay,
768     GstBuffer * nal)
769 {
770   if (gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265depay),
771           rtph265depay->vps, rtph265depay->sps, rtph265depay->pps, nal))
772     rtph265depay->new_codec_data = TRUE;
773 }
774
775 static gboolean
776 gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
777 {
778   gint clock_rate;
779   GstStructure *structure = gst_caps_get_structure (caps, 0);
780   GstRtpH265Depay *rtph265depay;
781   const gchar *ps;
782   GstBuffer *codec_data;
783   GstMapInfo map;
784   guint8 *ptr;
785
786   rtph265depay = GST_RTP_H265_DEPAY (depayload);
787
788   if (!gst_structure_get_int (structure, "clock-rate", &clock_rate))
789     clock_rate = 90000;
790   depayload->clock_rate = clock_rate;
791
792   /* Base64 encoded, comma separated config NALs */
793   ps = gst_structure_get_string (structure, "sprop-parameter-sets");
794
795   /* negotiate with downstream w.r.t. output format and alignment */
796   gst_rtp_h265_depay_negotiate (rtph265depay);
797
798   if (rtph265depay->byte_stream && ps != NULL) {
799     /* for bytestream we only need the parameter sets but we don't error out
800      * when they are not there, we assume they are in the stream. */
801     gchar **params;
802     guint len, total;
803     gint i;
804
805     params = g_strsplit (ps, ",", 0);
806
807     /* count total number of bytes in base64. Also include the sync bytes in
808      * front of the params. */
809     len = 0;
810     for (i = 0; params[i]; i++) {
811       len += strlen (params[i]);
812       len += sizeof (sync_bytes);
813     }
814     /* we seriously overshoot the length, but it's fine. */
815     codec_data = gst_buffer_new_and_alloc (len);
816
817     gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
818     ptr = map.data;
819     total = 0;
820     for (i = 0; params[i]; i++) {
821       guint save = 0;
822       gint state = 0;
823
824       GST_DEBUG_OBJECT (depayload, "decoding param %d (%s)", i, params[i]);
825       memcpy (ptr, sync_bytes, sizeof (sync_bytes));
826       ptr += sizeof (sync_bytes);
827       len =
828           g_base64_decode_step (params[i], strlen (params[i]), ptr, &state,
829           &save);
830       GST_DEBUG_OBJECT (depayload, "decoded %d bytes", len);
831       total += len + sizeof (sync_bytes);
832       ptr += len;
833     }
834     gst_buffer_unmap (codec_data, &map);
835     gst_buffer_resize (codec_data, 0, total);
836     g_strfreev (params);
837
838     /* keep the codec_data, we need to send it as the first buffer. We cannot
839      * push it in the adapter because the adapter might be flushed on discont.
840      */
841     if (rtph265depay->codec_data)
842       gst_buffer_unref (rtph265depay->codec_data);
843     rtph265depay->codec_data = codec_data;
844   } else if (!rtph265depay->byte_stream) {
845     gchar **params;
846     gint i;
847
848     if (ps == NULL)
849       goto incomplete_caps;
850
851     params = g_strsplit (ps, ",", 0);
852
853     GST_DEBUG_OBJECT (depayload, "we have %d params", g_strv_length (params));
854
855     /* start with 23 bytes header */
856     for (i = 0; params[i]; i++) {
857       GstBuffer *nal;
858       GstMapInfo nalmap;
859       gsize nal_len;
860       guint save = 0;
861       gint state = 0;
862
863       nal_len = strlen (params[i]);
864       nal = gst_buffer_new_and_alloc (nal_len);
865       gst_buffer_map (nal, &nalmap, GST_MAP_READWRITE);
866
867       nal_len =
868           g_base64_decode_step (params[i], nal_len, nalmap.data, &state, &save);
869
870       GST_DEBUG_OBJECT (depayload, "adding param %d as %s", i,
871           (((nalmap.data[0] >> 1) & 0x3f) ==
872               32) ? "VPS" : (((nalmap.data[0] >> 1) & 0x3f) ==
873               33) ? "SPS" : "PPS");
874
875       gst_buffer_unmap (nal, &nalmap);
876       gst_buffer_set_size (nal, nal_len);
877
878       gst_rtp_h265_depay_add_vps_sps_pps (rtph265depay, nal);
879     }
880     g_strfreev (params);
881
882     if (rtph265depay->sps->len == 0 || rtph265depay->pps->len == 0)
883       goto incomplete_caps;
884   }
885
886   return gst_rtp_h265_set_src_caps (rtph265depay);
887
888   /* ERRORS */
889 incomplete_caps:
890   {
891     GST_DEBUG_OBJECT (depayload, "we have incomplete caps,"
892         " doing setcaps later");
893     return TRUE;
894   }
895 }
896
897 static GstBuffer *
898 gst_rtp_h265_complete_au (GstRtpH265Depay * rtph265depay,
899     GstClockTime * out_timestamp, gboolean * out_keyframe)
900 {
901   guint outsize;
902   GstBuffer *outbuf;
903
904   /* we had a picture in the adapter and we completed it */
905   GST_DEBUG_OBJECT (rtph265depay, "taking completed AU");
906   outsize = gst_adapter_available (rtph265depay->picture_adapter);
907   outbuf = gst_adapter_take_buffer (rtph265depay->picture_adapter, outsize);
908
909   *out_timestamp = rtph265depay->last_ts;
910   *out_keyframe = rtph265depay->last_keyframe;
911
912   rtph265depay->last_keyframe = FALSE;
913   rtph265depay->picture_start = FALSE;
914
915   return outbuf;
916 }
917
918 /* VPS/SPS/PPS/RADL/TSA/RASL/IDR/CRA is considered key, all others DELTA;
919  * so downstream waiting for keyframe can pick up at VPS/SPS/PPS/IDR */
920
921 #define NAL_TYPE_IS_PARAMETER_SET(nt) (         ((nt) == GST_H265_VPS_NUT)\
922                                                                                 ||  ((nt) == GST_H265_SPS_NUT)\
923                                                                                 ||  ((nt) == GST_H265_PPS_NUT)                          )
924
925 #define NAL_TYPE_IS_CODED_SLICE_SEGMENT(nt) (           ((nt) == GST_H265_NAL_SLICE_TRAIL_N)\
926                                                                                                 ||      ((nt) == GST_H265_NAL_SLICE_TRAIL_R)\
927                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_TSA_N)\
928                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_TSA_R)\
929                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_STSA_N)\
930                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_STSA_R)\
931                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_RASL_N)\
932                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_RASL_R)\
933                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_BLA_W_LP)\
934                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_BLA_W_RADL)\
935                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_BLA_N_LP)\
936                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_IDR_W_RADL)\
937                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_IDR_N_LP)\
938                                                                                                 ||  ((nt) == GST_H265_NAL_SLICE_CRA_NUT)                )
939
940 #define NAL_TYPE_IS_KEY(nt) (NAL_TYPE_IS_PARAMETER_SET(nt) || NAL_TYPE_IS_CODED_SLICE_SEGMENT(nt))
941
942 static gboolean
943 foreach_metadata_copy (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
944 {
945   CopyMetaData *data = user_data;
946   GstElement *element = data->element;
947   GstBuffer *outbuf = data->outbuf;
948   const GstMetaInfo *info = (*meta)->info;
949   const gchar *const *tags = gst_meta_api_type_get_tags (info->api);
950
951   if (!tags || (g_strv_length ((gchar **) tags) == 1
952           && gst_meta_api_type_has_tag (info->api,
953               g_quark_from_string (GST_META_TAG_VIDEO_STR)))) {
954     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
955     GST_DEBUG_OBJECT (element, "copy metadata %s", g_type_name (info->api));
956     /* simply copy then */
957     info->transform_func (outbuf, *meta, inbuf,
958         _gst_meta_transform_copy, &copy_data);
959   } else {
960     GST_DEBUG_OBJECT (element, "not copying metadata %s",
961         g_type_name (info->api));
962   }
963
964   return TRUE;
965 }
966
967 /* TODO: Should probably make copy_tag an array at some point */
968 void
969 gst_rtp_copy_meta (GstElement * element, GstBuffer * outbuf, GstBuffer * inbuf,
970     GQuark copy_tag)
971 {
972   CopyMetaData data = { element, outbuf, copy_tag };
973
974   gst_buffer_foreach_meta (inbuf, foreach_metadata_copy, &data);
975 }
976
977 static gboolean
978 foreach_metadata_drop (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
979 {
980   GstRtpH265Depay *depay = user_data;
981   const GstMetaInfo *info = (*meta)->info;
982   const gchar *const *tags = gst_meta_api_type_get_tags (info->api);
983
984   if (!tags || (g_strv_length ((gchar **) tags) == 1
985           && gst_meta_api_type_has_tag (info->api,
986               g_quark_from_string (GST_META_TAG_VIDEO_STR)))) {
987     GST_DEBUG_OBJECT (depay, "keeping metadata %s", g_type_name (info->api));
988   } else {
989     GST_DEBUG_OBJECT (depay, "dropping metadata %s", g_type_name (info->api));
990     *meta = NULL;
991   }
992
993   return TRUE;
994 }
995
996 static GstBuffer *
997 gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
998     GstClockTime in_timestamp, gboolean marker)
999 {
1000   GstRTPBaseDepayload *depayload = GST_RTP_BASE_DEPAYLOAD (rtph265depay);
1001   gint nal_type;
1002   GstMapInfo map;
1003   GstBuffer *outbuf = NULL;
1004   GstClockTime out_timestamp;
1005   gboolean keyframe, out_keyframe;
1006
1007   gst_buffer_map (nal, &map, GST_MAP_READ);
1008   if (G_UNLIKELY (map.size < 5))
1009     goto short_nal;
1010
1011   nal_type = (map.data[4] >> 1) & 0x3f;
1012   GST_DEBUG_OBJECT (rtph265depay, "handle NAL type %d (RTP marker bit %d)",
1013       nal_type, marker);
1014
1015   keyframe = NAL_TYPE_IS_KEY (nal_type);
1016
1017   out_keyframe = keyframe;
1018   out_timestamp = in_timestamp;
1019
1020   if (!rtph265depay->byte_stream) {
1021     if (NAL_TYPE_IS_PARAMETER_SET (nal_type)) {
1022       gst_rtp_h265_depay_add_vps_sps_pps (rtph265depay,
1023           gst_buffer_copy_region (nal, GST_BUFFER_COPY_ALL,
1024               4, gst_buffer_get_size (nal) - 4));
1025       gst_buffer_unmap (nal, &map);
1026       gst_buffer_unref (nal);
1027       return NULL;
1028     } else if (rtph265depay->sps->len == 0 || rtph265depay->pps->len == 0) {
1029       /* Down push down any buffer in non-bytestream mode if the SPS/PPS haven't
1030        * go through yet
1031        */
1032       gst_pad_push_event (GST_RTP_BASE_DEPAYLOAD_SINKPAD (depayload),
1033           gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
1034               gst_structure_new ("GstForceKeyUnit",
1035                   "all-headers", G_TYPE_BOOLEAN, TRUE, NULL)));
1036       gst_buffer_unmap (nal, &map);
1037       gst_buffer_unref (nal);
1038       return NULL;
1039     }
1040
1041     if (rtph265depay->new_codec_data &&
1042         rtph265depay->sps->len > 0 && rtph265depay->pps->len > 0)
1043       gst_rtp_h265_set_src_caps (rtph265depay);
1044   }
1045
1046   if (rtph265depay->merge) {
1047     gboolean start = FALSE, complete = FALSE;
1048
1049     /* marker bit isn't mandatory so in the following code we try to detect
1050      * an AU boundary (see H.265 spec section 7.4.2.4.4) */
1051     if (!marker) {
1052
1053       if (NAL_TYPE_IS_CODED_SLICE_SEGMENT (nal_type)) {
1054         /* A NAL unit (X) ends an access unit if the next-occurring VCL NAL unit (Y) has the high-order bit of the first byte after its NAL unit header equal to 1 */
1055         start = TRUE;
1056         if (((map.data[6] >> 7) & 0x01) == 1) {
1057           complete = TRUE;
1058         }
1059         complete = TRUE;
1060       } else if ((nal_type >= 32 && nal_type <= 35)
1061           || nal_type == 39 || (nal_type >= 41 && nal_type <= 44)
1062           || (nal_type >= 48 && nal_type <= 55)) {
1063         /* VPS, SPS, PPS, SEI, ... terminate an access unit */
1064         complete = TRUE;
1065       }
1066       GST_DEBUG_OBJECT (depayload, "start %d, complete %d", start, complete);
1067
1068       if (complete && rtph265depay->picture_start)
1069         outbuf = gst_rtp_h265_complete_au (rtph265depay, &out_timestamp,
1070             &out_keyframe);
1071     }
1072     /* add to adapter */
1073     gst_buffer_unmap (nal, &map);
1074
1075     GST_DEBUG_OBJECT (depayload, "adding NAL to picture adapter");
1076     gst_adapter_push (rtph265depay->picture_adapter, nal);
1077     rtph265depay->last_ts = in_timestamp;
1078     rtph265depay->last_keyframe |= keyframe;
1079     rtph265depay->picture_start |= start;
1080
1081     if (marker)
1082       outbuf = gst_rtp_h265_complete_au (rtph265depay, &out_timestamp,
1083           &out_keyframe);
1084   } else {
1085     /* no merge, output is input nal */
1086     GST_DEBUG_OBJECT (depayload, "using NAL as output");
1087     outbuf = nal;
1088     gst_buffer_unmap (nal, &map);
1089   }
1090
1091   if (outbuf) {
1092     /* prepend codec_data */
1093     if (rtph265depay->codec_data) {
1094       GST_DEBUG_OBJECT (depayload, "prepending codec_data");
1095       gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay),
1096           rtph265depay->codec_data, outbuf,
1097           g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1098       outbuf = gst_buffer_append (rtph265depay->codec_data, outbuf);
1099       rtph265depay->codec_data = NULL;
1100       out_keyframe = TRUE;
1101     }
1102     outbuf = gst_buffer_make_writable (outbuf);
1103
1104     gst_buffer_foreach_meta (outbuf, foreach_metadata_drop, depayload);
1105
1106     GST_BUFFER_PTS (outbuf) = out_timestamp;
1107
1108     if (out_keyframe)
1109       GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1110     else
1111       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
1112   }
1113
1114   return outbuf;
1115
1116   /* ERRORS */
1117 short_nal:
1118   {
1119     GST_WARNING_OBJECT (depayload, "dropping short NAL");
1120     gst_buffer_unmap (nal, &map);
1121     gst_buffer_unref (nal);
1122     return NULL;
1123   }
1124 }
1125
1126 static GstBuffer *
1127 gst_rtp_h265_push_fragmentation_unit (GstRtpH265Depay * rtph265depay,
1128     gboolean send)
1129 {
1130   guint outsize;
1131   GstMapInfo map;
1132   GstBuffer *outbuf;
1133
1134   outsize = gst_adapter_available (rtph265depay->adapter);
1135   outbuf = gst_adapter_take_buffer (rtph265depay->adapter, outsize);
1136
1137   gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1138   GST_DEBUG_OBJECT (rtph265depay, "output %d bytes", outsize);
1139
1140   if (rtph265depay->byte_stream) {
1141     memcpy (map.data, sync_bytes, sizeof (sync_bytes));
1142   } else {
1143     goto not_implemented;
1144   }
1145   gst_buffer_unmap (outbuf, &map);
1146
1147   rtph265depay->current_fu_type = 0;
1148
1149   outbuf = gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf,
1150       rtph265depay->fu_timestamp, rtph265depay->fu_marker);
1151
1152   if (send && outbuf) {
1153     gst_rtp_base_depayload_push (GST_RTP_BASE_DEPAYLOAD (rtph265depay), outbuf);
1154     outbuf = NULL;
1155   }
1156   return outbuf;
1157
1158 not_implemented:
1159   {
1160     GST_ERROR_OBJECT (rtph265depay,
1161         ("Only bytestream format is currently supported."));
1162     gst_buffer_unmap (outbuf, &map);
1163     return NULL;
1164   }
1165 }
1166
1167 static GstBuffer *
1168 gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
1169 {
1170   GstRtpH265Depay *rtph265depay;
1171   GstBuffer *buf;
1172   GstBuffer *outbuf = NULL;
1173   guint8 nal_unit_type;
1174
1175   rtph265depay = GST_RTP_H265_DEPAY (depayload);
1176
1177   /* flush remaining data on discont */
1178   if (GST_BUFFER_IS_DISCONT (rtp->buffer)) {
1179     gst_adapter_clear (rtph265depay->adapter);
1180     rtph265depay->wait_start = TRUE;
1181     rtph265depay->current_fu_type = 0;
1182   }
1183
1184   {
1185     gint payload_len;
1186     guint8 *payload;
1187     guint header_len;
1188     GstMapInfo map;
1189     guint outsize, nalu_size;
1190     GstClockTime timestamp;
1191     gboolean marker;
1192     guint8 nuh_layer_id, nuh_temporal_id_plus1;
1193     guint8 S, E;
1194     guint16 nal_header;
1195 #if 0
1196     gboolean donl_present = FALSE;
1197 #endif
1198
1199     timestamp = GST_BUFFER_PTS (rtp->buffer);
1200
1201     payload_len = gst_rtp_buffer_get_payload_len (rtp);
1202     payload = gst_rtp_buffer_get_payload (rtp);
1203     buf = gst_rtp_buffer_get_payload_buffer (rtp);
1204     marker = gst_rtp_buffer_get_marker (rtp);
1205
1206     GST_DEBUG_OBJECT (rtph265depay, "receiving %d bytes", payload_len);
1207
1208     if (payload_len == 0)
1209       goto empty_packet;
1210
1211     /* +---------------+---------------+
1212      * |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|
1213      * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1214      * |F|   Type    |  LayerId  | TID |
1215      * +-------------+-----------------+
1216      *
1217      * F must be 0.
1218      *
1219      */
1220     nal_unit_type = (payload[0] >> 1) & 0x3f;
1221     nuh_layer_id = ((payload[0] & 0x01) << 5) | (payload[1] >> 3);      /* should be zero for now but this could change in future HEVC extensions */
1222     nuh_temporal_id_plus1 = payload[1] & 0x03;
1223
1224     /* At least two byte header with type */
1225     header_len = 2;
1226
1227     GST_DEBUG_OBJECT (rtph265depay,
1228         "NAL header nal_unit_type %d, nuh_temporal_id_plus1 %d", nal_unit_type,
1229         nuh_temporal_id_plus1);
1230
1231     GST_FIXME_OBJECT (rtph265depay, "Assuming DONL field is not present");
1232
1233     /* FIXME - assuming DONL field is not present for now */
1234     /*donl_present = (tx-mode == "MST") || (sprop-max-don-diff > 0); */
1235
1236     /* If FU unit was being processed, but the current nal is of a different
1237      * type.  Assume that the remote payloader is buggy (didn't set the end bit
1238      * when the FU ended) and send out what we gathered thusfar */
1239     if (G_UNLIKELY (rtph265depay->current_fu_type != 0 &&
1240             nal_unit_type != rtph265depay->current_fu_type))
1241       gst_rtp_h265_push_fragmentation_unit (rtph265depay, TRUE);
1242
1243     switch (nal_unit_type) {
1244       case 48:
1245       {
1246         GST_DEBUG_OBJECT (rtph265depay, "Processing aggregation packet");
1247
1248         /* Aggregation packet (section 4.7) */
1249
1250         /*  An example of an AP packet containing two aggregation units
1251            without the DONL and DOND fields
1252
1253            0                   1                   2                   3
1254            0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1255            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1256            |                          RTP Header                           |
1257            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1258            |   PayloadHdr (Type=48)        |         NALU 1 Size           |
1259            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1260            |          NALU 1 HDR           |                               |
1261            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+         NALU 1 Data           |
1262            |                   . . .                                       |
1263            |                                                               |
1264            +               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1265            |  . . .        | NALU 2 Size                   | NALU 2 HDR    |
1266            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1267            | NALU 2 HDR    |                                               |
1268            +-+-+-+-+-+-+-+-+              NALU 2 Data                      |
1269            |                   . . .                                       |
1270            |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1271            |                               :...OPTIONAL RTP padding        |
1272            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1273          */
1274
1275         /* strip headers */
1276         payload += header_len;
1277         payload_len -= header_len;
1278
1279         rtph265depay->wait_start = FALSE;
1280
1281 #if 0
1282         if (donl_present)
1283           goto not_implemented_donl_present;
1284 #endif
1285
1286         while (payload_len > 2) {
1287
1288           nalu_size = (payload[0] << 8) | payload[1];
1289
1290           /* dont include nalu_size */
1291           if (nalu_size > (payload_len - 2))
1292             nalu_size = payload_len - 2;
1293
1294           outsize = nalu_size + sizeof (sync_bytes);
1295           outbuf = gst_buffer_new_and_alloc (outsize);
1296
1297           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1298           if (rtph265depay->byte_stream) {
1299             memcpy (map.data, sync_bytes, sizeof (sync_bytes));
1300           } else {
1301             goto not_implemented;
1302           }
1303
1304           /* strip NALU size */
1305           payload += 2;
1306           payload_len -= 2;
1307
1308           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
1309           gst_buffer_unmap (outbuf, &map);
1310
1311           gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
1312               g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1313
1314           outbuf =
1315               gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
1316               marker);
1317           if (outbuf)
1318             gst_adapter_push (rtph265depay->adapter, outbuf);
1319
1320           payload += nalu_size;
1321           payload_len -= nalu_size;
1322         }
1323
1324         outsize = gst_adapter_available (rtph265depay->adapter);
1325         if (outsize > 0) {
1326           outbuf = gst_adapter_take_buffer (rtph265depay->adapter, outsize);
1327           outbuf =
1328               gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
1329               marker);
1330         }
1331         break;
1332       }
1333       case 49:
1334       {
1335         GST_DEBUG_OBJECT (rtph265depay, "Processing Fragmentation Unit");
1336
1337         /* Fragmentation units (FUs)  Section 4.8 */
1338
1339         /*    The structure of a Fragmentation Unit (FU)
1340          *
1341          *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1342          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1343          |    PayloadHdr (Type=49)       |   FU header   | DONL (cond)   |
1344          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
1345          | DONL (cond)   |                                               |
1346          |-+-+-+-+-+-+-+-+                                               |
1347          |                         FU payload                            |
1348          |                                                               |
1349          |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1350          |                               :...OPTIONAL RTP padding        |
1351          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1352          *
1353          *
1354          */
1355
1356         /* strip headers */
1357         payload += header_len;
1358         payload_len -= header_len;
1359
1360         /* processing FU header */
1361         S = (payload[0] & 0x80) == 0x80;
1362         E = (payload[0] & 0x40) == 0x40;
1363
1364         GST_DEBUG_OBJECT (rtph265depay,
1365             "FU header with S %d, E %d, nal_unit_type %d", S, E,
1366             payload[0] & 0x3f);
1367
1368         if (rtph265depay->wait_start && !S)
1369           goto waiting_start;
1370
1371 #if 0
1372         if (donl_present)
1373           goto not_implemented_donl_present;
1374 #endif
1375
1376         if (S) {
1377
1378           GST_DEBUG_OBJECT (rtph265depay, "Start of Fragmentation Unit");
1379
1380           /* If a new FU unit started, while still processing an older one.
1381            * Assume that the remote payloader is buggy (doesn't set the end
1382            * bit) and send out what we've gathered thusfar */
1383           if (G_UNLIKELY (rtph265depay->current_fu_type != 0))
1384             gst_rtp_h265_push_fragmentation_unit (rtph265depay, TRUE);
1385
1386           rtph265depay->current_fu_type = nal_unit_type;
1387           rtph265depay->fu_timestamp = timestamp;
1388
1389           rtph265depay->wait_start = FALSE;
1390
1391           /* reconstruct NAL header */
1392           nal_header =
1393               ((payload[0] & 0x3f) << 9) | (nuh_layer_id << 3) |
1394               nuh_temporal_id_plus1;
1395
1396           /* go back one byte so we can copy the payload + two bytes more in the front which
1397            * will be overwritten by the nal_header
1398            */
1399           payload -= 1;
1400           payload_len += 1;
1401
1402           nalu_size = payload_len;
1403           outsize = nalu_size + sizeof (sync_bytes);
1404           outbuf = gst_buffer_new_and_alloc (outsize);
1405
1406           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1407           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
1408           map.data[sizeof (sync_bytes)] = nal_header >> 8;
1409           map.data[sizeof (sync_bytes) + 1] = nal_header & 0xff;
1410           gst_buffer_unmap (outbuf, &map);
1411
1412           gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
1413               g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1414
1415           GST_DEBUG_OBJECT (rtph265depay, "queueing %d bytes", outsize);
1416
1417           /* and assemble in the adapter */
1418           gst_adapter_push (rtph265depay->adapter, outbuf);
1419         } else {
1420
1421           GST_DEBUG_OBJECT (rtph265depay,
1422               "Following part of Fragmentation Unit");
1423
1424           /* strip off FU header byte */
1425           payload += 1;
1426           payload_len -= 1;
1427
1428           outsize = payload_len;
1429           outbuf = gst_buffer_new_and_alloc (outsize);
1430           gst_buffer_fill (outbuf, 0, payload, outsize);
1431
1432           gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
1433               g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1434
1435           GST_DEBUG_OBJECT (rtph265depay, "queueing %d bytes", outsize);
1436
1437           /* and assemble in the adapter */
1438           gst_adapter_push (rtph265depay->adapter, outbuf);
1439         }
1440
1441         outbuf = NULL;
1442         rtph265depay->fu_marker = marker;
1443
1444         /* if NAL unit ends, flush the adapter */
1445         if (E) {
1446           outbuf = gst_rtp_h265_push_fragmentation_unit (rtph265depay, FALSE);
1447           GST_DEBUG_OBJECT (rtph265depay, "End of Fragmentation Unit");
1448         }
1449         break;
1450       }
1451       case 50:
1452         goto not_implemented;   /* PACI packets  Section 4.9 */
1453       default:
1454       {
1455         rtph265depay->wait_start = FALSE;
1456
1457         /* All other cases: Single NAL unit packet   Section 4.6 */
1458         /* the entire payload is the output buffer */
1459
1460 #if 0
1461         if (donl_present)
1462           goto not_implemented_donl_present;
1463 #endif
1464
1465         nalu_size = payload_len;
1466         outsize = nalu_size + sizeof (sync_bytes);
1467         outbuf = gst_buffer_new_and_alloc (outsize);
1468
1469         gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1470         if (rtph265depay->byte_stream) {
1471           memcpy (map.data, sync_bytes, sizeof (sync_bytes));
1472         } else {
1473           goto not_implemented;
1474         }
1475         memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
1476         gst_buffer_unmap (outbuf, &map);
1477
1478         gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
1479             g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1480
1481         outbuf = gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
1482             marker);
1483         break;
1484       }
1485     }
1486   }
1487
1488   gst_buffer_unref (buf);
1489
1490   return outbuf;
1491
1492   /* ERRORS */
1493 empty_packet:
1494   {
1495     GST_DEBUG_OBJECT (rtph265depay, "empty packet");
1496     gst_buffer_unref (buf);
1497     return NULL;
1498   }
1499 waiting_start:
1500   {
1501     GST_DEBUG_OBJECT (rtph265depay, "waiting for start");
1502     gst_buffer_unref (buf);
1503     return NULL;
1504   }
1505 #if 0
1506 not_implemented_donl_present:
1507   {
1508     GST_ELEMENT_ERROR (rtph265depay, STREAM, FORMAT,
1509         (NULL), ("DONL field present not supported yet"));
1510     gst_buffer_unref (buf);
1511     return NULL;
1512   }
1513 #endif
1514 not_implemented:
1515   {
1516     GST_ELEMENT_ERROR (rtph265depay, STREAM, FORMAT,
1517         (NULL), ("NAL unit type %d not supported yet", nal_unit_type));
1518     gst_buffer_unref (buf);
1519     return NULL;
1520   }
1521 }
1522
1523 static gboolean
1524 gst_rtp_h265_depay_handle_event (GstRTPBaseDepayload * depay, GstEvent * event)
1525 {
1526   GstRtpH265Depay *rtph265depay;
1527
1528   rtph265depay = GST_RTP_H265_DEPAY (depay);
1529
1530   switch (GST_EVENT_TYPE (event)) {
1531     case GST_EVENT_FLUSH_STOP:
1532       gst_rtp_h265_depay_reset (rtph265depay);
1533       break;
1534     default:
1535       break;
1536   }
1537
1538   return
1539       GST_RTP_BASE_DEPAYLOAD_CLASS (parent_class)->handle_event (depay, event);
1540 }
1541
1542 static GstStateChangeReturn
1543 gst_rtp_h265_depay_change_state (GstElement * element,
1544     GstStateChange transition)
1545 {
1546   GstRtpH265Depay *rtph265depay;
1547   GstStateChangeReturn ret;
1548
1549   rtph265depay = GST_RTP_H265_DEPAY (element);
1550
1551   switch (transition) {
1552     case GST_STATE_CHANGE_NULL_TO_READY:
1553       break;
1554     case GST_STATE_CHANGE_READY_TO_PAUSED:
1555       gst_rtp_h265_depay_reset (rtph265depay);
1556       break;
1557     default:
1558       break;
1559   }
1560
1561   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1562
1563   switch (transition) {
1564     case GST_STATE_CHANGE_READY_TO_NULL:
1565       break;
1566     default:
1567       break;
1568   }
1569   return ret;
1570 }
1571
1572 gboolean
1573 gst_rtp_h265_depay_plugin_init (GstPlugin * plugin)
1574 {
1575   GST_DEBUG_CATEGORY_INIT (rtph265depay_debug, "rtph265depay", 0,
1576       "H265 Video RTP Depayloader");
1577
1578   return gst_element_register (plugin, "rtph265depay",
1579       GST_RANK_SECONDARY, GST_TYPE_RTP_H265_DEPAY);
1580 }