812eeabc173125f0d73f5b4f8a678a85aafd6297
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtph265pay.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 <string.h>
26 #include <stdlib.h>
27
28 #include <gst/rtp/gstrtpbuffer.h>
29 #include <gst/pbutils/pbutils.h>
30 #include <gst/video/video.h>
31
32 /* Included to not duplicate gst_rtp_h265_add_vps_sps_pps () */
33 #include "gstrtph265depay.h"
34
35 #include "gstrtph265pay.h"
36 #include "gstrtputils.h"
37
38 GST_DEBUG_CATEGORY_STATIC (rtph265pay_debug);
39 #define GST_CAT_DEFAULT (rtph265pay_debug)
40
41 /* references:
42  *
43  * Internet Draft RTP Payload Format for High Efficiency Video Coding
44  *
45  *                   draft-ietf-payload-rtp-h265-03.txt
46  *
47  * This draft will be replaced with an RFC, so some details may change.
48  *
49  */
50
51 static GstStaticPadTemplate gst_rtp_h265_pay_sink_template =
52     GST_STATIC_PAD_TEMPLATE ("sink",
53     GST_PAD_SINK,
54     GST_PAD_ALWAYS,
55     GST_STATIC_CAPS (
56         /* only hvc1 and byte-stream formats supported for now */
57         "video/x-h265, stream-format = (string) hvc1, alignment = (string) au; "
58         /* "video/x-h265, "
59            "stream-format = (string) hev1, alignment = (string) au; " */
60         "video/x-h265, stream-format = (string) byte-stream, "
61         "alignment = (string) { nal, au }")
62     );
63
64 static GstStaticPadTemplate gst_rtp_h265_pay_src_template =
65 GST_STATIC_PAD_TEMPLATE ("src",
66     GST_PAD_SRC,
67     GST_PAD_ALWAYS,
68     GST_STATIC_CAPS ("application/x-rtp, "
69         "media = (string) \"video\", "
70         "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
71         "clock-rate = (int) 90000, " "encoding-name = (string) \"H265\"")
72                 /** optional parameters **/
73     /* "profile-space = (int) [ 0, 3 ], " */
74     /* "profile-id = (int) [ 0, 31 ], " */
75     /* "tier-flag = (int) [ 0, 1 ], " */
76     /* "level-id = (int) [ 0, 255 ], " */
77     /* "interop-constraints = (string) ANY, " */
78     /* "profile-compatibility-indicator = (string) ANY, " */
79     /* "sprop-sub-layer-id = (int) [ 0, 6 ], " */
80     /* "recv-sub-layer-id = (int) [ 0, 6 ], " */
81     /* "max-recv-level-id = (int) [ 0, 255 ], " */
82     /* "tx-mode = (string) {MST , SST}, " */
83     /* "sprop-vps = (string) ANY, " */
84     /* "sprop-sps = (string) ANY, " */
85     /* "sprop-pps = (string) ANY, " */
86     /* "sprop-sei = (string) ANY, " */
87     /* "max-lsr = (int) ANY, " *//* MUST be in the range of MaxLumaSR to 16 * MaxLumaSR, inclusive */
88     /* "max-lps = (int) ANY, " *//* MUST be in the range of MaxLumaPS to 16 * MaxLumaPS, inclusive */
89     /* "max-cpb = (int) ANY, " *//* MUST be in the range of MaxCPB to 16 * MaxCPB, inclusive */
90     /* "max-dpb = (int) [1, 16], " */
91     /* "max-br = (int) ANY, " *//* MUST be in the range of MaxBR to 16 * MaxBR, inclusive, for the highest level */
92     /* "max-tr = (int) ANY, " *//* MUST be in the range of MaxTileRows to 16 * MaxTileRows, inclusive, for the highest level */
93     /* "max-tc = (int) ANY, " *//* MUST be in the range of MaxTileCols to 16 * MaxTileCols, inclusive, for the highest level */
94     /* "max-fps = (int) ANY, " */
95     /* "sprop-max-don-diff = (int) [0, 32767], " */
96     /* "sprop-depack-buf-nalus = (int) [0, 32767], " */
97     /* "sprop-depack-buf-nalus = (int) [0, 4294967295], " */
98     /* "depack-buf-cap = (int) [1, 4294967295], " */
99     /* "sprop-segmentation-id = (int) [0, 3], " */
100     /* "sprop-spatial-segmentation-idc = (string) ANY, " */
101     /* "dec-parallel-cap = (string) ANY, " */
102     );
103
104 #define DEFAULT_CONFIG_INTERVAL               0
105
106 enum
107 {
108   PROP_0,
109   PROP_CONFIG_INTERVAL
110 };
111
112 #define IS_ACCESS_UNIT(x) (((x) >= 0x00) && ((x) < 0x20))
113
114 static void gst_rtp_h265_pay_finalize (GObject * object);
115
116 static void gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
117     const GValue * value, GParamSpec * pspec);
118 static void gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
119     GValue * value, GParamSpec * pspec);
120
121 static GstCaps *gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload,
122     GstPad * pad, GstCaps * filter);
123 static gboolean gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload,
124     GstCaps * caps);
125 static GstFlowReturn gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * pad,
126     GstBuffer * buffer);
127 static gboolean gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload,
128     GstEvent * event);
129 static GstStateChangeReturn gst_rtp_h265_pay_change_state (GstElement *
130     element, GstStateChange transition);
131
132 #define gst_rtp_h265_pay_parent_class parent_class
133 G_DEFINE_TYPE (GstRtpH265Pay, gst_rtp_h265_pay, GST_TYPE_RTP_BASE_PAYLOAD);
134
135 static void
136 gst_rtp_h265_pay_class_init (GstRtpH265PayClass * klass)
137 {
138   GObjectClass *gobject_class;
139   GstElementClass *gstelement_class;
140   GstRTPBasePayloadClass *gstrtpbasepayload_class;
141
142   gobject_class = (GObjectClass *) klass;
143   gstelement_class = (GstElementClass *) klass;
144   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
145
146   gobject_class->set_property = gst_rtp_h265_pay_set_property;
147   gobject_class->get_property = gst_rtp_h265_pay_get_property;
148
149   g_object_class_install_property (G_OBJECT_CLASS (klass),
150       PROP_CONFIG_INTERVAL,
151       g_param_spec_int ("config-interval",
152           "VPS SPS PPS Send Interval",
153           "Send VPS, SPS and PPS Insertion Interval in seconds (sprop parameter sets "
154           "will be multiplexed in the data stream when detected.) "
155           "(0 = disabled, -1 = send with every IDR frame)",
156           -1, 3600, DEFAULT_CONFIG_INTERVAL,
157           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
158       );
159
160   gobject_class->finalize = gst_rtp_h265_pay_finalize;
161
162   gst_element_class_add_static_pad_template (gstelement_class,
163       &gst_rtp_h265_pay_src_template);
164   gst_element_class_add_static_pad_template (gstelement_class,
165       &gst_rtp_h265_pay_sink_template);
166
167   gst_element_class_set_static_metadata (gstelement_class, "RTP H265 payloader",
168       "Codec/Payloader/Network/RTP",
169       "Payload-encode H265 video into RTP packets (RFC 7798)",
170       "Jurgen Slowack <jurgenslowack@gmail.com>");
171
172   gstelement_class->change_state =
173       GST_DEBUG_FUNCPTR (gst_rtp_h265_pay_change_state);
174
175   gstrtpbasepayload_class->get_caps = gst_rtp_h265_pay_getcaps;
176   gstrtpbasepayload_class->set_caps = gst_rtp_h265_pay_setcaps;
177   gstrtpbasepayload_class->handle_buffer = gst_rtp_h265_pay_handle_buffer;
178   gstrtpbasepayload_class->sink_event = gst_rtp_h265_pay_sink_event;
179
180   GST_DEBUG_CATEGORY_INIT (rtph265pay_debug, "rtph265pay", 0,
181       "H265 RTP Payloader");
182 }
183
184 static void
185 gst_rtp_h265_pay_init (GstRtpH265Pay * rtph265pay)
186 {
187   rtph265pay->queue = g_array_new (FALSE, FALSE, sizeof (guint));
188   rtph265pay->sps = g_ptr_array_new_with_free_func (
189       (GDestroyNotify) gst_buffer_unref);
190   rtph265pay->pps = g_ptr_array_new_with_free_func (
191       (GDestroyNotify) gst_buffer_unref);
192   rtph265pay->vps = g_ptr_array_new_with_free_func (
193       (GDestroyNotify) gst_buffer_unref);
194   rtph265pay->last_vps_sps_pps = -1;
195   rtph265pay->vps_sps_pps_interval = DEFAULT_CONFIG_INTERVAL;
196
197   rtph265pay->adapter = gst_adapter_new ();
198 }
199
200 static void
201 gst_rtp_h265_pay_clear_vps_sps_pps (GstRtpH265Pay * rtph265pay)
202 {
203   g_ptr_array_set_size (rtph265pay->vps, 0);
204   g_ptr_array_set_size (rtph265pay->sps, 0);
205   g_ptr_array_set_size (rtph265pay->pps, 0);
206 }
207
208 static void
209 gst_rtp_h265_pay_finalize (GObject * object)
210 {
211   GstRtpH265Pay *rtph265pay;
212
213   rtph265pay = GST_RTP_H265_PAY (object);
214
215   g_array_free (rtph265pay->queue, TRUE);
216
217   g_ptr_array_free (rtph265pay->sps, TRUE);
218   g_ptr_array_free (rtph265pay->pps, TRUE);
219   g_ptr_array_free (rtph265pay->vps, TRUE);
220
221   g_object_unref (rtph265pay->adapter);
222
223   G_OBJECT_CLASS (parent_class)->finalize (object);
224 }
225
226 static const gchar all_levels[][4] = {
227   "1",
228   "2",
229   "2.1",
230   "3",
231   "3.1",
232   "4",
233   "4.1",
234   "5",
235   "5.1",
236   "5.2",
237   "6",
238   "6.1",
239   "6.2"
240 };
241
242 static gboolean
243 parse_field (GstStructure * s, const gchar * field, gulong min, gulong max,
244     guint8 * result)
245 {
246   const gchar *str;
247
248   g_assert (result != NULL);
249
250   str = gst_structure_get_string (s, field);
251   if (str != NULL && *str != '\0') {
252     gulong value;
253     gchar *end;
254
255     value = strtoul (str, &end, 10);
256     if (*end == '\0' && value >= min && value <= max) {
257       *result = (guint8) value;
258     } else {
259       return FALSE;
260     }
261   } else {
262     return FALSE;
263   }
264
265   return TRUE;
266 }
267
268 static GstCaps *
269 gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload, GstPad * pad,
270     GstCaps * filter)
271 {
272   GstCaps *template_caps;
273   GstCaps *allowed_caps;
274   GstCaps *caps;
275   GstCaps *icaps;
276   guint i;
277
278   allowed_caps =
279       gst_pad_peer_query_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), NULL);
280
281   if (allowed_caps == NULL)
282     return NULL;
283
284   template_caps =
285       gst_static_pad_template_get_caps (&gst_rtp_h265_pay_sink_template);
286
287   if (gst_caps_is_any (allowed_caps)) {
288     caps = gst_caps_ref (template_caps);
289     goto done;
290   }
291
292   if (gst_caps_is_empty (allowed_caps)) {
293     caps = gst_caps_ref (allowed_caps);
294     goto done;
295   }
296
297   caps = gst_caps_new_empty ();
298   for (i = 0; i < gst_caps_get_size (allowed_caps); i++) {
299     GstStructure *s = gst_caps_get_structure (allowed_caps, i);
300     GstStructure *new_s = gst_structure_new_empty ("video/x-h265");
301     guint8 ptl[12] = { 0, };
302     guint8 value;
303
304     if (parse_field (s, "profile-id", 0, 31, &value)) {
305       const gchar *profile;
306
307       ptl[0] = value;
308       profile = gst_codec_utils_h265_get_profile (ptl, sizeof (ptl));
309       if (profile != NULL) {
310         GST_DEBUG_OBJECT (payload, "profile %s", profile);
311         gst_structure_set (new_s, "profile", G_TYPE_STRING, profile, NULL);
312       } else {
313         GST_WARNING_OBJECT (payload, "invalid profile-id %d in caps", value);
314       }
315     } else {
316       GST_DEBUG_OBJECT (payload, "no valid profile-id in caps");
317     }
318
319     if (parse_field (s, "tier-flag", 0, 1, &value)) {
320       const gchar *tier;
321
322       ptl[0] |= value << 5;
323       tier = gst_codec_utils_h265_get_tier (ptl, sizeof (ptl));
324       GST_DEBUG_OBJECT (payload, "tier %s", tier);
325       gst_structure_set (new_s, "tier", G_TYPE_STRING, tier, NULL);
326     } else {
327       GST_DEBUG_OBJECT (payload, "no valid tier-flag in caps");
328     }
329
330     if (parse_field (s, "level-id", 0, 255, &value)) {
331       const gchar *level;
332
333       ptl[11] = value;
334       level = gst_codec_utils_h265_get_level (ptl, sizeof (ptl));
335       if (level != NULL) {
336         GST_DEBUG_OBJECT (payload, "level %s", level);
337         if (strcmp (level, "1") == 0) {
338           gst_structure_set (new_s, "level", G_TYPE_STRING, level, NULL);
339         } else {
340           GValue levels = { 0, };
341           GValue val = { 0, };
342           int j;
343
344           g_value_init (&levels, GST_TYPE_LIST);
345           g_value_init (&val, G_TYPE_STRING);
346
347           for (j = 0; j < G_N_ELEMENTS (all_levels); j++) {
348             g_value_set_static_string (&val, all_levels[j]);
349             gst_value_list_prepend_value (&levels, &val);
350             if (!strcmp (level, all_levels[j]))
351               break;
352           }
353           gst_structure_take_value (new_s, "level", &levels);
354         }
355       } else {
356         GST_WARNING_OBJECT (payload, "invalid level-id %d in caps", value);
357       }
358     } else {
359       GST_DEBUG_OBJECT (payload, "no valid level-id in caps");
360     }
361
362     caps = gst_caps_merge_structure (caps, new_s);
363   }
364
365   icaps = gst_caps_intersect (caps, template_caps);
366   gst_caps_unref (caps);
367   caps = icaps;
368
369 done:
370
371   if (filter) {
372     GstCaps *tmp;
373
374     GST_DEBUG_OBJECT (payload, "Intersect %" GST_PTR_FORMAT " and filter %"
375         GST_PTR_FORMAT, caps, filter);
376     tmp = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
377     gst_caps_unref (caps);
378     caps = tmp;
379   }
380
381   gst_caps_unref (template_caps);
382   gst_caps_unref (allowed_caps);
383
384   GST_LOG_OBJECT (payload, "returning caps %" GST_PTR_FORMAT, caps);
385   return caps;
386 }
387
388 /* take the currently configured VPS, SPS and PPS lists and set them on the
389  * caps */
390 static gboolean
391 gst_rtp_h265_pay_set_vps_sps_pps (GstRTPBasePayload * basepayload)
392 {
393   GstRtpH265Pay *payloader = GST_RTP_H265_PAY (basepayload);
394   gchar *set;
395   GString *vps;
396   GString *sps;
397   GString *pps;
398   guint count;
399   gboolean res;
400   GstMapInfo map;
401   guint i;
402
403   vps = g_string_new ("");
404   sps = g_string_new ("");
405   pps = g_string_new ("");
406   count = 0;
407
408   for (i = 0; i < payloader->vps->len; i++) {
409     GstBuffer *vps_buf =
410         GST_BUFFER_CAST (g_ptr_array_index (payloader->vps, i));
411
412     gst_buffer_map (vps_buf, &map, GST_MAP_READ);
413     set = g_base64_encode (map.data, map.size);
414     gst_buffer_unmap (vps_buf, &map);
415
416     g_string_append_printf (vps, "%s%s", i ? "," : "", set);
417     g_free (set);
418     count++;
419   }
420   for (i = 0; i < payloader->sps->len; i++) {
421     GstBuffer *sps_buf =
422         GST_BUFFER_CAST (g_ptr_array_index (payloader->sps, i));
423
424     gst_buffer_map (sps_buf, &map, GST_MAP_READ);
425     set = g_base64_encode (map.data, map.size);
426     gst_buffer_unmap (sps_buf, &map);
427
428     g_string_append_printf (sps, "%s%s", i ? "," : "", set);
429     g_free (set);
430     count++;
431   }
432   for (i = 0; i < payloader->pps->len; i++) {
433     GstBuffer *pps_buf =
434         GST_BUFFER_CAST (g_ptr_array_index (payloader->pps, i));
435
436     gst_buffer_map (pps_buf, &map, GST_MAP_READ);
437     set = g_base64_encode (map.data, map.size);
438     gst_buffer_unmap (pps_buf, &map);
439
440     g_string_append_printf (pps, "%s%s", i ? "," : "", set);
441     g_free (set);
442     count++;
443   }
444
445   if (G_LIKELY (count)) {
446     /* combine into output caps */
447     res = gst_rtp_base_payload_set_outcaps (basepayload,
448         "sprop-vps", G_TYPE_STRING, vps->str,
449         "sprop-sps", G_TYPE_STRING, sps->str,
450         "sprop-pps", G_TYPE_STRING, pps->str, NULL);
451   } else {
452     res = gst_rtp_base_payload_set_outcaps (basepayload, NULL);
453   }
454   g_string_free (vps, TRUE);
455   g_string_free (sps, TRUE);
456   g_string_free (pps, TRUE);
457
458   return res;
459 }
460
461
462 static gboolean
463 gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
464 {
465   GstRtpH265Pay *rtph265pay;
466   GstStructure *str;
467   const GValue *value;
468   GstMapInfo map;
469   guint8 *data;
470   gsize size;
471   GstBuffer *buffer;
472   const gchar *alignment, *stream_format;
473   guint8 num_arrays;
474
475   rtph265pay = GST_RTP_H265_PAY (basepayload);
476
477   str = gst_caps_get_structure (caps, 0);
478
479   /* we can only set the output caps when we found the sprops and profile
480    * NALs */
481   gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "H265", 90000);
482
483   rtph265pay->alignment = GST_H265_ALIGNMENT_UNKNOWN;
484   alignment = gst_structure_get_string (str, "alignment");
485   if (alignment) {
486     if (g_str_equal (alignment, "au"))
487       rtph265pay->alignment = GST_H265_ALIGNMENT_AU;
488     if (g_str_equal (alignment, "nal"))
489       rtph265pay->alignment = GST_H265_ALIGNMENT_NAL;
490   }
491
492   rtph265pay->stream_format = GST_H265_STREAM_FORMAT_UNKNOWN;
493   stream_format = gst_structure_get_string (str, "stream-format");
494   if (stream_format) {
495     if (g_str_equal (stream_format, "hvc1"))
496       rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HVC1;
497     if (g_str_equal (stream_format, "hev1"))
498       rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HEV1;
499     if (g_str_equal (stream_format, "byte-stream"))
500       rtph265pay->stream_format = GST_H265_STREAM_FORMAT_BYTESTREAM;
501   }
502
503   /* packetized HEVC video has a codec_data */
504   if ((value = gst_structure_get_value (str, "codec_data"))) {
505     guint num_vps, num_sps, num_pps;
506     gint i, j, nal_size;
507
508     GST_DEBUG_OBJECT (rtph265pay, "have packetized h265");
509
510     buffer = gst_value_get_buffer (value);
511
512     gst_buffer_map (buffer, &map, GST_MAP_READ);
513     data = map.data;
514     size = map.size;
515
516     /* parse the hevcC data */
517     if (size < 23)
518       goto hevcc_too_small;
519     /* HEVCDecoderConfigurationVersion (must be 1) */
520     if (data[0] != 1)
521       goto wrong_version;
522
523     /* profile_space | tier_flag | profile_idc */
524     GST_DEBUG_OBJECT (rtph265pay, "profile %06x", data[1]);
525
526     /* profile_compatibility_flags */
527     for (i = 2; i < 6; i++) {
528       for (j = 7; j >= 0; j--) {
529         GST_DEBUG_OBJECT (rtph265pay, "profile_compatibility_flag %06x",
530             (data[i] >> j) & 1);
531       }
532     }
533
534     GST_DEBUG_OBJECT (rtph265pay, "progressive_source_flag %06x",
535         (data[6] >> 7) & 1);
536     GST_DEBUG_OBJECT (rtph265pay, "interlaced_source_flag %06x",
537         (data[6] >> 6) & 1);
538     GST_DEBUG_OBJECT (rtph265pay, "non_packed_constraint_flag %06x",
539         (data[6] >> 5) & 1);
540     GST_DEBUG_OBJECT (rtph265pay, "frame_only_constraint_flag %06x",
541         (data[6] >> 4) & 1);
542
543     GST_DEBUG_OBJECT (rtph265pay, "level_idc %06x", data[12]);
544
545     GST_DEBUG_OBJECT (rtph265pay, "min_spatial_segmentation_idc %06x",
546         ((data[13] ^ 0xf0) << 8) + data[14]);
547     GST_DEBUG_OBJECT (rtph265pay, "parrallelismType %06x (ignored by paloader)",
548         data[15]);
549
550     GST_DEBUG_OBJECT (rtph265pay, "sps_chroma_format_idc %06x",
551         data[16] ^ 0xfc);
552     GST_DEBUG_OBJECT (rtph265pay, "bit_depth_luma_minus8 %06x",
553         data[17] ^ 0xf8);
554     GST_DEBUG_OBJECT (rtph265pay, "bit_depth_chroma_minus8 %06x",
555         data[18] ^ 0xf8);
556     GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[19]);
557     GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[20]);
558
559     /* constFrameRate(2 bits): 0, stream may or may not be of constant framerate
560      * numTemporalLayers (3 bits): number of temporal layers, value from SPS
561      * TemporalIdNested (1 bit): sps_temporal_id_nesting_flag from SPS
562      * lengthSizeMinusOne (2 bits): plus 1 indicates the length of the NALUnitLength */
563     GST_DEBUG_OBJECT (rtph265pay, "constFrameRate %06x",
564         (data[21] >> 6) & 0x03);
565     GST_DEBUG_OBJECT (rtph265pay, "numTemporalLayers %06x",
566         (data[21] >> 3) & 0x07);
567     GST_DEBUG_OBJECT (rtph265pay, "temporal_id_nesting_flag %06x",
568         (data[21] >> 2) & 0x01);
569
570     rtph265pay->nal_length_size = (data[21] & 0x3) + 1;
571     GST_DEBUG_OBJECT (rtph265pay, "nal length %u", rtph265pay->nal_length_size);
572
573     num_arrays = GST_READ_UINT8 (data + 22);
574
575     data += 23;
576     size -= 23;
577
578     if (num_arrays > 0) {
579       if ((data[0] & 0x3f) == 0x20) {   /* VPS */
580
581         data++;
582         num_vps = data[0] << 8 | data[1];
583         data += 2;
584         size -= 2;
585
586         for (i = 0; i < num_vps; i++) {
587
588           GstBuffer *vps_buf;
589
590           if (size < 2)
591             goto hevcc_error;
592
593           nal_size = (data[0] << 8) | data[1];
594           data += 2;
595           size -= 2;
596
597           GST_LOG_OBJECT (rtph265pay, "VPS %d size %d", i, nal_size);
598
599           if (size < nal_size)
600             goto hevcc_error;
601
602           /* make a buffer out of it and add to VPS list */
603           vps_buf = gst_buffer_new_and_alloc (nal_size);
604           gst_buffer_fill (vps_buf, 0, data, nal_size);
605           gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
606               rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, vps_buf);
607           data += nal_size;
608           size -= nal_size;
609         }
610       }
611
612       --num_arrays;
613     }
614
615     if (num_arrays > 0) {
616       if ((data[0] & 0x3f) == 0x21) {   /* SPS */
617
618         data++;
619         num_sps = data[0] << 8 | data[1];
620         data += 2;
621         size -= 2;
622
623         for (i = 0; i < num_sps; i++) {
624
625           GstBuffer *sps_buf;
626
627           if (size < 2)
628             goto hevcc_error;
629
630           nal_size = (data[0] << 8) | data[1];
631           data += 2;
632           size -= 2;
633
634           GST_LOG_OBJECT (rtph265pay, "SPS %d size %d", i, nal_size);
635
636           if (size < nal_size)
637             goto hevcc_error;
638
639           /* make a buffer out of it and add to SPS list */
640           sps_buf = gst_buffer_new_and_alloc (nal_size);
641           gst_buffer_fill (sps_buf, 0, data, nal_size);
642           gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
643               rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, sps_buf);
644           data += nal_size;
645           size -= nal_size;
646         }
647       }
648
649       --num_arrays;
650     }
651
652     if (num_arrays > 0) {
653       if ((data[0] & 0x3f) == 0x22) {   /* PPS */
654
655         data++;
656         num_pps = data[0] << 8 | data[1];
657         data += 2;
658         size -= 2;
659
660         for (i = 0; i < num_pps; i++) {
661
662           GstBuffer *pps_buf;
663
664           if (size < 2)
665             goto hevcc_error;
666
667           nal_size = (data[0] << 8) | data[1];
668           data += 2;
669           size -= 2;
670
671           GST_LOG_OBJECT (rtph265pay, "PPS %d size %d", i, nal_size);
672
673           if (size < nal_size)
674             goto hevcc_error;
675
676           /* make a buffer out of it and add to PPS list */
677           pps_buf = gst_buffer_new_and_alloc (nal_size);
678           gst_buffer_fill (pps_buf, 0, data, nal_size);
679           gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
680               rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, pps_buf);
681           data += nal_size;
682           size -= nal_size;
683         }
684       }
685
686       --num_arrays;
687     }
688
689     /* and update the caps with the collected data */
690     if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
691       goto set_vps_sps_pps_failed;
692
693     GST_DEBUG_OBJECT (rtph265pay, "Caps have been set");
694
695     gst_buffer_unmap (buffer, &map);
696   } else {
697     GST_DEBUG_OBJECT (rtph265pay, "have bytestream h265");
698   }
699
700   return TRUE;
701
702 hevcc_too_small:
703   {
704     GST_ERROR_OBJECT (rtph265pay, "hevcC size %" G_GSIZE_FORMAT " < 7", size);
705     goto error;
706   }
707 wrong_version:
708   {
709     GST_ERROR_OBJECT (rtph265pay, "wrong hevcC version");
710     goto error;
711   }
712 hevcc_error:
713   {
714     GST_ERROR_OBJECT (rtph265pay, "hevcC too small ");
715     goto error;
716   }
717 set_vps_sps_pps_failed:
718   {
719     GST_ERROR_OBJECT (rtph265pay, "failed to set vps/sps/pps");
720     goto error;
721   }
722 error:
723   {
724     gst_buffer_unmap (buffer, &map);
725     return FALSE;
726   }
727 }
728
729 static guint
730 next_start_code (const guint8 * data, guint size)
731 {
732   /* Boyer-Moore string matching algorithm, in a degenerative
733    * sense because our search 'alphabet' is binary - 0 & 1 only.
734    * This allow us to simplify the general BM algorithm to a very
735    * simple form. */
736   /* assume 1 is in the 3rd byte */
737   guint offset = 2;
738
739   while (offset < size) {
740     if (1 == data[offset]) {
741       unsigned int shift = offset;
742
743       if (0 == data[--shift]) {
744         if (0 == data[--shift]) {
745           return shift;
746         }
747       }
748       /* The jump is always 3 because of the 1 previously matched.
749        * All the 0's must be after this '1' matched at offset */
750       offset += 3;
751     } else if (0 == data[offset]) {
752       /* maybe next byte is 1? */
753       offset++;
754     } else {
755       /* can jump 3 bytes forward */
756       offset += 3;
757     }
758     /* at each iteration, we rescan in a backward manner until
759      * we match 0.0.1 in reverse order. Since our search string
760      * has only 2 'alpabets' (i.e. 0 & 1), we know that any
761      * mismatch will force us to shift a fixed number of steps */
762   }
763   GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
764
765   return size;
766 }
767
768 static gboolean
769 gst_rtp_h265_pay_decode_nal (GstRtpH265Pay * payloader,
770     const guint8 * data, guint size, GstClockTime dts, GstClockTime pts)
771 {
772   guint8 type;
773   gboolean updated;
774
775   /* default is no update */
776   updated = FALSE;
777
778   GST_DEBUG_OBJECT (payloader, "NAL payload size %u", size);
779
780   type = (data[0] >> 1) & 0x3f;
781
782   /* We record the timestamp of the last SPS/PPS so
783    * that we can insert them at regular intervals and when needed. */
784   if (GST_H265_NAL_VPS == type || GST_H265_NAL_SPS == type
785       || GST_H265_NAL_PPS == type) {
786     GstBuffer *nal;
787
788     /* trailing 0x0 are not part of the VPS/SPS/PPS */
789     while (size > 0 && data[size - 1] == 0x0)
790       size--;
791
792     /* encode the entire NAL in base64 */
793     GST_DEBUG_OBJECT (payloader, "found %s (type 0x%x), size %u",
794         type == GST_H265_NAL_VPS ? "VPS" : type == GST_H265_NAL_SPS ?
795         "SPS" : "PPS", type, size);
796
797     nal = gst_buffer_new_allocate (NULL, size, NULL);
798     gst_buffer_fill (nal, 0, data, size);
799
800     updated = gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (payloader),
801         payloader->vps, payloader->sps, payloader->pps, nal);
802
803     /* remember when we last saw VPS */
804     if (pts != -1)
805       payloader->last_vps_sps_pps =
806           gst_segment_to_running_time (&GST_RTP_BASE_PAYLOAD_CAST
807           (payloader)->segment, GST_FORMAT_TIME, pts);
808   } else {
809     GST_DEBUG_OBJECT (payloader, "NALU type 0x%x, size %u", type, size);
810   }
811
812   return updated;
813 }
814
815 static GstFlowReturn
816 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
817     GPtrArray * paybufs, GstClockTime dts, GstClockTime pts);
818
819 static GstFlowReturn
820 gst_rtp_h265_pay_send_vps_sps_pps (GstRTPBasePayload * basepayload,
821     GstRtpH265Pay * rtph265pay, GstClockTime dts, GstClockTime pts)
822 {
823   GstFlowReturn ret = GST_FLOW_OK;
824   gboolean sent_all_vps_sps_pps = TRUE;
825   guint i;
826   GPtrArray *bufs;
827
828   bufs = g_ptr_array_new ();
829
830   for (i = 0; i < rtph265pay->vps->len; i++) {
831     GstBuffer *vps_buf =
832         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->vps, i));
833
834     GST_DEBUG_OBJECT (rtph265pay, "inserting VPS in the stream");
835     g_ptr_array_add (bufs, gst_buffer_ref (vps_buf));
836   }
837   for (i = 0; i < rtph265pay->sps->len; i++) {
838     GstBuffer *sps_buf =
839         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->sps, i));
840
841     GST_DEBUG_OBJECT (rtph265pay, "inserting SPS in the stream");
842     g_ptr_array_add (bufs, gst_buffer_ref (sps_buf));
843   }
844   for (i = 0; i < rtph265pay->pps->len; i++) {
845     GstBuffer *pps_buf =
846         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->pps, i));
847
848     GST_DEBUG_OBJECT (rtph265pay, "inserting PPS in the stream");
849     g_ptr_array_add (bufs, gst_buffer_ref (pps_buf));
850   }
851
852   ret = gst_rtp_h265_pay_payload_nal (basepayload, bufs, dts, pts);
853   if (ret != GST_FLOW_OK) {
854     /* not critical but warn */
855     GST_WARNING_OBJECT (basepayload, "failed pushing VPS/SPS/PPS");
856
857     sent_all_vps_sps_pps = FALSE;
858   }
859
860   if (pts != -1 && sent_all_vps_sps_pps)
861     rtph265pay->last_vps_sps_pps =
862         gst_segment_to_running_time (&basepayload->segment, GST_FORMAT_TIME,
863         pts);
864
865   return ret;
866 }
867
868 static GstFlowReturn
869 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
870     GPtrArray * paybufs, GstClockTime dts, GstClockTime pts)
871 {
872   GstRtpH265Pay *rtph265pay;
873   guint mtu;
874   GstFlowReturn ret;
875   gint i;
876   gboolean sent_ps;
877
878   rtph265pay = GST_RTP_H265_PAY (basepayload);
879   mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph265pay);
880
881   /* should set src caps before pushing stuff,
882    * and if we did not see enough VPS/SPS/PPS, that may not be the case */
883   if (G_UNLIKELY (!gst_pad_has_current_caps (GST_RTP_BASE_PAYLOAD_SRCPAD
884               (basepayload))))
885     gst_rtp_h265_pay_set_vps_sps_pps (basepayload);
886
887   ret = GST_FLOW_OK;
888   sent_ps = FALSE;
889   for (i = 0; i < paybufs->len; i++) {
890     guint8 nalHeader[2];
891     guint8 nalType;
892     guint packet_len, payload_len;
893     GstBuffer *paybuf;
894     GstBuffer *outbuf;
895     guint8 *payload;
896     GstBufferList *outlist = NULL;
897     gboolean send_ps;
898     GstRTPBuffer rtp = { NULL };
899     guint size;
900     gboolean marker;
901
902     paybuf = g_ptr_array_index (paybufs, i);
903
904     if (ret != GST_FLOW_OK) {
905       /* unref buffers that will not be payloaded after a flow error */
906       gst_buffer_unref (paybuf);
907       continue;
908     }
909
910     marker = GST_BUFFER_FLAG_IS_SET (paybuf, GST_BUFFER_FLAG_MARKER);
911
912     size = gst_buffer_get_size (paybuf);
913     gst_buffer_extract (paybuf, 0, nalHeader, 2);
914     nalType = (nalHeader[0] >> 1) & 0x3f;
915
916     GST_DEBUG_OBJECT (rtph265pay, "Processing Buffer with NAL TYPE=%d",
917         nalType);
918
919     send_ps = FALSE;
920
921     /* check if we need to emit an VPS/SPS/PPS now */
922     if ((nalType == GST_H265_NAL_SLICE_TRAIL_N)
923         || (nalType == GST_H265_NAL_SLICE_TRAIL_R)
924         || (nalType == GST_H265_NAL_SLICE_TSA_N)
925         || (nalType == GST_H265_NAL_SLICE_TSA_R)
926         || (nalType == GST_H265_NAL_SLICE_STSA_N)
927         || (nalType == GST_H265_NAL_SLICE_STSA_R)
928         || (nalType == GST_H265_NAL_SLICE_RASL_N)
929         || (nalType == GST_H265_NAL_SLICE_RASL_R)
930         || (nalType == GST_H265_NAL_SLICE_BLA_W_LP)
931         || (nalType == GST_H265_NAL_SLICE_BLA_W_RADL)
932         || (nalType == GST_H265_NAL_SLICE_BLA_N_LP)
933         || (nalType == GST_H265_NAL_SLICE_IDR_W_RADL)
934         || (nalType == GST_H265_NAL_SLICE_IDR_N_LP)
935         || (nalType == GST_H265_NAL_SLICE_CRA_NUT)) {
936       if (rtph265pay->vps_sps_pps_interval > 0) {
937         if (rtph265pay->last_vps_sps_pps != -1) {
938           guint64 diff;
939           GstClockTime running_time =
940               gst_segment_to_running_time (&basepayload->segment,
941               GST_FORMAT_TIME, pts);
942
943           GST_LOG_OBJECT (rtph265pay,
944               "now %" GST_TIME_FORMAT ", last VPS/SPS/PPS %" GST_TIME_FORMAT,
945               GST_TIME_ARGS (running_time),
946               GST_TIME_ARGS (rtph265pay->last_vps_sps_pps));
947
948           /* calculate diff between last SPS/PPS in milliseconds */
949           if (running_time > rtph265pay->last_vps_sps_pps)
950             diff = running_time - rtph265pay->last_vps_sps_pps;
951           else
952             diff = 0;
953
954           GST_DEBUG_OBJECT (rtph265pay,
955               "interval since last VPS/SPS/PPS %" GST_TIME_FORMAT,
956               GST_TIME_ARGS (diff));
957
958           /* bigger than interval, queue SPS/PPS */
959           if (GST_TIME_AS_SECONDS (diff) >= rtph265pay->vps_sps_pps_interval) {
960             GST_DEBUG_OBJECT (rtph265pay, "time to send VPS/SPS/PPS");
961             send_ps = TRUE;
962           }
963         } else {
964           /* no known previous SPS/PPS time, send now */
965           GST_DEBUG_OBJECT (rtph265pay,
966               "no previous VPS/SPS/PPS time, send now");
967           send_ps = TRUE;
968         }
969       } else if (rtph265pay->vps_sps_pps_interval == -1
970           && (nalType == GST_H265_NAL_SLICE_IDR_W_RADL
971               || nalType == GST_H265_NAL_SLICE_IDR_N_LP)) {
972         /* send VPS/SPS/PPS before every IDR frame */
973         send_ps = TRUE;
974       }
975     }
976
977     if (!sent_ps && (send_ps || rtph265pay->send_vps_sps_pps)) {
978       /* we need to send SPS/PPS now first. FIXME, don't use the pts for
979        * checking when we need to send SPS/PPS but convert to running_time
980        * first */
981       rtph265pay->send_vps_sps_pps = FALSE;
982       sent_ps = TRUE;
983       GST_DEBUG_OBJECT (rtph265pay, "sending VPS/SPS/PPS before current frame");
984       ret =
985           gst_rtp_h265_pay_send_vps_sps_pps (basepayload, rtph265pay, dts, pts);
986       if (ret != GST_FLOW_OK) {
987         gst_buffer_unref (paybuf);
988         continue;
989       }
990     }
991
992     packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
993
994     if (packet_len < mtu) {
995       GST_DEBUG_OBJECT (rtph265pay,
996           "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
997       /* will fit in one packet */
998
999       /* use buffer lists
1000        * create buffer without payload containing only the RTP header
1001        * (memory block at index 0) */
1002       outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
1003
1004       gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1005
1006       /* Mark the end of a frame */
1007       gst_rtp_buffer_set_marker (&rtp, marker);
1008
1009       /* timestamp the outbuffer */
1010       GST_BUFFER_PTS (outbuf) = pts;
1011       GST_BUFFER_DTS (outbuf) = dts;
1012
1013       /* insert payload memory block */
1014       gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1015       outbuf = gst_buffer_append (outbuf, paybuf);
1016
1017       outlist = gst_buffer_list_new ();
1018
1019       /* add the buffer to the buffer list */
1020       gst_buffer_list_add (outlist, outbuf);
1021
1022       gst_rtp_buffer_unmap (&rtp);
1023
1024       /* push the list to the next element in the pipe */
1025       ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1026     } else {
1027       /* fragmentation Units */
1028       guint limitedSize;
1029       int ii = 0, start = 1, end = 0, pos = 0;
1030
1031       GST_DEBUG_OBJECT (basepayload,
1032           "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
1033
1034       pos += 2;
1035       size -= 2;
1036
1037       GST_DEBUG_OBJECT (basepayload, "Using FU fragmentation for data size=%d",
1038           size);
1039
1040       /* We keep 3 bytes for PayloadHdr and FU Header */
1041       payload_len = gst_rtp_buffer_calc_payload_len (mtu - 3, 0, 0);
1042
1043       outlist = gst_buffer_list_new ();
1044
1045       while (end == 0) {
1046         limitedSize = size < payload_len ? size : payload_len;
1047         GST_DEBUG_OBJECT (basepayload,
1048             "Inside  FU fragmentation limitedSize=%d iteration=%d", limitedSize,
1049             ii);
1050
1051         /* use buffer lists
1052          * create buffer without payload containing only the RTP header
1053          * (memory block at index 0), and with space for PayloadHdr and FU header */
1054         outbuf = gst_rtp_buffer_new_allocate (3, 0, 0);
1055
1056         gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1057
1058         GST_BUFFER_DTS (outbuf) = dts;
1059         GST_BUFFER_PTS (outbuf) = pts;
1060         payload = gst_rtp_buffer_get_payload (&rtp);
1061
1062         if (limitedSize == size) {
1063           GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
1064           end = 1;
1065         }
1066
1067         /* PayloadHdr (type = 49) */
1068         payload[0] = (nalHeader[0] & 0x81) | (49 << 1);
1069         payload[1] = nalHeader[1];
1070
1071         /* If it's the last fragment and the end of this au, mark the end of
1072          * slice */
1073         gst_rtp_buffer_set_marker (&rtp, marker);
1074
1075         /* FU Header */
1076         payload[2] = (start << 7) | (end << 6) | (nalType & 0x3f);
1077
1078         gst_rtp_buffer_unmap (&rtp);
1079
1080         /* insert payload memory block */
1081         gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1082         gst_buffer_copy_into (outbuf, paybuf, GST_BUFFER_COPY_MEMORY, pos,
1083             limitedSize);
1084         /* add the buffer to the buffer list */
1085         gst_buffer_list_add (outlist, outbuf);
1086
1087         size -= limitedSize;
1088         pos += limitedSize;
1089         ii++;
1090         start = 0;
1091       }
1092
1093       ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1094       gst_buffer_unref (paybuf);
1095     }
1096   }
1097
1098   g_ptr_array_free (paybufs, TRUE);
1099
1100   return ret;
1101 }
1102
1103 static GstFlowReturn
1104 gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * basepayload,
1105     GstBuffer * buffer)
1106 {
1107   GstRtpH265Pay *rtph265pay;
1108   GstFlowReturn ret;
1109   gsize size;
1110   guint nal_len, i;
1111   GstMapInfo map;
1112   const guint8 *data;
1113   GstClockTime dts, pts;
1114   GArray *nal_queue;
1115   gboolean hevc;
1116   GstBuffer *paybuf = NULL;
1117   gsize skip;
1118
1119   rtph265pay = GST_RTP_H265_PAY (basepayload);
1120
1121   /* the input buffer contains one or more NAL units */
1122
1123   hevc = (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HEV1)
1124       || (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HVC1);
1125
1126   if (hevc) {
1127     /* In hevc mode, there is no adapter, so nothing to flush */
1128     if (buffer == NULL)
1129       return GST_FLOW_OK;
1130     gst_buffer_map (buffer, &map, GST_MAP_READ);
1131     data = map.data;
1132     size = map.size;
1133     pts = GST_BUFFER_PTS (buffer);
1134     dts = GST_BUFFER_DTS (buffer);
1135     GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1136   } else {
1137     dts = gst_adapter_prev_dts (rtph265pay->adapter, NULL);
1138     pts = gst_adapter_prev_pts (rtph265pay->adapter, NULL);
1139     if (buffer) {
1140       if (!GST_CLOCK_TIME_IS_VALID (dts))
1141         dts = GST_BUFFER_DTS (buffer);
1142       if (!GST_CLOCK_TIME_IS_VALID (pts))
1143         pts = GST_BUFFER_PTS (buffer);
1144
1145       gst_adapter_push (rtph265pay->adapter, buffer);
1146     }
1147     size = gst_adapter_available (rtph265pay->adapter);
1148     /* Nothing to do here if the adapter is empty, e.g. on EOS */
1149     if (size == 0)
1150       return GST_FLOW_OK;
1151     data = gst_adapter_map (rtph265pay->adapter, size);
1152     GST_DEBUG_OBJECT (basepayload,
1153         "got %" G_GSIZE_FORMAT " bytes (%" G_GSIZE_FORMAT ")", size,
1154         buffer ? gst_buffer_get_size (buffer) : 0);
1155   }
1156
1157   ret = GST_FLOW_OK;
1158
1159   /* now loop over all NAL units and put them in a packet
1160    * FIXME, we should really try to pack multiple NAL units into one RTP packet
1161    * if we can, especially for the config packets that wont't cause decoder
1162    * latency. */
1163   if (hevc) {
1164     guint nal_length_size;
1165     gsize offset = 0;
1166     GPtrArray *paybufs;
1167
1168     paybufs = g_ptr_array_new ();
1169     nal_length_size = rtph265pay->nal_length_size;
1170
1171     while (size > nal_length_size) {
1172       gint i;
1173
1174       nal_len = 0;
1175       for (i = 0; i < nal_length_size; i++) {
1176         nal_len = ((nal_len << 8) + data[i]);
1177       }
1178
1179       /* skip the length bytes, make sure we don't run past the buffer size */
1180       data += nal_length_size;
1181       offset += nal_length_size;
1182       size -= nal_length_size;
1183
1184       if (size >= nal_len) {
1185         GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1186       } else {
1187         nal_len = size;
1188         GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1189             nal_len);
1190       }
1191
1192       paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1193           nal_len);
1194       g_ptr_array_add (paybufs, paybuf);
1195
1196       /* If we're at the end of the buffer, then we're at the end of the
1197        * access unit
1198        */
1199       GST_BUFFER_FLAG_UNSET (paybuf, GST_BUFFER_FLAG_MARKER);
1200       if (size - nal_len <= nal_length_size) {
1201         if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU ||
1202             GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER))
1203           GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1204       }
1205
1206       data += nal_len;
1207       offset += nal_len;
1208       size -= nal_len;
1209     }
1210     ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1211   } else {
1212     guint next;
1213     gboolean update = FALSE;
1214     GPtrArray *paybufs;
1215
1216     /* get offset of first start code */
1217     next = next_start_code (data, size);
1218
1219     /* skip to start code, if no start code is found, next will be size and we
1220      * will not collect data. */
1221     data += next;
1222     size -= next;
1223     nal_queue = rtph265pay->queue;
1224     skip = next;
1225
1226     /* array must be empty when we get here */
1227     g_assert (nal_queue->len == 0);
1228
1229     GST_DEBUG_OBJECT (basepayload,
1230         "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1231
1232     paybufs = g_ptr_array_new ();
1233
1234     /* first pass to locate NALs and parse VPS/SPS/PPS */
1235     while (size > 4) {
1236       /* skip start code */
1237       data += 3;
1238       size -= 3;
1239
1240       /* use next_start_code() to scan buffer.
1241        * next_start_code() returns the offset in data,
1242        * starting from zero to the first byte of 0.0.0.1
1243        * If no start code is found, it returns the value of the
1244        * 'size' parameter.
1245        * data is unchanged by the call to next_start_code()
1246        */
1247       next = next_start_code (data, size);
1248
1249       if (next == size && buffer != NULL) {
1250         /* Didn't find the start of next NAL and it's not EOS,
1251          * handle it next time */
1252         break;
1253       }
1254
1255       /* nal length is distance to next start code */
1256       nal_len = next;
1257
1258       GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1259           nal_len);
1260
1261       /* We know our stream is a valid H265 NAL packet,
1262        * go parse it for VPS/SPS/PPS to enrich the caps */
1263       /* order: make sure to check nal */
1264       update = gst_rtp_h265_pay_decode_nal (rtph265pay, data, nal_len, dts, pts)
1265           || update;
1266
1267       /* move to next NAL packet */
1268       data += nal_len;
1269       size -= nal_len;
1270
1271       g_array_append_val (nal_queue, nal_len);
1272     }
1273
1274     /* if has new VPS, SPS & PPS, update the output caps */
1275     if (G_UNLIKELY (update))
1276       if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
1277         goto caps_rejected;
1278
1279     /* second pass to payload and push */
1280
1281     if (nal_queue->len != 0)
1282       gst_adapter_flush (rtph265pay->adapter, skip);
1283
1284     for (i = 0; i < nal_queue->len; i++) {
1285       guint size;
1286
1287       nal_len = g_array_index (nal_queue, guint, i);
1288       /* skip start code */
1289       gst_adapter_flush (rtph265pay->adapter, 3);
1290
1291       /* Trim the end unless we're the last NAL in the stream.
1292        * In case we're not at the end of the buffer we know the next block
1293        * starts with 0x000001 so all the 0x00 bytes at the end of this one are
1294        * trailing 0x0 that can be discarded */
1295       size = nal_len;
1296       data = gst_adapter_map (rtph265pay->adapter, size);
1297       if (i + 1 != nal_queue->len || buffer != NULL)
1298         for (; size > 1 && data[size - 1] == 0x0; size--)
1299           /* skip */ ;
1300
1301       paybuf = gst_adapter_take_buffer (rtph265pay->adapter, size);
1302       g_assert (paybuf);
1303       g_ptr_array_add (paybufs, paybuf);
1304
1305       /* If it's the last nal unit we have in non-bytestream mode, we can
1306        * assume it's the end of an access-unit */
1307       GST_BUFFER_FLAG_UNSET (paybuf, GST_BUFFER_FLAG_MARKER);
1308       if (i == nal_queue->len - 1) {
1309         if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU ||
1310             buffer == NULL ||
1311             GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER))
1312           GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1313       }
1314
1315       /* move to next NAL packet */
1316       /* Skips the trailing zeros */
1317       gst_adapter_flush (rtph265pay->adapter, nal_len - size);
1318     }
1319     /* put the data in one or more RTP packets */
1320     ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1321     g_array_set_size (nal_queue, 0);
1322   }
1323
1324 done:
1325   if (hevc) {
1326     gst_buffer_unmap (buffer, &map);
1327     gst_buffer_unref (buffer);
1328   } else {
1329     gst_adapter_unmap (rtph265pay->adapter);
1330   }
1331
1332   return ret;
1333
1334 caps_rejected:
1335   {
1336     GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1337     g_array_set_size (nal_queue, 0);
1338     ret = GST_FLOW_NOT_NEGOTIATED;
1339     goto done;
1340   }
1341 }
1342
1343 static gboolean
1344 gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1345 {
1346   gboolean res;
1347   const GstStructure *s;
1348   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (payload);
1349
1350   switch (GST_EVENT_TYPE (event)) {
1351     case GST_EVENT_FLUSH_STOP:
1352       gst_adapter_clear (rtph265pay->adapter);
1353       break;
1354     case GST_EVENT_CUSTOM_DOWNSTREAM:
1355       s = gst_event_get_structure (event);
1356       if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1357         gboolean resend_codec_data;
1358
1359         if (gst_structure_get_boolean (s, "all-headers",
1360                 &resend_codec_data) && resend_codec_data)
1361           rtph265pay->send_vps_sps_pps = TRUE;
1362       }
1363       break;
1364     case GST_EVENT_EOS:
1365     {
1366       /* call handle_buffer with NULL to flush last NAL from adapter
1367        * in byte-stream mode
1368        */
1369       gst_rtp_h265_pay_handle_buffer (payload, NULL);
1370       break;
1371     }
1372     case GST_EVENT_STREAM_START:
1373       GST_DEBUG_OBJECT (rtph265pay,
1374           "New stream detected => Clear VPS, SPS and PPS");
1375       gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1376       break;
1377     default:
1378       break;
1379   }
1380
1381   res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1382
1383   return res;
1384 }
1385
1386 static GstStateChangeReturn
1387 gst_rtp_h265_pay_change_state (GstElement * element, GstStateChange transition)
1388 {
1389   GstStateChangeReturn ret;
1390   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (element);
1391
1392   switch (transition) {
1393     case GST_STATE_CHANGE_READY_TO_PAUSED:
1394       rtph265pay->send_vps_sps_pps = FALSE;
1395       gst_adapter_clear (rtph265pay->adapter);
1396       break;
1397     default:
1398       break;
1399   }
1400
1401   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1402
1403   switch (transition) {
1404     case GST_STATE_CHANGE_PAUSED_TO_READY:
1405       rtph265pay->last_vps_sps_pps = -1;
1406       gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1407       break;
1408     default:
1409       break;
1410   }
1411
1412   return ret;
1413 }
1414
1415 static void
1416 gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
1417     const GValue * value, GParamSpec * pspec)
1418 {
1419   GstRtpH265Pay *rtph265pay;
1420
1421   rtph265pay = GST_RTP_H265_PAY (object);
1422
1423   switch (prop_id) {
1424     case PROP_CONFIG_INTERVAL:
1425       rtph265pay->vps_sps_pps_interval = g_value_get_int (value);
1426       break;
1427     default:
1428       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1429       break;
1430   }
1431 }
1432
1433 static void
1434 gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
1435     GValue * value, GParamSpec * pspec)
1436 {
1437   GstRtpH265Pay *rtph265pay;
1438
1439   rtph265pay = GST_RTP_H265_PAY (object);
1440
1441   switch (prop_id) {
1442     case PROP_CONFIG_INTERVAL:
1443       g_value_set_int (value, rtph265pay->vps_sps_pps_interval);
1444       break;
1445     default:
1446       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1447       break;
1448   }
1449 }
1450
1451 gboolean
1452 gst_rtp_h265_pay_plugin_init (GstPlugin * plugin)
1453 {
1454   return gst_element_register (plugin, "rtph265pay",
1455       GST_RANK_SECONDARY, GST_TYPE_RTP_H265_PAY);
1456 }