2 * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com>
3 * Copyright (C) <2014> Jurgen Slowack <jurgenslowack@gmail.com>
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.
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.
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.
28 #include <gst/rtp/gstrtpbuffer.h>
29 #include <gst/pbutils/pbutils.h>
30 #include <gst/video/video.h>
32 /* Included to not duplicate gst_rtp_h265_add_vps_sps_pps () */
33 #include "gstrtph265depay.h"
35 #include "gstrtph265pay.h"
36 #include "gstrtputils.h"
38 GST_DEBUG_CATEGORY_STATIC (rtph265pay_debug);
39 #define GST_CAT_DEFAULT (rtph265pay_debug)
43 * Internet Draft RTP Payload Format for High Efficiency Video Coding
45 * draft-ietf-payload-rtp-h265-03.txt
47 * This draft will be replaced with an RFC, so some details may change.
51 static GstStaticPadTemplate gst_rtp_h265_pay_sink_template =
52 GST_STATIC_PAD_TEMPLATE ("sink",
56 /* only hvc1 and byte-stream formats supported for now */
57 "video/x-h265, stream-format = (string) hvc1, alignment = (string) au; "
59 "stream-format = (string) hev1, alignment = (string) au; " */
60 "video/x-h265, stream-format = (string) byte-stream, "
61 "alignment = (string) { nal, au }")
64 static GstStaticPadTemplate gst_rtp_h265_pay_src_template =
65 GST_STATIC_PAD_TEMPLATE ("src",
68 GST_STATIC_CAPS ("application/x-rtp, "
69 "media = (string) \"video\", "
70 "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
71 "clock-rate = (int) 90000, " "encoding-name = (string) \"H265\"")
72 /** optional parameters **/
73 /* "profile-space = (int) [ 0, 3 ], " */
74 /* "profile-id = (int) [ 0, 31 ], " */
75 /* "tier-flag = (int) [ 0, 1 ], " */
76 /* "level-id = (int) [ 0, 255 ], " */
77 /* "interop-constraints = (string) ANY, " */
78 /* "profile-compatibility-indicator = (string) ANY, " */
79 /* "sprop-sub-layer-id = (int) [ 0, 6 ], " */
80 /* "recv-sub-layer-id = (int) [ 0, 6 ], " */
81 /* "max-recv-level-id = (int) [ 0, 255 ], " */
82 /* "tx-mode = (string) {MST , SST}, " */
83 /* "sprop-vps = (string) ANY, " */
84 /* "sprop-sps = (string) ANY, " */
85 /* "sprop-pps = (string) ANY, " */
86 /* "sprop-sei = (string) ANY, " */
87 /* "max-lsr = (int) ANY, " *//* MUST be in the range of MaxLumaSR to 16 * MaxLumaSR, inclusive */
88 /* "max-lps = (int) ANY, " *//* MUST be in the range of MaxLumaPS to 16 * MaxLumaPS, inclusive */
89 /* "max-cpb = (int) ANY, " *//* MUST be in the range of MaxCPB to 16 * MaxCPB, inclusive */
90 /* "max-dpb = (int) [1, 16], " */
91 /* "max-br = (int) ANY, " *//* MUST be in the range of MaxBR to 16 * MaxBR, inclusive, for the highest level */
92 /* "max-tr = (int) ANY, " *//* MUST be in the range of MaxTileRows to 16 * MaxTileRows, inclusive, for the highest level */
93 /* "max-tc = (int) ANY, " *//* MUST be in the range of MaxTileCols to 16 * MaxTileCols, inclusive, for the highest level */
94 /* "max-fps = (int) ANY, " */
95 /* "sprop-max-don-diff = (int) [0, 32767], " */
96 /* "sprop-depack-buf-nalus = (int) [0, 32767], " */
97 /* "sprop-depack-buf-nalus = (int) [0, 4294967295], " */
98 /* "depack-buf-cap = (int) [1, 4294967295], " */
99 /* "sprop-segmentation-id = (int) [0, 3], " */
100 /* "sprop-spatial-segmentation-idc = (string) ANY, " */
101 /* "dec-parallel-cap = (string) ANY, " */
104 #define DEFAULT_CONFIG_INTERVAL 0
112 static void gst_rtp_h265_pay_finalize (GObject * object);
114 static void gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
115 const GValue * value, GParamSpec * pspec);
116 static void gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
117 GValue * value, GParamSpec * pspec);
119 static GstCaps *gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload,
120 GstPad * pad, GstCaps * filter);
121 static gboolean gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload,
123 static GstFlowReturn gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * pad,
125 static gboolean gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload,
127 static GstStateChangeReturn gst_rtp_h265_pay_change_state (GstElement *
128 element, GstStateChange transition);
130 #define gst_rtp_h265_pay_parent_class parent_class
131 G_DEFINE_TYPE (GstRtpH265Pay, gst_rtp_h265_pay, GST_TYPE_RTP_BASE_PAYLOAD);
134 gst_rtp_h265_pay_class_init (GstRtpH265PayClass * klass)
136 GObjectClass *gobject_class;
137 GstElementClass *gstelement_class;
138 GstRTPBasePayloadClass *gstrtpbasepayload_class;
140 gobject_class = (GObjectClass *) klass;
141 gstelement_class = (GstElementClass *) klass;
142 gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
144 gobject_class->set_property = gst_rtp_h265_pay_set_property;
145 gobject_class->get_property = gst_rtp_h265_pay_get_property;
147 g_object_class_install_property (G_OBJECT_CLASS (klass),
148 PROP_CONFIG_INTERVAL,
149 g_param_spec_int ("config-interval",
150 "VPS SPS PPS Send Interval",
151 "Send VPS, SPS and PPS Insertion Interval in seconds (sprop parameter sets "
152 "will be multiplexed in the data stream when detected.) "
153 "(0 = disabled, -1 = send with every IDR frame)",
154 -1, 3600, DEFAULT_CONFIG_INTERVAL,
155 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
158 gobject_class->finalize = gst_rtp_h265_pay_finalize;
160 gst_element_class_add_static_pad_template (gstelement_class,
161 &gst_rtp_h265_pay_src_template);
162 gst_element_class_add_static_pad_template (gstelement_class,
163 &gst_rtp_h265_pay_sink_template);
165 gst_element_class_set_static_metadata (gstelement_class, "RTP H265 payloader",
166 "Codec/Payloader/Network/RTP",
167 "Payload-encode H265 video into RTP packets (RFC 7798)",
168 "Jurgen Slowack <jurgenslowack@gmail.com>");
170 gstelement_class->change_state =
171 GST_DEBUG_FUNCPTR (gst_rtp_h265_pay_change_state);
173 gstrtpbasepayload_class->get_caps = gst_rtp_h265_pay_getcaps;
174 gstrtpbasepayload_class->set_caps = gst_rtp_h265_pay_setcaps;
175 gstrtpbasepayload_class->handle_buffer = gst_rtp_h265_pay_handle_buffer;
176 gstrtpbasepayload_class->sink_event = gst_rtp_h265_pay_sink_event;
178 GST_DEBUG_CATEGORY_INIT (rtph265pay_debug, "rtph265pay", 0,
179 "H265 RTP Payloader");
183 gst_rtp_h265_pay_init (GstRtpH265Pay * rtph265pay)
185 rtph265pay->queue = g_array_new (FALSE, FALSE, sizeof (guint));
186 rtph265pay->sps = g_ptr_array_new_with_free_func (
187 (GDestroyNotify) gst_buffer_unref);
188 rtph265pay->pps = g_ptr_array_new_with_free_func (
189 (GDestroyNotify) gst_buffer_unref);
190 rtph265pay->vps = g_ptr_array_new_with_free_func (
191 (GDestroyNotify) gst_buffer_unref);
192 rtph265pay->last_vps_sps_pps = -1;
193 rtph265pay->vps_sps_pps_interval = DEFAULT_CONFIG_INTERVAL;
195 rtph265pay->adapter = gst_adapter_new ();
199 gst_rtp_h265_pay_clear_vps_sps_pps (GstRtpH265Pay * rtph265pay)
201 g_ptr_array_set_size (rtph265pay->vps, 0);
202 g_ptr_array_set_size (rtph265pay->sps, 0);
203 g_ptr_array_set_size (rtph265pay->pps, 0);
207 gst_rtp_h265_pay_finalize (GObject * object)
209 GstRtpH265Pay *rtph265pay;
211 rtph265pay = GST_RTP_H265_PAY (object);
213 g_array_free (rtph265pay->queue, TRUE);
215 g_ptr_array_free (rtph265pay->sps, TRUE);
216 g_ptr_array_free (rtph265pay->pps, TRUE);
217 g_ptr_array_free (rtph265pay->vps, TRUE);
219 g_object_unref (rtph265pay->adapter);
221 G_OBJECT_CLASS (parent_class)->finalize (object);
224 static const gchar all_levels[][4] = {
241 parse_field (GstStructure * s, const gchar * field, gulong min, gulong max,
246 g_assert (result != NULL);
248 str = gst_structure_get_string (s, field);
249 if (str != NULL && *str != '\0') {
253 value = strtoul (str, &end, 10);
254 if (*end == '\0' && value >= min && value <= max) {
255 *result = (guint8) value;
267 gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload, GstPad * pad,
270 GstCaps *template_caps;
271 GstCaps *allowed_caps;
277 gst_pad_peer_query_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), NULL);
279 if (allowed_caps == NULL)
283 gst_static_pad_template_get_caps (&gst_rtp_h265_pay_sink_template);
285 if (gst_caps_is_any (allowed_caps)) {
286 caps = gst_caps_ref (template_caps);
290 if (gst_caps_is_empty (allowed_caps)) {
291 caps = gst_caps_ref (allowed_caps);
295 caps = gst_caps_new_empty ();
296 for (i = 0; i < gst_caps_get_size (allowed_caps); i++) {
297 GstStructure *s = gst_caps_get_structure (allowed_caps, i);
298 GstStructure *new_s = gst_structure_new_empty ("video/x-h265");
299 guint8 ptl[12] = { 0, };
302 if (parse_field (s, "profile-id", 0, 31, &value)) {
303 const gchar *profile;
306 profile = gst_codec_utils_h265_get_profile (ptl, sizeof (ptl));
307 if (profile != NULL) {
308 GST_DEBUG_OBJECT (payload, "profile %s", profile);
309 gst_structure_set (new_s, "profile", G_TYPE_STRING, profile, NULL);
311 GST_WARNING_OBJECT (payload, "invalid profile-id %d in caps", value);
314 GST_DEBUG_OBJECT (payload, "no valid profile-id in caps");
317 if (parse_field (s, "tier-flag", 0, 1, &value)) {
320 ptl[0] |= value << 5;
321 tier = gst_codec_utils_h265_get_tier (ptl, sizeof (ptl));
322 GST_DEBUG_OBJECT (payload, "tier %s", tier);
323 gst_structure_set (new_s, "tier", G_TYPE_STRING, tier, NULL);
325 GST_DEBUG_OBJECT (payload, "no valid tier-flag in caps");
328 if (parse_field (s, "level-id", 0, 255, &value)) {
332 level = gst_codec_utils_h265_get_level (ptl, sizeof (ptl));
334 GST_DEBUG_OBJECT (payload, "level %s", level);
335 if (strcmp (level, "1") == 0) {
336 gst_structure_set (new_s, "level", G_TYPE_STRING, level, NULL);
338 GValue levels = { 0, };
342 g_value_init (&levels, GST_TYPE_LIST);
343 g_value_init (&val, G_TYPE_STRING);
345 for (j = 0; j < G_N_ELEMENTS (all_levels); j++) {
346 g_value_set_static_string (&val, all_levels[j]);
347 gst_value_list_prepend_value (&levels, &val);
348 if (!strcmp (level, all_levels[j]))
351 gst_structure_take_value (new_s, "level", &levels);
354 GST_WARNING_OBJECT (payload, "invalid level-id %d in caps", value);
357 GST_DEBUG_OBJECT (payload, "no valid level-id in caps");
360 caps = gst_caps_merge_structure (caps, new_s);
363 icaps = gst_caps_intersect (caps, template_caps);
364 gst_caps_unref (caps);
372 GST_DEBUG_OBJECT (payload, "Intersect %" GST_PTR_FORMAT " and filter %"
373 GST_PTR_FORMAT, caps, filter);
374 tmp = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
375 gst_caps_unref (caps);
379 gst_caps_unref (template_caps);
380 gst_caps_unref (allowed_caps);
382 GST_LOG_OBJECT (payload, "returning caps %" GST_PTR_FORMAT, caps);
386 /* take the currently configured VPS, SPS and PPS lists and set them on the
389 gst_rtp_h265_pay_set_vps_sps_pps (GstRTPBasePayload * basepayload)
391 GstRtpH265Pay *payloader = GST_RTP_H265_PAY (basepayload);
401 vps = g_string_new ("");
402 sps = g_string_new ("");
403 pps = g_string_new ("");
406 for (i = 0; i < payloader->vps->len; i++) {
408 GST_BUFFER_CAST (g_ptr_array_index (payloader->vps, i));
410 gst_buffer_map (vps_buf, &map, GST_MAP_READ);
411 set = g_base64_encode (map.data, map.size);
412 gst_buffer_unmap (vps_buf, &map);
414 g_string_append_printf (vps, "%s%s", i ? "," : "", set);
418 for (i = 0; i < payloader->sps->len; i++) {
420 GST_BUFFER_CAST (g_ptr_array_index (payloader->sps, i));
422 gst_buffer_map (sps_buf, &map, GST_MAP_READ);
423 set = g_base64_encode (map.data, map.size);
424 gst_buffer_unmap (sps_buf, &map);
426 g_string_append_printf (sps, "%s%s", i ? "," : "", set);
430 for (i = 0; i < payloader->pps->len; i++) {
432 GST_BUFFER_CAST (g_ptr_array_index (payloader->pps, i));
434 gst_buffer_map (pps_buf, &map, GST_MAP_READ);
435 set = g_base64_encode (map.data, map.size);
436 gst_buffer_unmap (pps_buf, &map);
438 g_string_append_printf (pps, "%s%s", i ? "," : "", set);
443 if (G_LIKELY (count)) {
444 /* combine into output caps */
445 res = gst_rtp_base_payload_set_outcaps (basepayload,
446 "sprop-vps", G_TYPE_STRING, vps->str,
447 "sprop-sps", G_TYPE_STRING, sps->str,
448 "sprop-pps", G_TYPE_STRING, pps->str, NULL);
450 res = gst_rtp_base_payload_set_outcaps (basepayload, NULL);
452 g_string_free (vps, TRUE);
453 g_string_free (sps, TRUE);
454 g_string_free (pps, TRUE);
461 gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
463 GstRtpH265Pay *rtph265pay;
470 const gchar *alignment, *stream_format;
473 rtph265pay = GST_RTP_H265_PAY (basepayload);
475 str = gst_caps_get_structure (caps, 0);
477 /* we can only set the output caps when we found the sprops and profile
479 gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "H265", 90000);
481 rtph265pay->alignment = GST_H265_ALIGNMENT_UNKNOWN;
482 alignment = gst_structure_get_string (str, "alignment");
484 if (g_str_equal (alignment, "au"))
485 rtph265pay->alignment = GST_H265_ALIGNMENT_AU;
486 if (g_str_equal (alignment, "nal"))
487 rtph265pay->alignment = GST_H265_ALIGNMENT_NAL;
490 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_UNKNOWN;
491 stream_format = gst_structure_get_string (str, "stream-format");
493 if (g_str_equal (stream_format, "hvc1"))
494 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HVC1;
495 if (g_str_equal (stream_format, "hev1"))
496 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HEV1;
497 if (g_str_equal (stream_format, "byte-stream"))
498 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_BYTESTREAM;
501 /* packetized HEVC video has a codec_data */
502 if ((value = gst_structure_get_value (str, "codec_data"))) {
503 guint num_vps, num_sps, num_pps;
506 GST_DEBUG_OBJECT (rtph265pay, "have packetized h265");
508 buffer = gst_value_get_buffer (value);
510 gst_buffer_map (buffer, &map, GST_MAP_READ);
514 /* parse the hevcC data */
516 goto hevcc_too_small;
517 /* HEVCDecoderConfigurationVersion (must be 1) */
521 /* profile_space | tier_flag | profile_idc */
522 GST_DEBUG_OBJECT (rtph265pay, "profile %06x", data[1]);
524 /* profile_compatibility_flags */
525 for (i = 2; i < 6; i++) {
526 for (j = 7; j >= 0; j--) {
527 GST_DEBUG_OBJECT (rtph265pay, "profile_compatibility_flag %06x",
532 GST_DEBUG_OBJECT (rtph265pay, "progressive_source_flag %06x",
534 GST_DEBUG_OBJECT (rtph265pay, "interlaced_source_flag %06x",
536 GST_DEBUG_OBJECT (rtph265pay, "non_packed_constraint_flag %06x",
538 GST_DEBUG_OBJECT (rtph265pay, "frame_only_constraint_flag %06x",
541 GST_DEBUG_OBJECT (rtph265pay, "level_idc %06x", data[12]);
543 GST_DEBUG_OBJECT (rtph265pay, "min_spatial_segmentation_idc %06x",
544 ((data[13] ^ 0xf0) << 8) + data[14]);
545 GST_DEBUG_OBJECT (rtph265pay, "parrallelismType %06x (ignored by paloader)",
548 GST_DEBUG_OBJECT (rtph265pay, "sps_chroma_format_idc %06x",
550 GST_DEBUG_OBJECT (rtph265pay, "bit_depth_luma_minus8 %06x",
552 GST_DEBUG_OBJECT (rtph265pay, "bit_depth_chroma_minus8 %06x",
554 GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[19]);
555 GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[20]);
557 /* constFrameRate(2 bits): 0, stream may or may not be of constant framerate
558 * numTemporalLayers (3 bits): number of temporal layers, value from SPS
559 * TemporalIdNested (1 bit): sps_temporal_id_nesting_flag from SPS
560 * lengthSizeMinusOne (2 bits): plus 1 indicates the length of the NALUnitLength */
561 GST_DEBUG_OBJECT (rtph265pay, "constFrameRate %06x",
562 (data[21] >> 6) & 0x03);
563 GST_DEBUG_OBJECT (rtph265pay, "numTemporalLayers %06x",
564 (data[21] >> 3) & 0x07);
565 GST_DEBUG_OBJECT (rtph265pay, "temporal_id_nesting_flag %06x",
566 (data[21] >> 2) & 0x01);
568 rtph265pay->nal_length_size = (data[21] & 0x3) + 1;
569 GST_DEBUG_OBJECT (rtph265pay, "nal length %u", rtph265pay->nal_length_size);
571 num_arrays = GST_READ_UINT8 (data + 22);
576 if (num_arrays > 0) {
577 if ((data[0] & 0x3f) == 0x20) { /* VPS */
580 num_vps = data[0] << 8 | data[1];
584 for (i = 0; i < num_vps; i++) {
591 nal_size = (data[0] << 8) | data[1];
595 GST_LOG_OBJECT (rtph265pay, "VPS %d size %d", i, nal_size);
600 /* make a buffer out of it and add to VPS list */
601 vps_buf = gst_buffer_new_and_alloc (nal_size);
602 gst_buffer_fill (vps_buf, 0, data, nal_size);
603 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
604 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, vps_buf);
613 if (num_arrays > 0) {
614 if ((data[0] & 0x3f) == 0x21) { /* SPS */
617 num_sps = data[0] << 8 | data[1];
621 for (i = 0; i < num_sps; i++) {
628 nal_size = (data[0] << 8) | data[1];
632 GST_LOG_OBJECT (rtph265pay, "SPS %d size %d", i, nal_size);
637 /* make a buffer out of it and add to SPS list */
638 sps_buf = gst_buffer_new_and_alloc (nal_size);
639 gst_buffer_fill (sps_buf, 0, data, nal_size);
640 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
641 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, sps_buf);
650 if (num_arrays > 0) {
651 if ((data[0] & 0x3f) == 0x22) { /* PPS */
654 num_pps = data[0] << 8 | data[1];
658 for (i = 0; i < num_pps; i++) {
665 nal_size = (data[0] << 8) | data[1];
669 GST_LOG_OBJECT (rtph265pay, "PPS %d size %d", i, nal_size);
674 /* make a buffer out of it and add to PPS list */
675 pps_buf = gst_buffer_new_and_alloc (nal_size);
676 gst_buffer_fill (pps_buf, 0, data, nal_size);
677 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
678 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, pps_buf);
687 /* and update the caps with the collected data */
688 if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
689 goto set_vps_sps_pps_failed;
691 GST_DEBUG_OBJECT (rtph265pay, "Caps have been set");
693 gst_buffer_unmap (buffer, &map);
695 GST_DEBUG_OBJECT (rtph265pay, "have bytestream h265");
702 GST_ERROR_OBJECT (rtph265pay, "hevcC size %" G_GSIZE_FORMAT " < 7", size);
707 GST_ERROR_OBJECT (rtph265pay, "wrong hevcC version");
712 GST_ERROR_OBJECT (rtph265pay, "hevcC too small ");
715 set_vps_sps_pps_failed:
717 GST_ERROR_OBJECT (rtph265pay, "failed to set vps/sps/pps");
722 gst_buffer_unmap (buffer, &map);
728 next_start_code (const guint8 * data, guint size)
730 /* Boyer-Moore string matching algorithm, in a degenerative
731 * sense because our search 'alphabet' is binary - 0 & 1 only.
732 * This allow us to simplify the general BM algorithm to a very
734 /* assume 1 is in the 3rd byte */
737 while (offset < size) {
738 if (1 == data[offset]) {
739 unsigned int shift = offset;
741 if (0 == data[--shift]) {
742 if (0 == data[--shift]) {
746 /* The jump is always 3 because of the 1 previously matched.
747 * All the 0's must be after this '1' matched at offset */
749 } else if (0 == data[offset]) {
750 /* maybe next byte is 1? */
753 /* can jump 3 bytes forward */
756 /* at each iteration, we rescan in a backward manner until
757 * we match 0.0.1 in reverse order. Since our search string
758 * has only 2 'alpabets' (i.e. 0 & 1), we know that any
759 * mismatch will force us to shift a fixed number of steps */
761 GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
767 gst_rtp_h265_pay_decode_nal (GstRtpH265Pay * payloader,
768 const guint8 * data, guint size, GstClockTime dts, GstClockTime pts)
773 /* default is no update */
776 GST_DEBUG_OBJECT (payloader, "NAL payload size %u", size);
778 type = (data[0] >> 1) & 0x3f;
780 /* We record the timestamp of the last SPS/PPS so
781 * that we can insert them at regular intervals and when needed. */
782 if (GST_H265_NAL_VPS == type || GST_H265_NAL_SPS == type
783 || GST_H265_NAL_PPS == type) {
786 /* trailing 0x0 are not part of the VPS/SPS/PPS */
787 while (size > 0 && data[size - 1] == 0x0)
790 /* encode the entire NAL in base64 */
791 GST_DEBUG_OBJECT (payloader, "found %s (type 0x%x), size %u",
792 type == GST_H265_NAL_VPS ? "VPS" : type == GST_H265_NAL_SPS ?
793 "SPS" : "PPS", type, size);
795 nal = gst_buffer_new_allocate (NULL, size, NULL);
796 gst_buffer_fill (nal, 0, data, size);
798 updated = gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (payloader),
799 payloader->vps, payloader->sps, payloader->pps, nal);
801 /* remember when we last saw VPS */
803 payloader->last_vps_sps_pps =
804 gst_segment_to_running_time (&GST_RTP_BASE_PAYLOAD_CAST
805 (payloader)->segment, GST_FORMAT_TIME, pts);
807 GST_DEBUG_OBJECT (payloader, "NALU type 0x%x, size %u", type, size);
814 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
815 GPtrArray * paybufs, GstClockTime dts, GstClockTime pts);
818 gst_rtp_h265_pay_send_vps_sps_pps (GstRTPBasePayload * basepayload,
819 GstRtpH265Pay * rtph265pay, GstClockTime dts, GstClockTime pts)
821 GstFlowReturn ret = GST_FLOW_OK;
822 gboolean sent_all_vps_sps_pps = TRUE;
826 bufs = g_ptr_array_new ();
828 for (i = 0; i < rtph265pay->vps->len; i++) {
830 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->vps, i));
832 GST_DEBUG_OBJECT (rtph265pay, "inserting VPS in the stream");
833 g_ptr_array_add (bufs, gst_buffer_ref (vps_buf));
835 for (i = 0; i < rtph265pay->sps->len; i++) {
837 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->sps, i));
839 GST_DEBUG_OBJECT (rtph265pay, "inserting SPS in the stream");
840 g_ptr_array_add (bufs, gst_buffer_ref (sps_buf));
842 for (i = 0; i < rtph265pay->pps->len; i++) {
844 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->pps, i));
846 GST_DEBUG_OBJECT (rtph265pay, "inserting PPS in the stream");
847 g_ptr_array_add (bufs, gst_buffer_ref (pps_buf));
850 ret = gst_rtp_h265_pay_payload_nal (basepayload, bufs, dts, pts);
851 if (ret != GST_FLOW_OK) {
852 /* not critical but warn */
853 GST_WARNING_OBJECT (basepayload, "failed pushing VPS/SPS/PPS");
855 sent_all_vps_sps_pps = FALSE;
858 if (pts != -1 && sent_all_vps_sps_pps)
859 rtph265pay->last_vps_sps_pps =
860 gst_segment_to_running_time (&basepayload->segment, GST_FORMAT_TIME,
867 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
868 GPtrArray * paybufs, GstClockTime dts, GstClockTime pts)
870 GstRtpH265Pay *rtph265pay;
876 rtph265pay = GST_RTP_H265_PAY (basepayload);
877 mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph265pay);
879 /* should set src caps before pushing stuff,
880 * and if we did not see enough VPS/SPS/PPS, that may not be the case */
881 if (G_UNLIKELY (!gst_pad_has_current_caps (GST_RTP_BASE_PAYLOAD_SRCPAD
883 gst_rtp_h265_pay_set_vps_sps_pps (basepayload);
887 for (i = 0; i < paybufs->len; i++) {
890 guint packet_len, payload_len;
894 GstBufferList *outlist = NULL;
896 GstRTPBuffer rtp = { NULL };
900 paybuf = g_ptr_array_index (paybufs, i);
902 if (ret != GST_FLOW_OK) {
903 /* unref buffers that will not be payloaded after a flow error */
904 gst_buffer_unref (paybuf);
908 marker = GST_BUFFER_FLAG_IS_SET (paybuf, GST_BUFFER_FLAG_MARKER);
910 size = gst_buffer_get_size (paybuf);
911 gst_buffer_extract (paybuf, 0, nalHeader, 2);
912 nalType = (nalHeader[0] >> 1) & 0x3f;
914 GST_DEBUG_OBJECT (rtph265pay, "Processing Buffer with NAL TYPE=%d",
919 /* check if we need to emit an VPS/SPS/PPS now */
920 if ((nalType == GST_H265_NAL_SLICE_TRAIL_N)
921 || (nalType == GST_H265_NAL_SLICE_TRAIL_R)
922 || (nalType == GST_H265_NAL_SLICE_TSA_N)
923 || (nalType == GST_H265_NAL_SLICE_TSA_R)
924 || (nalType == GST_H265_NAL_SLICE_STSA_N)
925 || (nalType == GST_H265_NAL_SLICE_STSA_R)
926 || (nalType == GST_H265_NAL_SLICE_RASL_N)
927 || (nalType == GST_H265_NAL_SLICE_RASL_R)
928 || (nalType == GST_H265_NAL_SLICE_BLA_W_LP)
929 || (nalType == GST_H265_NAL_SLICE_BLA_W_RADL)
930 || (nalType == GST_H265_NAL_SLICE_BLA_N_LP)
931 || (nalType == GST_H265_NAL_SLICE_IDR_W_RADL)
932 || (nalType == GST_H265_NAL_SLICE_IDR_N_LP)
933 || (nalType == GST_H265_NAL_SLICE_CRA_NUT)) {
934 if (rtph265pay->vps_sps_pps_interval > 0) {
935 if (rtph265pay->last_vps_sps_pps != -1) {
937 GstClockTime running_time =
938 gst_segment_to_running_time (&basepayload->segment,
939 GST_FORMAT_TIME, pts);
941 GST_LOG_OBJECT (rtph265pay,
942 "now %" GST_TIME_FORMAT ", last VPS/SPS/PPS %" GST_TIME_FORMAT,
943 GST_TIME_ARGS (running_time),
944 GST_TIME_ARGS (rtph265pay->last_vps_sps_pps));
946 /* calculate diff between last SPS/PPS in milliseconds */
947 if (running_time > rtph265pay->last_vps_sps_pps)
948 diff = running_time - rtph265pay->last_vps_sps_pps;
952 GST_DEBUG_OBJECT (rtph265pay,
953 "interval since last VPS/SPS/PPS %" GST_TIME_FORMAT,
954 GST_TIME_ARGS (diff));
956 /* bigger than interval, queue SPS/PPS */
957 if (GST_TIME_AS_SECONDS (diff) >= rtph265pay->vps_sps_pps_interval) {
958 GST_DEBUG_OBJECT (rtph265pay, "time to send VPS/SPS/PPS");
962 /* no known previous SPS/PPS time, send now */
963 GST_DEBUG_OBJECT (rtph265pay,
964 "no previous VPS/SPS/PPS time, send now");
967 } else if (rtph265pay->vps_sps_pps_interval == -1
968 && (nalType == GST_H265_NAL_SLICE_IDR_W_RADL
969 || nalType == GST_H265_NAL_SLICE_IDR_N_LP)) {
970 /* send VPS/SPS/PPS before every IDR frame */
975 if (!sent_ps && (send_ps || rtph265pay->send_vps_sps_pps)) {
976 /* we need to send SPS/PPS now first. FIXME, don't use the pts for
977 * checking when we need to send SPS/PPS but convert to running_time
979 rtph265pay->send_vps_sps_pps = FALSE;
981 GST_DEBUG_OBJECT (rtph265pay, "sending VPS/SPS/PPS before current frame");
983 gst_rtp_h265_pay_send_vps_sps_pps (basepayload, rtph265pay, dts, pts);
984 if (ret != GST_FLOW_OK) {
985 gst_buffer_unref (paybuf);
990 packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
992 if (packet_len < mtu) {
993 GST_DEBUG_OBJECT (rtph265pay,
994 "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
995 /* will fit in one packet */
998 * create buffer without payload containing only the RTP header
999 * (memory block at index 0) */
1000 outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
1002 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1004 /* Mark the end of a frame */
1005 gst_rtp_buffer_set_marker (&rtp, marker);
1007 /* timestamp the outbuffer */
1008 GST_BUFFER_PTS (outbuf) = pts;
1009 GST_BUFFER_DTS (outbuf) = dts;
1011 /* insert payload memory block */
1012 gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1013 outbuf = gst_buffer_append (outbuf, paybuf);
1015 outlist = gst_buffer_list_new ();
1017 /* add the buffer to the buffer list */
1018 gst_buffer_list_add (outlist, outbuf);
1020 gst_rtp_buffer_unmap (&rtp);
1022 /* push the list to the next element in the pipe */
1023 ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1025 /* fragmentation Units */
1027 int ii = 0, start = 1, end = 0, pos = 0;
1029 GST_DEBUG_OBJECT (basepayload,
1030 "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
1035 GST_DEBUG_OBJECT (basepayload, "Using FU fragmentation for data size=%d",
1038 /* We keep 3 bytes for PayloadHdr and FU Header */
1039 payload_len = gst_rtp_buffer_calc_payload_len (mtu - 3, 0, 0);
1041 outlist = gst_buffer_list_new ();
1044 limitedSize = size < payload_len ? size : payload_len;
1045 GST_DEBUG_OBJECT (basepayload,
1046 "Inside FU fragmentation limitedSize=%d iteration=%d", limitedSize,
1050 * create buffer without payload containing only the RTP header
1051 * (memory block at index 0), and with space for PayloadHdr and FU header */
1052 outbuf = gst_rtp_buffer_new_allocate (3, 0, 0);
1054 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1056 GST_BUFFER_DTS (outbuf) = dts;
1057 GST_BUFFER_PTS (outbuf) = pts;
1058 payload = gst_rtp_buffer_get_payload (&rtp);
1060 if (limitedSize == size) {
1061 GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
1065 /* PayloadHdr (type = 49) */
1066 payload[0] = (nalHeader[0] & 0x81) | (49 << 1);
1067 payload[1] = nalHeader[1];
1069 /* If it's the last fragment and the end of this au, mark the end of
1071 gst_rtp_buffer_set_marker (&rtp, end && marker);
1074 payload[2] = (start << 7) | (end << 6) | (nalType & 0x3f);
1076 gst_rtp_buffer_unmap (&rtp);
1078 /* insert payload memory block */
1079 gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1080 gst_buffer_copy_into (outbuf, paybuf, GST_BUFFER_COPY_MEMORY, pos,
1082 /* add the buffer to the buffer list */
1083 gst_buffer_list_add (outlist, outbuf);
1085 size -= limitedSize;
1091 ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1092 gst_buffer_unref (paybuf);
1096 g_ptr_array_free (paybufs, TRUE);
1101 static GstFlowReturn
1102 gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * basepayload,
1105 GstRtpH265Pay *rtph265pay;
1111 GstClockTime dts, pts;
1114 GstBuffer *paybuf = NULL;
1116 gboolean marker = FALSE;
1117 gboolean draining = (buffer == NULL);
1119 rtph265pay = GST_RTP_H265_PAY (basepayload);
1121 /* the input buffer contains one or more NAL units */
1123 hevc = (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HEV1)
1124 || (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HVC1);
1127 /* In hevc mode, there is no adapter, so nothing to drain */
1130 gst_buffer_map (buffer, &map, GST_MAP_READ);
1133 pts = GST_BUFFER_PTS (buffer);
1134 dts = GST_BUFFER_DTS (buffer);
1135 marker = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER);
1136 GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1139 marker = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER);
1140 gst_adapter_push (rtph265pay->adapter, buffer);
1144 /* We want to use the first TS used to construct the following NAL */
1145 dts = gst_adapter_prev_dts (rtph265pay->adapter, NULL);
1146 pts = gst_adapter_prev_pts (rtph265pay->adapter, NULL);
1148 size = gst_adapter_available (rtph265pay->adapter);
1149 /* Nothing to do here if the adapter is empty, e.g. on EOS */
1152 data = gst_adapter_map (rtph265pay->adapter, size);
1153 GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1158 /* now loop over all NAL units and put them in a packet
1159 * FIXME, we should really try to pack multiple NAL units into one RTP packet
1160 * if we can, especially for the config packets that wont't cause decoder
1163 guint nal_length_size;
1167 paybufs = g_ptr_array_new ();
1168 nal_length_size = rtph265pay->nal_length_size;
1170 while (size > nal_length_size) {
1174 for (i = 0; i < nal_length_size; i++) {
1175 nal_len = ((nal_len << 8) + data[i]);
1178 /* skip the length bytes, make sure we don't run past the buffer size */
1179 data += nal_length_size;
1180 offset += nal_length_size;
1181 size -= nal_length_size;
1183 if (size >= nal_len) {
1184 GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1187 GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1191 paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1193 g_ptr_array_add (paybufs, paybuf);
1195 /* If we're at the end of the buffer, then we're at the end of the
1198 GST_BUFFER_FLAG_UNSET (paybuf, GST_BUFFER_FLAG_MARKER);
1199 if (size - nal_len <= nal_length_size) {
1200 if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU || marker)
1201 GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1208 ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1211 gboolean update = FALSE;
1214 /* get offset of first start code */
1215 next = next_start_code (data, size);
1217 /* skip to start code, if no start code is found, next will be size and we
1218 * will not collect data. */
1221 nal_queue = rtph265pay->queue;
1224 /* array must be empty when we get here */
1225 g_assert (nal_queue->len == 0);
1227 GST_DEBUG_OBJECT (basepayload,
1228 "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1230 paybufs = g_ptr_array_new ();
1232 /* first pass to locate NALs and parse VPS/SPS/PPS */
1234 /* skip start code */
1238 /* use next_start_code() to scan buffer.
1239 * next_start_code() returns the offset in data,
1240 * starting from zero to the first byte of 0.0.0.1
1241 * If no start code is found, it returns the value of the
1243 * data is unchanged by the call to next_start_code()
1245 next = next_start_code (data, size);
1247 /* nal or au aligned input needs no delaying until next time */
1248 if (next == size && !draining &&
1249 rtph265pay->alignment == GST_H265_ALIGNMENT_UNKNOWN) {
1250 /* Didn't find the start of next NAL and it's not EOS,
1251 * handle it next time */
1255 /* nal length is distance to next start code */
1258 GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1261 /* We know our stream is a valid H265 NAL packet,
1262 * go parse it for VPS/SPS/PPS to enrich the caps */
1263 /* order: make sure to check nal */
1264 update = gst_rtp_h265_pay_decode_nal (rtph265pay, data, nal_len, dts, pts)
1267 /* move to next NAL packet */
1271 g_array_append_val (nal_queue, nal_len);
1274 /* if has new VPS, SPS & PPS, update the output caps */
1275 if (G_UNLIKELY (update))
1276 if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
1279 /* second pass to payload and push */
1281 if (nal_queue->len != 0)
1282 gst_adapter_flush (rtph265pay->adapter, skip);
1284 for (i = 0; i < nal_queue->len; i++) {
1287 nal_len = g_array_index (nal_queue, guint, i);
1288 /* skip start code */
1289 gst_adapter_flush (rtph265pay->adapter, 3);
1291 /* Trim the end unless we're the last NAL in the stream.
1292 * In case we're not at the end of the buffer we know the next block
1293 * starts with 0x000001 so all the 0x00 bytes at the end of this one are
1294 * trailing 0x0 that can be discarded */
1296 data = gst_adapter_map (rtph265pay->adapter, size);
1297 if (i + 1 != nal_queue->len || !draining)
1298 for (; size > 1 && data[size - 1] == 0x0; size--)
1301 paybuf = gst_adapter_take_buffer (rtph265pay->adapter, size);
1303 g_ptr_array_add (paybufs, paybuf);
1305 /* If it's the last nal unit we have in non-bytestream mode, we can
1306 * assume it's the end of an access-unit */
1307 GST_BUFFER_FLAG_UNSET (paybuf, GST_BUFFER_FLAG_MARKER);
1308 if (i == nal_queue->len - 1) {
1309 if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU ||
1311 GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1314 /* move to next NAL packet */
1315 /* Skips the trailing zeros */
1316 gst_adapter_flush (rtph265pay->adapter, nal_len - size);
1318 /* put the data in one or more RTP packets */
1319 ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1320 g_array_set_size (nal_queue, 0);
1325 gst_buffer_unmap (buffer, &map);
1326 gst_buffer_unref (buffer);
1328 gst_adapter_unmap (rtph265pay->adapter);
1335 GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1336 g_array_set_size (nal_queue, 0);
1337 ret = GST_FLOW_NOT_NEGOTIATED;
1343 gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1346 const GstStructure *s;
1347 GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (payload);
1349 switch (GST_EVENT_TYPE (event)) {
1350 case GST_EVENT_FLUSH_STOP:
1351 gst_adapter_clear (rtph265pay->adapter);
1353 case GST_EVENT_CUSTOM_DOWNSTREAM:
1354 s = gst_event_get_structure (event);
1355 if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1356 gboolean resend_codec_data;
1358 if (gst_structure_get_boolean (s, "all-headers",
1359 &resend_codec_data) && resend_codec_data)
1360 rtph265pay->send_vps_sps_pps = TRUE;
1365 /* call handle_buffer with NULL to flush last NAL from adapter
1366 * in byte-stream mode
1368 gst_rtp_h265_pay_handle_buffer (payload, NULL);
1371 case GST_EVENT_STREAM_START:
1372 GST_DEBUG_OBJECT (rtph265pay,
1373 "New stream detected => Clear VPS, SPS and PPS");
1374 gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1380 res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1385 static GstStateChangeReturn
1386 gst_rtp_h265_pay_change_state (GstElement * element, GstStateChange transition)
1388 GstStateChangeReturn ret;
1389 GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (element);
1391 switch (transition) {
1392 case GST_STATE_CHANGE_READY_TO_PAUSED:
1393 rtph265pay->send_vps_sps_pps = FALSE;
1394 gst_adapter_clear (rtph265pay->adapter);
1400 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1402 switch (transition) {
1403 case GST_STATE_CHANGE_PAUSED_TO_READY:
1404 rtph265pay->last_vps_sps_pps = -1;
1405 gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1415 gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
1416 const GValue * value, GParamSpec * pspec)
1418 GstRtpH265Pay *rtph265pay;
1420 rtph265pay = GST_RTP_H265_PAY (object);
1423 case PROP_CONFIG_INTERVAL:
1424 rtph265pay->vps_sps_pps_interval = g_value_get_int (value);
1427 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1433 gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
1434 GValue * value, GParamSpec * pspec)
1436 GstRtpH265Pay *rtph265pay;
1438 rtph265pay = GST_RTP_H265_PAY (object);
1441 case PROP_CONFIG_INTERVAL:
1442 g_value_set_int (value, rtph265pay->vps_sps_pps_interval);
1445 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1451 gst_rtp_h265_pay_plugin_init (GstPlugin * plugin)
1453 return gst_element_register (plugin, "rtph265pay",
1454 GST_RANK_SECONDARY, GST_TYPE_RTP_H265_PAY);