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