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