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