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