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