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