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