rtp: h265: use common meta utility functions
[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_pad_template (gstelement_class,
174       gst_static_pad_template_get (&gst_rtp_h265_pay_src_template));
175   gst_element_class_add_pad_template (gstelement_class,
176       gst_static_pad_template_get (&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 header, type;
817   gboolean updated;
818
819   /* default is no update */
820   updated = FALSE;
821
822   GST_DEBUG ("NAL payload len=%u", size);
823
824   header = data[0];
825   type = header & 0x3f;
826
827   /* We record the timestamp of the last SPS/PPS so
828    * that we can insert them at regular intervals and when needed. */
829   if (GST_H265_NAL_VPS == type || GST_H265_NAL_SPS == type
830       || GST_H265_NAL_PPS == type) {
831     GstBuffer *nal;
832
833     /* encode the entire NAL in base64 */
834     GST_DEBUG ("Found %s %x %x %x Len=%u",
835         type == GST_H265_NAL_VPS ? "VPS" : type ==
836         GST_H265_NAL_SPS ? "SPS" : "PPS", (header >> 7), (header >> 5) & 3,
837         type, size);
838
839     nal = gst_buffer_new_allocate (NULL, size, NULL);
840     gst_buffer_fill (nal, 0, data, size);
841
842     updated = gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (payloader),
843         payloader->vps, payloader->sps, payloader->pps, nal);
844
845     /* remember when we last saw VPS */
846     if (updated && pts != -1)
847       payloader->last_vps_sps_pps = pts;
848   } else {
849     GST_DEBUG ("NAL: %x %x %x Len = %u", (header >> 7),
850         (header >> 5) & 3, type, size);
851   }
852
853   return updated;
854 }
855
856 static GstFlowReturn
857 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
858     GstBuffer * paybuf, GstClockTime dts, GstClockTime pts, gboolean end_of_au);
859
860 static GstFlowReturn
861 gst_rtp_h265_pay_send_vps_sps_pps (GstRTPBasePayload * basepayload,
862     GstRtpH265Pay * rtph265pay, GstClockTime dts, GstClockTime pts)
863 {
864   GstFlowReturn ret = GST_FLOW_OK;
865   gboolean sent_all_vps_sps_pps = TRUE;
866   guint i;
867
868   for (i = 0; i < rtph265pay->vps->len; i++) {
869     GstBuffer *vps_buf =
870         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->vps, i));
871
872     GST_DEBUG_OBJECT (rtph265pay, "inserting VPS in the stream");
873     /* resend VPS */
874     ret = gst_rtp_h265_pay_payload_nal (basepayload, gst_buffer_ref (vps_buf),
875         dts, pts, FALSE);
876     /* Not critical here; but throw a warning */
877     if (ret != GST_FLOW_OK) {
878       sent_all_vps_sps_pps = FALSE;
879       GST_WARNING_OBJECT (basepayload, "Problem pushing VPS");
880     }
881   }
882   for (i = 0; i < rtph265pay->sps->len; i++) {
883     GstBuffer *sps_buf =
884         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->sps, i));
885
886     GST_DEBUG_OBJECT (rtph265pay, "inserting SPS in the stream");
887     /* resend SPS */
888     ret = gst_rtp_h265_pay_payload_nal (basepayload, gst_buffer_ref (sps_buf),
889         dts, pts, FALSE);
890     /* Not critical here; but throw a warning */
891     if (ret != GST_FLOW_OK) {
892       sent_all_vps_sps_pps = FALSE;
893       GST_WARNING_OBJECT (basepayload, "Problem pushing SPS");
894     }
895   }
896   for (i = 0; i < rtph265pay->pps->len; i++) {
897     GstBuffer *pps_buf =
898         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->pps, i));
899
900     GST_DEBUG_OBJECT (rtph265pay, "inserting PPS in the stream");
901     /* resend PPS */
902     ret = gst_rtp_h265_pay_payload_nal (basepayload, gst_buffer_ref (pps_buf),
903         dts, pts, FALSE);
904     /* Not critical here; but throw a warning */
905     if (ret != GST_FLOW_OK) {
906       sent_all_vps_sps_pps = FALSE;
907       GST_WARNING ("Problem pushing PPS");
908     }
909   }
910
911   if (pts != -1 && sent_all_vps_sps_pps)
912     rtph265pay->last_vps_sps_pps = pts;
913
914   return ret;
915 }
916
917 static GstFlowReturn
918 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
919     GstBuffer * paybuf, GstClockTime dts, GstClockTime pts, gboolean end_of_au)
920 {
921   GstRtpH265Pay *rtph265pay;
922   GstFlowReturn ret;
923   guint8 nalHeader[2];
924   guint8 nalType;
925   guint packet_len, payload_len, mtu;
926   GstBuffer *outbuf;
927   guint8 *payload;
928   GstBufferList *list = NULL;
929   gboolean send_vps_sps_pps;
930   GstRTPBuffer rtp = { NULL };
931   guint size = gst_buffer_get_size (paybuf);
932
933   rtph265pay = GST_RTP_H265_PAY (basepayload);
934   mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph265pay);
935
936   gst_buffer_extract (paybuf, 0, nalHeader, 2);
937   nalType = (nalHeader[0] >> 1) & 0x3f;
938
939   GST_DEBUG_OBJECT (rtph265pay, "Processing Buffer with NAL TYPE=%d", nalType);
940
941   /* should set src caps before pushing stuff,
942    * and if we did not see enough VPS/SPS/PPS, that may not be the case */
943   if (G_UNLIKELY (!gst_pad_has_current_caps (GST_RTP_BASE_PAYLOAD_SRCPAD
944               (basepayload))))
945     gst_rtp_h265_pay_set_vps_sps_pps (basepayload);
946
947   send_vps_sps_pps = FALSE;
948
949   /* check if we need to emit an VPS/SPS/PPS now */
950   if ((nalType == GST_H265_NAL_SLICE_TRAIL_N)
951       || (nalType == GST_H265_NAL_SLICE_TRAIL_R)
952       || (nalType == GST_H265_NAL_SLICE_TSA_N)
953       || (nalType == GST_H265_NAL_SLICE_TSA_R)
954       || (nalType == GST_H265_NAL_SLICE_STSA_N)
955       || (nalType == GST_H265_NAL_SLICE_STSA_R)
956       || (nalType == GST_H265_NAL_SLICE_RASL_N)
957       || (nalType == GST_H265_NAL_SLICE_RASL_R)
958       || (nalType == GST_H265_NAL_SLICE_BLA_W_LP)
959       || (nalType == GST_H265_NAL_SLICE_BLA_W_RADL)
960       || (nalType == GST_H265_NAL_SLICE_BLA_N_LP)
961       || (nalType == GST_H265_NAL_SLICE_IDR_W_RADL)
962       || (nalType == GST_H265_NAL_SLICE_IDR_N_LP)
963       || (nalType == GST_H265_NAL_SLICE_CRA_NUT)) {
964     if (rtph265pay->vps_sps_pps_interval > 0) {
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     } else if (rtph265pay->vps_sps_pps_interval == -1) {
993       GST_DEBUG_OBJECT (rtph265pay,
994           "sending VPS/SPS/PPS before current IDR frame");
995       /* send VPS/SPS/PPS before every IDR frame */
996       send_vps_sps_pps = TRUE;
997     }
998   }
999
1000   if (send_vps_sps_pps || rtph265pay->send_vps_sps_pps) {
1001     /* we need to send SPS/PPS now first. FIXME, don't use the pts for
1002      * checking when we need to send SPS/PPS but convert to running_time first. */
1003     rtph265pay->send_vps_sps_pps = FALSE;
1004     ret = gst_rtp_h265_pay_send_vps_sps_pps (basepayload, rtph265pay, dts, pts);
1005     if (ret != GST_FLOW_OK) {
1006       gst_buffer_unref (paybuf);
1007       return ret;
1008     }
1009   }
1010
1011   packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
1012
1013   GST_FIXME_OBJECT (rtph265pay, "Set RTP marker bit appropriately");
1014
1015   if (packet_len < mtu) {
1016     GST_DEBUG_OBJECT (rtph265pay,
1017         "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
1018     /* will fit in one packet */
1019
1020     /* use buffer lists
1021      * create buffer without payload containing only the RTP header
1022      * (memory block at index 0) */
1023     outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
1024
1025     gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1026
1027     /* FIXME : only set the marker bit on packets containing access units */
1028     /* if (IS_ACCESS_UNIT (nalType) && end_of_au) {
1029        gst_rtp_buffer_set_marker (&rtp, 1);
1030        } */
1031
1032     /* timestamp the outbuffer */
1033     GST_BUFFER_PTS (outbuf) = pts;
1034     GST_BUFFER_DTS (outbuf) = dts;
1035
1036     /* insert payload memory block */
1037     gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265pay), outbuf, paybuf,
1038         g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1039     outbuf = gst_buffer_append (outbuf, paybuf);
1040
1041     list = gst_buffer_list_new ();
1042
1043     /* add the buffer to the buffer list */
1044     gst_buffer_list_add (list, outbuf);
1045
1046     gst_rtp_buffer_unmap (&rtp);
1047
1048     /* push the list to the next element in the pipe */
1049     ret = gst_rtp_base_payload_push_list (basepayload, list);
1050   } else {
1051     /* fragmentation Units */
1052     guint limitedSize;
1053     int ii = 0, start = 1, end = 0, pos = 0;
1054
1055     GST_DEBUG_OBJECT (basepayload,
1056         "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
1057
1058     pos += 2;
1059     size -= 2;
1060
1061     GST_DEBUG_OBJECT (basepayload, "Using FU fragmentation for data size=%d",
1062         size);
1063
1064     /* We keep 3 bytes for PayloadHdr and FU Header */
1065     payload_len = gst_rtp_buffer_calc_payload_len (mtu - 3, 0, 0);
1066
1067     list = gst_buffer_list_new ();
1068
1069     while (end == 0) {
1070       limitedSize = size < payload_len ? size : payload_len;
1071       GST_DEBUG_OBJECT (basepayload,
1072           "Inside  FU fragmentation limitedSize=%d iteration=%d", limitedSize,
1073           ii);
1074
1075       /* use buffer lists
1076        * create buffer without payload containing only the RTP header
1077        * (memory block at index 0), and with space for PayloadHdr and FU header */
1078       outbuf = gst_rtp_buffer_new_allocate (3, 0, 0);
1079
1080       gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1081
1082       GST_BUFFER_DTS (outbuf) = dts;
1083       GST_BUFFER_PTS (outbuf) = pts;
1084       payload = gst_rtp_buffer_get_payload (&rtp);
1085
1086       if (limitedSize == size) {
1087         GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
1088         end = 1;
1089       }
1090
1091       /* PayloadHdr (type = 49) */
1092       payload[0] = (nalHeader[0] & 0x81) | (49 << 1);
1093       payload[1] = nalHeader[1];
1094
1095       /* FIXME - set RTP marker bit appropriately */
1096       /* if (IS_ACCESS_UNIT (nalType)) {
1097          gst_rtp_buffer_set_marker (&rtp, end && end_of_au);
1098          } */
1099
1100       /* FU Header */
1101       payload[2] = (start << 7) | (end << 6) | (nalType & 0x3f);
1102
1103       gst_rtp_buffer_unmap (&rtp);
1104
1105       /* insert payload memory block */
1106       gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265pay), outbuf, paybuf,
1107           g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
1108       gst_buffer_copy_into (outbuf, paybuf, GST_BUFFER_COPY_MEMORY, pos,
1109           limitedSize);
1110       /* add the buffer to the buffer list */
1111       gst_buffer_list_add (list, outbuf);
1112
1113       size -= limitedSize;
1114       pos += limitedSize;
1115       ii++;
1116       start = 0;
1117     }
1118
1119     ret = gst_rtp_base_payload_push_list (basepayload, list);
1120     gst_buffer_unref (paybuf);
1121   }
1122   return ret;
1123 }
1124
1125 static GstFlowReturn
1126 gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * basepayload,
1127     GstBuffer * buffer)
1128 {
1129   GstRtpH265Pay *rtph265pay;
1130   GstFlowReturn ret;
1131   gsize size;
1132   guint nal_len, i;
1133   GstMapInfo map;
1134   const guint8 *data;
1135   GstClockTime dts, pts;
1136   GArray *nal_queue;
1137   gboolean hevc;
1138   GstBuffer *paybuf = NULL;
1139   gsize skip;
1140
1141   rtph265pay = GST_RTP_H265_PAY (basepayload);
1142
1143   /* the input buffer contains one or more NAL units */
1144
1145   hevc = (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HEV1)
1146       || (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HVC1);
1147
1148   if (hevc) {
1149     /* In hevc mode, there is no adapter, so nothing to flush */
1150     if (buffer == NULL)
1151       return GST_FLOW_OK;
1152     gst_buffer_map (buffer, &map, GST_MAP_READ);
1153     data = map.data;
1154     size = map.size;
1155     pts = GST_BUFFER_PTS (buffer);
1156     dts = GST_BUFFER_DTS (buffer);
1157     GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1158   } else {
1159     dts = gst_adapter_prev_dts (rtph265pay->adapter, NULL);
1160     pts = gst_adapter_prev_pts (rtph265pay->adapter, NULL);
1161     if (buffer) {
1162       if (!GST_CLOCK_TIME_IS_VALID (dts))
1163         dts = GST_BUFFER_DTS (buffer);
1164       if (!GST_CLOCK_TIME_IS_VALID (pts))
1165         pts = GST_BUFFER_PTS (buffer);
1166
1167       gst_adapter_push (rtph265pay->adapter, buffer);
1168     }
1169     size = gst_adapter_available (rtph265pay->adapter);
1170     /* Nothing to do here if the adapter is empty, e.g. on EOS */
1171     if (size == 0)
1172       return GST_FLOW_OK;
1173     data = gst_adapter_map (rtph265pay->adapter, size);
1174     GST_DEBUG_OBJECT (basepayload,
1175         "got %" G_GSIZE_FORMAT " bytes (%" G_GSIZE_FORMAT ")", size,
1176         buffer ? gst_buffer_get_size (buffer) : 0);
1177   }
1178
1179   ret = GST_FLOW_OK;
1180
1181   /* now loop over all NAL units and put them in a packet
1182    * FIXME, we should really try to pack multiple NAL units into one RTP packet
1183    * if we can, especially for the config packets that wont't cause decoder
1184    * latency. */
1185   if (hevc) {
1186     guint nal_length_size;
1187     gsize offset = 0;
1188
1189     nal_length_size = rtph265pay->nal_length_size;
1190
1191     while (size > nal_length_size) {
1192       gint i;
1193       gboolean end_of_au = FALSE;
1194
1195       nal_len = 0;
1196       for (i = 0; i < nal_length_size; i++) {
1197         nal_len = ((nal_len << 8) + data[i]);
1198       }
1199
1200       /* skip the length bytes, make sure we don't run past the buffer size */
1201       data += nal_length_size;
1202       offset += nal_length_size;
1203       size -= nal_length_size;
1204
1205       if (size >= nal_len) {
1206         GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1207       } else {
1208         nal_len = size;
1209         GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1210             nal_len);
1211       }
1212
1213       /* If we're at the end of the buffer, then we're at the end of the
1214        * access unit
1215        */
1216       if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU
1217           && size - nal_len <= nal_length_size) {
1218         end_of_au = TRUE;
1219       }
1220
1221       paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1222           nal_len);
1223
1224       ret =
1225           gst_rtp_h265_pay_payload_nal (basepayload, paybuf, dts, pts,
1226           end_of_au);
1227       if (ret != GST_FLOW_OK)
1228         break;
1229
1230       data += nal_len;
1231       offset += nal_len;
1232       size -= nal_len;
1233     }
1234   } else {
1235     guint next;
1236     gboolean update = FALSE;
1237
1238     /* get offset of first start code */
1239     next = next_start_code (data, size);
1240
1241     /* skip to start code, if no start code is found, next will be size and we
1242      * will not collect data. */
1243     data += next;
1244     size -= next;
1245     nal_queue = rtph265pay->queue;
1246     skip = next;
1247
1248     /* array must be empty when we get here */
1249     g_assert (nal_queue->len == 0);
1250
1251     GST_DEBUG_OBJECT (basepayload,
1252         "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1253
1254     /* first pass to locate NALs and parse SPS/PPS */
1255     while (size > 4) {
1256       /* skip start code */
1257       data += 3;
1258       size -= 3;
1259
1260       /* use next_start_code() to scan buffer.
1261        * next_start_code() returns the offset in data,
1262        * starting from zero to the first byte of 0.0.0.1
1263        * If no start code is found, it returns the value of the
1264        * 'size' parameter.
1265        * data is unchanged by the call to next_start_code()
1266        */
1267       next = next_start_code (data, size);
1268
1269       if (next == size && buffer != NULL) {
1270         /* Didn't find the start of next NAL and it's not EOS,
1271          * handle it next time */
1272         break;
1273       }
1274
1275       /* nal length is distance to next start code */
1276       nal_len = next;
1277
1278       GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1279           nal_len);
1280
1281       if (rtph265pay->sprop_parameter_sets != NULL) {
1282         /* explicitly set profile and sprop, use those */
1283         if (rtph265pay->update_caps) {
1284           if (!gst_rtp_base_payload_set_outcaps (basepayload,
1285                   "sprop-parameter-sets", G_TYPE_STRING,
1286                   rtph265pay->sprop_parameter_sets, NULL))
1287             goto caps_rejected;
1288
1289           /* parse SPS and PPS from provided parameter set (for insertion) */
1290           gst_rtp_h265_pay_parse_sprop_parameter_sets (rtph265pay);
1291
1292           rtph265pay->update_caps = FALSE;
1293
1294           GST_DEBUG ("outcaps update: sprop-parameter-sets=%s",
1295               rtph265pay->sprop_parameter_sets);
1296         }
1297       } else {
1298         /* We know our stream is a valid H265 NAL packet,
1299          * go parse it for SPS/PPS to enrich the caps */
1300         /* order: make sure to check nal */
1301         update =
1302             gst_rtp_h265_pay_decode_nal (rtph265pay, data, nal_len, dts, pts)
1303             || update;
1304       }
1305       /* move to next NAL packet */
1306       data += nal_len;
1307       size -= nal_len;
1308
1309       g_array_append_val (nal_queue, nal_len);
1310     }
1311
1312     /* if has new VPS, SPS & PPS, update the output caps */
1313     if (G_UNLIKELY (update))
1314       if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
1315         goto caps_rejected;
1316
1317     /* second pass to payload and push */
1318
1319     if (nal_queue->len != 0)
1320       gst_adapter_flush (rtph265pay->adapter, skip);
1321
1322     for (i = 0; i < nal_queue->len; i++) {
1323       guint size;
1324       gboolean end_of_au = FALSE;
1325
1326       nal_len = g_array_index (nal_queue, guint, i);
1327       /* skip start code */
1328       gst_adapter_flush (rtph265pay->adapter, 3);
1329
1330       /* Trim the end unless we're the last NAL in the stream.
1331        * In case we're not at the end of the buffer we know the next block
1332        * starts with 0x000001 so all the 0x00 bytes at the end of this one are
1333        * trailing 0x0 that can be discarded */
1334       size = nal_len;
1335       data = gst_adapter_map (rtph265pay->adapter, size);
1336       if (i + 1 != nal_queue->len || buffer != NULL)
1337         for (; size > 1 && data[size - 1] == 0x0; size--)
1338           /* skip */ ;
1339
1340
1341       /* If it's the last nal unit we have in non-bytestream mode, we can
1342        * assume it's the end of an access-unit
1343        *
1344        * FIXME: We need to wait until the next packet or EOS to
1345        * actually payload the NAL so we can know if the current NAL is
1346        * the last one of an access unit or not if we are in bytestream mode
1347        */
1348       if ((rtph265pay->alignment == GST_H265_ALIGNMENT_AU || buffer == NULL) &&
1349           i == nal_queue->len - 1)
1350         end_of_au = TRUE;
1351       paybuf = gst_adapter_take_buffer (rtph265pay->adapter, size);
1352       g_assert (paybuf);
1353
1354       /* put the data in one or more RTP packets */
1355       ret =
1356           gst_rtp_h265_pay_payload_nal (basepayload, paybuf, dts, pts,
1357           end_of_au);
1358       if (ret != GST_FLOW_OK) {
1359         break;
1360       }
1361
1362       /* move to next NAL packet */
1363       /* Skips the trailing zeros */
1364       gst_adapter_flush (rtph265pay->adapter, nal_len - size);
1365     }
1366     g_array_set_size (nal_queue, 0);
1367   }
1368
1369 done:
1370   if (hevc) {
1371     gst_buffer_unmap (buffer, &map);
1372     gst_buffer_unref (buffer);
1373   } else {
1374     gst_adapter_unmap (rtph265pay->adapter);
1375   }
1376
1377   return ret;
1378
1379 caps_rejected:
1380   {
1381     GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1382     g_array_set_size (nal_queue, 0);
1383     ret = GST_FLOW_NOT_NEGOTIATED;
1384     goto done;
1385   }
1386 }
1387
1388 static gboolean
1389 gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1390 {
1391   gboolean res;
1392   const GstStructure *s;
1393   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (payload);
1394
1395   switch (GST_EVENT_TYPE (event)) {
1396     case GST_EVENT_FLUSH_STOP:
1397       gst_adapter_clear (rtph265pay->adapter);
1398       break;
1399     case GST_EVENT_CUSTOM_DOWNSTREAM:
1400       s = gst_event_get_structure (event);
1401       if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1402         gboolean resend_codec_data;
1403
1404         if (gst_structure_get_boolean (s, "all-headers",
1405                 &resend_codec_data) && resend_codec_data)
1406           rtph265pay->send_vps_sps_pps = TRUE;
1407       }
1408       break;
1409     case GST_EVENT_EOS:
1410     {
1411       /* call handle_buffer with NULL to flush last NAL from adapter
1412        * in byte-stream mode
1413        */
1414       gst_rtp_h265_pay_handle_buffer (payload, NULL);
1415       break;
1416     }
1417     case GST_EVENT_STREAM_START:
1418       GST_DEBUG_OBJECT (rtph265pay,
1419           "New stream detected => Clear VPS, SPS and PPS");
1420       gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1421       break;
1422     default:
1423       break;
1424   }
1425
1426   res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1427
1428   return res;
1429 }
1430
1431 static GstStateChangeReturn
1432 gst_rtp_h265_pay_change_state (GstElement * element, GstStateChange transition)
1433 {
1434   GstStateChangeReturn ret;
1435   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (element);
1436
1437   switch (transition) {
1438     case GST_STATE_CHANGE_READY_TO_PAUSED:
1439       rtph265pay->send_vps_sps_pps = FALSE;
1440       gst_adapter_clear (rtph265pay->adapter);
1441       break;
1442     default:
1443       break;
1444   }
1445
1446   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1447
1448   switch (transition) {
1449     case GST_STATE_CHANGE_PAUSED_TO_READY:
1450       rtph265pay->last_vps_sps_pps = -1;
1451       gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1452       break;
1453     default:
1454       break;
1455   }
1456
1457   return ret;
1458 }
1459
1460 static void
1461 gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
1462     const GValue * value, GParamSpec * pspec)
1463 {
1464   GstRtpH265Pay *rtph265pay;
1465
1466   rtph265pay = GST_RTP_H265_PAY (object);
1467
1468   switch (prop_id) {
1469     case PROP_SPROP_PARAMETER_SETS:
1470       g_free (rtph265pay->sprop_parameter_sets);
1471       rtph265pay->sprop_parameter_sets = g_value_dup_string (value);
1472       rtph265pay->update_caps = TRUE;
1473       break;
1474     case PROP_CONFIG_INTERVAL:
1475       rtph265pay->vps_sps_pps_interval = g_value_get_int (value);
1476       break;
1477     default:
1478       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1479       break;
1480   }
1481 }
1482
1483 static void
1484 gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
1485     GValue * value, GParamSpec * pspec)
1486 {
1487   GstRtpH265Pay *rtph265pay;
1488
1489   rtph265pay = GST_RTP_H265_PAY (object);
1490
1491   switch (prop_id) {
1492     case PROP_SPROP_PARAMETER_SETS:
1493       g_value_set_string (value, rtph265pay->sprop_parameter_sets);
1494       break;
1495     case PROP_CONFIG_INTERVAL:
1496       g_value_set_int (value, rtph265pay->vps_sps_pps_interval);
1497       break;
1498     default:
1499       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1500       break;
1501   }
1502 }
1503
1504 gboolean
1505 gst_rtp_h265_pay_plugin_init (GstPlugin * plugin)
1506 {
1507   return gst_element_register (plugin, "rtph265pay",
1508       GST_RANK_SECONDARY, GST_TYPE_RTP_H265_PAY);
1509 }