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