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