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