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 #define IS_ACCESS_UNIT(x) (((x) >= 0x00) && ((x) < 0x20))
114 static void gst_rtp_h265_pay_finalize (GObject * object);
116 static void gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
117 const GValue * value, GParamSpec * pspec);
118 static void gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
119 GValue * value, GParamSpec * pspec);
121 static GstCaps *gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload,
122 GstPad * pad, GstCaps * filter);
123 static gboolean gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload,
125 static GstFlowReturn gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * pad,
127 static gboolean gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload,
129 static GstStateChangeReturn gst_rtp_h265_pay_change_state (GstElement *
130 element, GstStateChange transition);
132 #define gst_rtp_h265_pay_parent_class parent_class
133 G_DEFINE_TYPE (GstRtpH265Pay, gst_rtp_h265_pay, GST_TYPE_RTP_BASE_PAYLOAD);
136 gst_rtp_h265_pay_class_init (GstRtpH265PayClass * klass)
138 GObjectClass *gobject_class;
139 GstElementClass *gstelement_class;
140 GstRTPBasePayloadClass *gstrtpbasepayload_class;
142 gobject_class = (GObjectClass *) klass;
143 gstelement_class = (GstElementClass *) klass;
144 gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
146 gobject_class->set_property = gst_rtp_h265_pay_set_property;
147 gobject_class->get_property = gst_rtp_h265_pay_get_property;
149 g_object_class_install_property (G_OBJECT_CLASS (klass),
150 PROP_CONFIG_INTERVAL,
151 g_param_spec_int ("config-interval",
152 "VPS SPS PPS Send Interval",
153 "Send VPS, SPS and PPS Insertion Interval in seconds (sprop parameter sets "
154 "will be multiplexed in the data stream when detected.) "
155 "(0 = disabled, -1 = send with every IDR frame)",
156 -1, 3600, DEFAULT_CONFIG_INTERVAL,
157 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
160 gobject_class->finalize = gst_rtp_h265_pay_finalize;
162 gst_element_class_add_static_pad_template (gstelement_class,
163 &gst_rtp_h265_pay_src_template);
164 gst_element_class_add_static_pad_template (gstelement_class,
165 &gst_rtp_h265_pay_sink_template);
167 gst_element_class_set_static_metadata (gstelement_class, "RTP H265 payloader",
168 "Codec/Payloader/Network/RTP",
169 "Payload-encode H265 video into RTP packets (RFC 7798)",
170 "Jurgen Slowack <jurgenslowack@gmail.com>");
172 gstelement_class->change_state =
173 GST_DEBUG_FUNCPTR (gst_rtp_h265_pay_change_state);
175 gstrtpbasepayload_class->get_caps = gst_rtp_h265_pay_getcaps;
176 gstrtpbasepayload_class->set_caps = gst_rtp_h265_pay_setcaps;
177 gstrtpbasepayload_class->handle_buffer = gst_rtp_h265_pay_handle_buffer;
178 gstrtpbasepayload_class->sink_event = gst_rtp_h265_pay_sink_event;
180 GST_DEBUG_CATEGORY_INIT (rtph265pay_debug, "rtph265pay", 0,
181 "H265 RTP Payloader");
185 gst_rtp_h265_pay_init (GstRtpH265Pay * rtph265pay)
187 rtph265pay->queue = g_array_new (FALSE, FALSE, sizeof (guint));
188 rtph265pay->sps = g_ptr_array_new_with_free_func (
189 (GDestroyNotify) gst_buffer_unref);
190 rtph265pay->pps = g_ptr_array_new_with_free_func (
191 (GDestroyNotify) gst_buffer_unref);
192 rtph265pay->vps = g_ptr_array_new_with_free_func (
193 (GDestroyNotify) gst_buffer_unref);
194 rtph265pay->last_vps_sps_pps = -1;
195 rtph265pay->vps_sps_pps_interval = DEFAULT_CONFIG_INTERVAL;
197 rtph265pay->adapter = gst_adapter_new ();
201 gst_rtp_h265_pay_clear_vps_sps_pps (GstRtpH265Pay * rtph265pay)
203 g_ptr_array_set_size (rtph265pay->vps, 0);
204 g_ptr_array_set_size (rtph265pay->sps, 0);
205 g_ptr_array_set_size (rtph265pay->pps, 0);
209 gst_rtp_h265_pay_finalize (GObject * object)
211 GstRtpH265Pay *rtph265pay;
213 rtph265pay = GST_RTP_H265_PAY (object);
215 g_array_free (rtph265pay->queue, TRUE);
217 g_ptr_array_free (rtph265pay->sps, TRUE);
218 g_ptr_array_free (rtph265pay->pps, TRUE);
219 g_ptr_array_free (rtph265pay->vps, TRUE);
221 g_object_unref (rtph265pay->adapter);
223 G_OBJECT_CLASS (parent_class)->finalize (object);
226 static const gchar all_levels[][4] = {
243 parse_field (GstStructure * s, const gchar * field, gulong min, gulong max,
248 g_assert (result != NULL);
250 str = gst_structure_get_string (s, field);
251 if (str != NULL && *str != '\0') {
255 value = strtoul (str, &end, 10);
256 if (*end == '\0' && value >= min && value <= max) {
257 *result = (guint8) value;
269 gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload, GstPad * pad,
272 GstCaps *template_caps;
273 GstCaps *allowed_caps;
279 gst_pad_peer_query_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), NULL);
281 if (allowed_caps == NULL)
285 gst_static_pad_template_get_caps (&gst_rtp_h265_pay_sink_template);
287 if (gst_caps_is_any (allowed_caps)) {
288 caps = gst_caps_ref (template_caps);
292 if (gst_caps_is_empty (allowed_caps)) {
293 caps = gst_caps_ref (allowed_caps);
297 caps = gst_caps_new_empty ();
298 for (i = 0; i < gst_caps_get_size (allowed_caps); i++) {
299 GstStructure *s = gst_caps_get_structure (allowed_caps, i);
300 GstStructure *new_s = gst_structure_new_empty ("video/x-h265");
301 guint8 ptl[12] = { 0, };
304 if (parse_field (s, "profile-id", 0, 31, &value)) {
305 const gchar *profile;
308 profile = gst_codec_utils_h265_get_profile (ptl, sizeof (ptl));
309 if (profile != NULL) {
310 GST_DEBUG_OBJECT (payload, "profile %s", profile);
311 gst_structure_set (new_s, "profile", G_TYPE_STRING, profile, NULL);
313 GST_WARNING_OBJECT (payload, "invalid profile-id %d in caps", value);
316 GST_DEBUG_OBJECT (payload, "no valid profile-id in caps");
319 if (parse_field (s, "tier-flag", 0, 1, &value)) {
322 ptl[0] |= value << 5;
323 tier = gst_codec_utils_h265_get_tier (ptl, sizeof (ptl));
324 GST_DEBUG_OBJECT (payload, "tier %s", tier);
325 gst_structure_set (new_s, "tier", G_TYPE_STRING, tier, NULL);
327 GST_DEBUG_OBJECT (payload, "no valid tier-flag in caps");
330 if (parse_field (s, "level-id", 0, 255, &value)) {
334 level = gst_codec_utils_h265_get_level (ptl, sizeof (ptl));
336 GST_DEBUG_OBJECT (payload, "level %s", level);
337 if (strcmp (level, "1") == 0) {
338 gst_structure_set (new_s, "level", G_TYPE_STRING, level, NULL);
340 GValue levels = { 0, };
344 g_value_init (&levels, GST_TYPE_LIST);
345 g_value_init (&val, G_TYPE_STRING);
347 for (j = 0; j < G_N_ELEMENTS (all_levels); j++) {
348 g_value_set_static_string (&val, all_levels[j]);
349 gst_value_list_prepend_value (&levels, &val);
350 if (!strcmp (level, all_levels[j]))
353 gst_structure_take_value (new_s, "level", &levels);
356 GST_WARNING_OBJECT (payload, "invalid level-id %d in caps", value);
359 GST_DEBUG_OBJECT (payload, "no valid level-id in caps");
362 caps = gst_caps_merge_structure (caps, new_s);
365 icaps = gst_caps_intersect (caps, template_caps);
366 gst_caps_unref (caps);
374 GST_DEBUG_OBJECT (payload, "Intersect %" GST_PTR_FORMAT " and filter %"
375 GST_PTR_FORMAT, caps, filter);
376 tmp = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
377 gst_caps_unref (caps);
381 gst_caps_unref (template_caps);
382 gst_caps_unref (allowed_caps);
384 GST_LOG_OBJECT (payload, "returning caps %" GST_PTR_FORMAT, caps);
388 /* take the currently configured VPS, SPS and PPS lists and set them on the
391 gst_rtp_h265_pay_set_vps_sps_pps (GstRTPBasePayload * basepayload)
393 GstRtpH265Pay *payloader = GST_RTP_H265_PAY (basepayload);
403 vps = g_string_new ("");
404 sps = g_string_new ("");
405 pps = g_string_new ("");
408 for (i = 0; i < payloader->vps->len; i++) {
410 GST_BUFFER_CAST (g_ptr_array_index (payloader->vps, i));
412 gst_buffer_map (vps_buf, &map, GST_MAP_READ);
413 set = g_base64_encode (map.data, map.size);
414 gst_buffer_unmap (vps_buf, &map);
416 g_string_append_printf (vps, "%s%s", i ? "," : "", set);
420 for (i = 0; i < payloader->sps->len; i++) {
422 GST_BUFFER_CAST (g_ptr_array_index (payloader->sps, i));
424 gst_buffer_map (sps_buf, &map, GST_MAP_READ);
425 set = g_base64_encode (map.data, map.size);
426 gst_buffer_unmap (sps_buf, &map);
428 g_string_append_printf (sps, "%s%s", i ? "," : "", set);
432 for (i = 0; i < payloader->pps->len; i++) {
434 GST_BUFFER_CAST (g_ptr_array_index (payloader->pps, i));
436 gst_buffer_map (pps_buf, &map, GST_MAP_READ);
437 set = g_base64_encode (map.data, map.size);
438 gst_buffer_unmap (pps_buf, &map);
440 g_string_append_printf (pps, "%s%s", i ? "," : "", set);
445 if (G_LIKELY (count)) {
446 /* combine into output caps */
447 res = gst_rtp_base_payload_set_outcaps (basepayload,
448 "sprop-vps", G_TYPE_STRING, vps->str,
449 "sprop-sps", G_TYPE_STRING, sps->str,
450 "sprop-pps", G_TYPE_STRING, pps->str, NULL);
452 res = gst_rtp_base_payload_set_outcaps (basepayload, NULL);
454 g_string_free (vps, TRUE);
455 g_string_free (sps, TRUE);
456 g_string_free (pps, TRUE);
463 gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
465 GstRtpH265Pay *rtph265pay;
472 const gchar *alignment, *stream_format;
475 rtph265pay = GST_RTP_H265_PAY (basepayload);
477 str = gst_caps_get_structure (caps, 0);
479 /* we can only set the output caps when we found the sprops and profile
481 gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "H265", 90000);
483 rtph265pay->alignment = GST_H265_ALIGNMENT_UNKNOWN;
484 alignment = gst_structure_get_string (str, "alignment");
486 if (g_str_equal (alignment, "au"))
487 rtph265pay->alignment = GST_H265_ALIGNMENT_AU;
488 if (g_str_equal (alignment, "nal"))
489 rtph265pay->alignment = GST_H265_ALIGNMENT_NAL;
492 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_UNKNOWN;
493 stream_format = gst_structure_get_string (str, "stream-format");
495 if (g_str_equal (stream_format, "hvc1"))
496 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HVC1;
497 if (g_str_equal (stream_format, "hev1"))
498 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_HEV1;
499 if (g_str_equal (stream_format, "byte-stream"))
500 rtph265pay->stream_format = GST_H265_STREAM_FORMAT_BYTESTREAM;
503 /* packetized HEVC video has a codec_data */
504 if ((value = gst_structure_get_value (str, "codec_data"))) {
505 guint num_vps, num_sps, num_pps;
508 GST_DEBUG_OBJECT (rtph265pay, "have packetized h265");
510 buffer = gst_value_get_buffer (value);
512 gst_buffer_map (buffer, &map, GST_MAP_READ);
516 /* parse the hevcC data */
518 goto hevcc_too_small;
519 /* HEVCDecoderConfigurationVersion (must be 1) */
523 /* profile_space | tier_flag | profile_idc */
524 GST_DEBUG_OBJECT (rtph265pay, "profile %06x", data[1]);
526 /* profile_compatibility_flags */
527 for (i = 2; i < 6; i++) {
528 for (j = 7; j >= 0; j--) {
529 GST_DEBUG_OBJECT (rtph265pay, "profile_compatibility_flag %06x",
534 GST_DEBUG_OBJECT (rtph265pay, "progressive_source_flag %06x",
536 GST_DEBUG_OBJECT (rtph265pay, "interlaced_source_flag %06x",
538 GST_DEBUG_OBJECT (rtph265pay, "non_packed_constraint_flag %06x",
540 GST_DEBUG_OBJECT (rtph265pay, "frame_only_constraint_flag %06x",
543 GST_DEBUG_OBJECT (rtph265pay, "level_idc %06x", data[12]);
545 GST_DEBUG_OBJECT (rtph265pay, "min_spatial_segmentation_idc %06x",
546 ((data[13] ^ 0xf0) << 8) + data[14]);
547 GST_DEBUG_OBJECT (rtph265pay, "parrallelismType %06x (ignored by paloader)",
550 GST_DEBUG_OBJECT (rtph265pay, "sps_chroma_format_idc %06x",
552 GST_DEBUG_OBJECT (rtph265pay, "bit_depth_luma_minus8 %06x",
554 GST_DEBUG_OBJECT (rtph265pay, "bit_depth_chroma_minus8 %06x",
556 GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[19]);
557 GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[20]);
559 /* constFrameRate(2 bits): 0, stream may or may not be of constant framerate
560 * numTemporalLayers (3 bits): number of temporal layers, value from SPS
561 * TemporalIdNested (1 bit): sps_temporal_id_nesting_flag from SPS
562 * lengthSizeMinusOne (2 bits): plus 1 indicates the length of the NALUnitLength */
563 GST_DEBUG_OBJECT (rtph265pay, "constFrameRate %06x",
564 (data[21] >> 6) & 0x03);
565 GST_DEBUG_OBJECT (rtph265pay, "numTemporalLayers %06x",
566 (data[21] >> 3) & 0x07);
567 GST_DEBUG_OBJECT (rtph265pay, "temporal_id_nesting_flag %06x",
568 (data[21] >> 2) & 0x01);
570 rtph265pay->nal_length_size = (data[21] & 0x3) + 1;
571 GST_DEBUG_OBJECT (rtph265pay, "nal length %u", rtph265pay->nal_length_size);
573 num_arrays = GST_READ_UINT8 (data + 22);
578 if (num_arrays > 0) {
579 if ((data[0] & 0x3f) == 0x20) { /* VPS */
582 num_vps = data[0] << 8 | data[1];
586 for (i = 0; i < num_vps; i++) {
593 nal_size = (data[0] << 8) | data[1];
597 GST_LOG_OBJECT (rtph265pay, "VPS %d size %d", i, nal_size);
602 /* make a buffer out of it and add to VPS list */
603 vps_buf = gst_buffer_new_and_alloc (nal_size);
604 gst_buffer_fill (vps_buf, 0, data, nal_size);
605 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
606 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, vps_buf);
615 if (num_arrays > 0) {
616 if ((data[0] & 0x3f) == 0x21) { /* SPS */
619 num_sps = data[0] << 8 | data[1];
623 for (i = 0; i < num_sps; i++) {
630 nal_size = (data[0] << 8) | data[1];
634 GST_LOG_OBJECT (rtph265pay, "SPS %d size %d", i, nal_size);
639 /* make a buffer out of it and add to SPS list */
640 sps_buf = gst_buffer_new_and_alloc (nal_size);
641 gst_buffer_fill (sps_buf, 0, data, nal_size);
642 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
643 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, sps_buf);
652 if (num_arrays > 0) {
653 if ((data[0] & 0x3f) == 0x22) { /* PPS */
656 num_pps = data[0] << 8 | data[1];
660 for (i = 0; i < num_pps; i++) {
667 nal_size = (data[0] << 8) | data[1];
671 GST_LOG_OBJECT (rtph265pay, "PPS %d size %d", i, nal_size);
676 /* make a buffer out of it and add to PPS list */
677 pps_buf = gst_buffer_new_and_alloc (nal_size);
678 gst_buffer_fill (pps_buf, 0, data, nal_size);
679 gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (rtph265pay),
680 rtph265pay->vps, rtph265pay->sps, rtph265pay->pps, pps_buf);
689 /* and update the caps with the collected data */
690 if (!gst_rtp_h265_pay_set_vps_sps_pps (basepayload))
691 goto set_vps_sps_pps_failed;
693 GST_DEBUG_OBJECT (rtph265pay, "Caps have been set");
695 gst_buffer_unmap (buffer, &map);
697 GST_DEBUG_OBJECT (rtph265pay, "have bytestream h265");
704 GST_ERROR_OBJECT (rtph265pay, "hevcC size %" G_GSIZE_FORMAT " < 7", size);
709 GST_ERROR_OBJECT (rtph265pay, "wrong hevcC version");
714 GST_ERROR_OBJECT (rtph265pay, "hevcC too small ");
717 set_vps_sps_pps_failed:
719 GST_ERROR_OBJECT (rtph265pay, "failed to set vps/sps/pps");
724 gst_buffer_unmap (buffer, &map);
730 next_start_code (const guint8 * data, guint size)
732 /* Boyer-Moore string matching algorithm, in a degenerative
733 * sense because our search 'alphabet' is binary - 0 & 1 only.
734 * This allow us to simplify the general BM algorithm to a very
736 /* assume 1 is in the 3rd byte */
739 while (offset < size) {
740 if (1 == data[offset]) {
741 unsigned int shift = offset;
743 if (0 == data[--shift]) {
744 if (0 == data[--shift]) {
748 /* The jump is always 3 because of the 1 previously matched.
749 * All the 0's must be after this '1' matched at offset */
751 } else if (0 == data[offset]) {
752 /* maybe next byte is 1? */
755 /* can jump 3 bytes forward */
758 /* at each iteration, we rescan in a backward manner until
759 * we match 0.0.1 in reverse order. Since our search string
760 * has only 2 'alpabets' (i.e. 0 & 1), we know that any
761 * mismatch will force us to shift a fixed number of steps */
763 GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
769 gst_rtp_h265_pay_decode_nal (GstRtpH265Pay * payloader,
770 const guint8 * data, guint size, GstClockTime dts, GstClockTime pts)
775 /* default is no update */
778 GST_DEBUG_OBJECT (payloader, "NAL payload size %u", size);
780 type = (data[0] >> 1) & 0x3f;
782 /* We record the timestamp of the last SPS/PPS so
783 * that we can insert them at regular intervals and when needed. */
784 if (GST_H265_NAL_VPS == type || GST_H265_NAL_SPS == type
785 || GST_H265_NAL_PPS == type) {
788 /* trailing 0x0 are not part of the VPS/SPS/PPS */
789 while (size > 0 && data[size - 1] == 0x0)
792 /* encode the entire NAL in base64 */
793 GST_DEBUG_OBJECT (payloader, "found %s (type 0x%x), size %u",
794 type == GST_H265_NAL_VPS ? "VPS" : type == GST_H265_NAL_SPS ?
795 "SPS" : "PPS", type, size);
797 nal = gst_buffer_new_allocate (NULL, size, NULL);
798 gst_buffer_fill (nal, 0, data, size);
800 updated = gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (payloader),
801 payloader->vps, payloader->sps, payloader->pps, nal);
803 /* remember when we last saw VPS */
805 payloader->last_vps_sps_pps =
806 gst_segment_to_running_time (&GST_RTP_BASE_PAYLOAD_CAST
807 (payloader)->segment, GST_FORMAT_TIME, pts);
809 GST_DEBUG_OBJECT (payloader, "NALU type 0x%x, size %u", type, size);
816 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
817 GPtrArray * paybufs, GstClockTime dts, GstClockTime pts);
820 gst_rtp_h265_pay_send_vps_sps_pps (GstRTPBasePayload * basepayload,
821 GstRtpH265Pay * rtph265pay, GstClockTime dts, GstClockTime pts)
823 GstFlowReturn ret = GST_FLOW_OK;
824 gboolean sent_all_vps_sps_pps = TRUE;
828 bufs = g_ptr_array_new ();
830 for (i = 0; i < rtph265pay->vps->len; i++) {
832 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->vps, i));
834 GST_DEBUG_OBJECT (rtph265pay, "inserting VPS in the stream");
835 g_ptr_array_add (bufs, gst_buffer_ref (vps_buf));
837 for (i = 0; i < rtph265pay->sps->len; i++) {
839 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->sps, i));
841 GST_DEBUG_OBJECT (rtph265pay, "inserting SPS in the stream");
842 g_ptr_array_add (bufs, gst_buffer_ref (sps_buf));
844 for (i = 0; i < rtph265pay->pps->len; i++) {
846 GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->pps, i));
848 GST_DEBUG_OBJECT (rtph265pay, "inserting PPS in the stream");
849 g_ptr_array_add (bufs, gst_buffer_ref (pps_buf));
852 ret = gst_rtp_h265_pay_payload_nal (basepayload, bufs, dts, pts);
853 if (ret != GST_FLOW_OK) {
854 /* not critical but warn */
855 GST_WARNING_OBJECT (basepayload, "failed pushing VPS/SPS/PPS");
857 sent_all_vps_sps_pps = FALSE;
860 if (pts != -1 && sent_all_vps_sps_pps)
861 rtph265pay->last_vps_sps_pps =
862 gst_segment_to_running_time (&basepayload->segment, GST_FORMAT_TIME,
869 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
870 GPtrArray * paybufs, GstClockTime dts, GstClockTime pts)
872 GstRtpH265Pay *rtph265pay;
878 rtph265pay = GST_RTP_H265_PAY (basepayload);
879 mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph265pay);
881 /* should set src caps before pushing stuff,
882 * and if we did not see enough VPS/SPS/PPS, that may not be the case */
883 if (G_UNLIKELY (!gst_pad_has_current_caps (GST_RTP_BASE_PAYLOAD_SRCPAD
885 gst_rtp_h265_pay_set_vps_sps_pps (basepayload);
889 for (i = 0; i < paybufs->len; i++) {
892 guint packet_len, payload_len;
896 GstBufferList *outlist = NULL;
898 GstRTPBuffer rtp = { NULL };
902 paybuf = g_ptr_array_index (paybufs, i);
904 if (ret != GST_FLOW_OK) {
905 /* unref buffers that will not be payloaded after a flow error */
906 gst_buffer_unref (paybuf);
910 marker = GST_BUFFER_FLAG_IS_SET (paybuf, GST_BUFFER_FLAG_MARKER);
912 size = gst_buffer_get_size (paybuf);
913 gst_buffer_extract (paybuf, 0, nalHeader, 2);
914 nalType = (nalHeader[0] >> 1) & 0x3f;
916 GST_DEBUG_OBJECT (rtph265pay, "Processing Buffer with NAL TYPE=%d",
921 /* check if we need to emit an VPS/SPS/PPS now */
922 if ((nalType == GST_H265_NAL_SLICE_TRAIL_N)
923 || (nalType == GST_H265_NAL_SLICE_TRAIL_R)
924 || (nalType == GST_H265_NAL_SLICE_TSA_N)
925 || (nalType == GST_H265_NAL_SLICE_TSA_R)
926 || (nalType == GST_H265_NAL_SLICE_STSA_N)
927 || (nalType == GST_H265_NAL_SLICE_STSA_R)
928 || (nalType == GST_H265_NAL_SLICE_RASL_N)
929 || (nalType == GST_H265_NAL_SLICE_RASL_R)
930 || (nalType == GST_H265_NAL_SLICE_BLA_W_LP)
931 || (nalType == GST_H265_NAL_SLICE_BLA_W_RADL)
932 || (nalType == GST_H265_NAL_SLICE_BLA_N_LP)
933 || (nalType == GST_H265_NAL_SLICE_IDR_W_RADL)
934 || (nalType == GST_H265_NAL_SLICE_IDR_N_LP)
935 || (nalType == GST_H265_NAL_SLICE_CRA_NUT)) {
936 if (rtph265pay->vps_sps_pps_interval > 0) {
937 if (rtph265pay->last_vps_sps_pps != -1) {
939 GstClockTime running_time =
940 gst_segment_to_running_time (&basepayload->segment,
941 GST_FORMAT_TIME, pts);
943 GST_LOG_OBJECT (rtph265pay,
944 "now %" GST_TIME_FORMAT ", last VPS/SPS/PPS %" GST_TIME_FORMAT,
945 GST_TIME_ARGS (running_time),
946 GST_TIME_ARGS (rtph265pay->last_vps_sps_pps));
948 /* calculate diff between last SPS/PPS in milliseconds */
949 if (running_time > rtph265pay->last_vps_sps_pps)
950 diff = running_time - rtph265pay->last_vps_sps_pps;
954 GST_DEBUG_OBJECT (rtph265pay,
955 "interval since last VPS/SPS/PPS %" GST_TIME_FORMAT,
956 GST_TIME_ARGS (diff));
958 /* bigger than interval, queue SPS/PPS */
959 if (GST_TIME_AS_SECONDS (diff) >= rtph265pay->vps_sps_pps_interval) {
960 GST_DEBUG_OBJECT (rtph265pay, "time to send VPS/SPS/PPS");
964 /* no known previous SPS/PPS time, send now */
965 GST_DEBUG_OBJECT (rtph265pay,
966 "no previous VPS/SPS/PPS time, send now");
969 } else if (rtph265pay->vps_sps_pps_interval == -1
970 && (nalType == GST_H265_NAL_SLICE_IDR_W_RADL
971 || nalType == GST_H265_NAL_SLICE_IDR_N_LP)) {
972 /* send VPS/SPS/PPS before every IDR frame */
977 if (!sent_ps && (send_ps || rtph265pay->send_vps_sps_pps)) {
978 /* we need to send SPS/PPS now first. FIXME, don't use the pts for
979 * checking when we need to send SPS/PPS but convert to running_time
981 rtph265pay->send_vps_sps_pps = FALSE;
983 GST_DEBUG_OBJECT (rtph265pay, "sending VPS/SPS/PPS before current frame");
985 gst_rtp_h265_pay_send_vps_sps_pps (basepayload, rtph265pay, dts, pts);
986 if (ret != GST_FLOW_OK) {
987 gst_buffer_unref (paybuf);
992 packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
994 if (packet_len < mtu) {
995 GST_DEBUG_OBJECT (rtph265pay,
996 "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
997 /* will fit in one packet */
1000 * create buffer without payload containing only the RTP header
1001 * (memory block at index 0) */
1002 outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
1004 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1006 /* Mark the end of a frame */
1007 gst_rtp_buffer_set_marker (&rtp, marker);
1009 /* timestamp the outbuffer */
1010 GST_BUFFER_PTS (outbuf) = pts;
1011 GST_BUFFER_DTS (outbuf) = dts;
1013 /* insert payload memory block */
1014 gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1015 outbuf = gst_buffer_append (outbuf, paybuf);
1017 outlist = gst_buffer_list_new ();
1019 /* add the buffer to the buffer list */
1020 gst_buffer_list_add (outlist, outbuf);
1022 gst_rtp_buffer_unmap (&rtp);
1024 /* push the list to the next element in the pipe */
1025 ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1027 /* fragmentation Units */
1029 int ii = 0, start = 1, end = 0, pos = 0;
1031 GST_DEBUG_OBJECT (basepayload,
1032 "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
1037 GST_DEBUG_OBJECT (basepayload, "Using FU fragmentation for data size=%d",
1040 /* We keep 3 bytes for PayloadHdr and FU Header */
1041 payload_len = gst_rtp_buffer_calc_payload_len (mtu - 3, 0, 0);
1043 outlist = gst_buffer_list_new ();
1046 limitedSize = size < payload_len ? size : payload_len;
1047 GST_DEBUG_OBJECT (basepayload,
1048 "Inside FU fragmentation limitedSize=%d iteration=%d", limitedSize,
1052 * create buffer without payload containing only the RTP header
1053 * (memory block at index 0), and with space for PayloadHdr and FU header */
1054 outbuf = gst_rtp_buffer_new_allocate (3, 0, 0);
1056 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1058 GST_BUFFER_DTS (outbuf) = dts;
1059 GST_BUFFER_PTS (outbuf) = pts;
1060 payload = gst_rtp_buffer_get_payload (&rtp);
1062 if (limitedSize == size) {
1063 GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
1067 /* PayloadHdr (type = 49) */
1068 payload[0] = (nalHeader[0] & 0x81) | (49 << 1);
1069 payload[1] = nalHeader[1];
1071 /* If it's the last fragment and the end of this au, mark the end of
1073 gst_rtp_buffer_set_marker (&rtp, marker);
1076 payload[2] = (start << 7) | (end << 6) | (nalType & 0x3f);
1078 gst_rtp_buffer_unmap (&rtp);
1080 /* insert payload memory block */
1081 gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1082 gst_buffer_copy_into (outbuf, paybuf, GST_BUFFER_COPY_MEMORY, pos,
1084 /* add the buffer to the buffer list */
1085 gst_buffer_list_add (outlist, outbuf);
1087 size -= limitedSize;
1093 ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1094 gst_buffer_unref (paybuf);
1098 g_ptr_array_free (paybufs, TRUE);
1103 static GstFlowReturn
1104 gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * basepayload,
1107 GstRtpH265Pay *rtph265pay;
1113 GstClockTime dts, pts;
1116 GstBuffer *paybuf = 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 flush */
1130 gst_buffer_map (buffer, &map, GST_MAP_READ);
1133 pts = GST_BUFFER_PTS (buffer);
1134 dts = GST_BUFFER_DTS (buffer);
1135 GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1137 dts = gst_adapter_prev_dts (rtph265pay->adapter, NULL);
1138 pts = gst_adapter_prev_pts (rtph265pay->adapter, NULL);
1140 if (!GST_CLOCK_TIME_IS_VALID (dts))
1141 dts = GST_BUFFER_DTS (buffer);
1142 if (!GST_CLOCK_TIME_IS_VALID (pts))
1143 pts = GST_BUFFER_PTS (buffer);
1145 gst_adapter_push (rtph265pay->adapter, buffer);
1147 size = gst_adapter_available (rtph265pay->adapter);
1148 /* Nothing to do here if the adapter is empty, e.g. on EOS */
1151 data = gst_adapter_map (rtph265pay->adapter, size);
1152 GST_DEBUG_OBJECT (basepayload,
1153 "got %" G_GSIZE_FORMAT " bytes (%" G_GSIZE_FORMAT ")", size,
1154 buffer ? gst_buffer_get_size (buffer) : 0);
1159 /* now loop over all NAL units and put them in a packet
1160 * FIXME, we should really try to pack multiple NAL units into one RTP packet
1161 * if we can, especially for the config packets that wont't cause decoder
1164 guint nal_length_size;
1168 paybufs = g_ptr_array_new ();
1169 nal_length_size = rtph265pay->nal_length_size;
1171 while (size > nal_length_size) {
1175 for (i = 0; i < nal_length_size; i++) {
1176 nal_len = ((nal_len << 8) + data[i]);
1179 /* skip the length bytes, make sure we don't run past the buffer size */
1180 data += nal_length_size;
1181 offset += nal_length_size;
1182 size -= nal_length_size;
1184 if (size >= nal_len) {
1185 GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1188 GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1192 paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1194 g_ptr_array_add (paybufs, paybuf);
1196 /* If we're at the end of the buffer, then we're at the end of the
1199 GST_BUFFER_FLAG_UNSET (paybuf, GST_BUFFER_FLAG_MARKER);
1200 if (size - nal_len <= nal_length_size) {
1201 if (rtph265pay->alignment == GST_H265_ALIGNMENT_AU ||
1202 GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER))
1203 GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1210 ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1213 gboolean update = FALSE;
1216 /* get offset of first start code */
1217 next = next_start_code (data, size);
1219 /* skip to start code, if no start code is found, next will be size and we
1220 * will not collect data. */
1223 nal_queue = rtph265pay->queue;
1226 /* array must be empty when we get here */
1227 g_assert (nal_queue->len == 0);
1229 GST_DEBUG_OBJECT (basepayload,
1230 "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1232 paybufs = g_ptr_array_new ();
1234 /* first pass to locate NALs and parse VPS/SPS/PPS */
1236 /* skip start code */
1240 /* use next_start_code() to scan buffer.
1241 * next_start_code() returns the offset in data,
1242 * starting from zero to the first byte of 0.0.0.1
1243 * If no start code is found, it returns the value of the
1245 * data is unchanged by the call to next_start_code()
1247 next = next_start_code (data, size);
1249 if (next == size && buffer != NULL) {
1250 /* Didn't find the start of next NAL and it's not EOS,
1251 * handle it next time */
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 || buffer != NULL)
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_IS_SET (buffer, GST_BUFFER_FLAG_MARKER))
1312 GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1315 /* move to next NAL packet */
1316 /* Skips the trailing zeros */
1317 gst_adapter_flush (rtph265pay->adapter, nal_len - size);
1319 /* put the data in one or more RTP packets */
1320 ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1321 g_array_set_size (nal_queue, 0);
1326 gst_buffer_unmap (buffer, &map);
1327 gst_buffer_unref (buffer);
1329 gst_adapter_unmap (rtph265pay->adapter);
1336 GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1337 g_array_set_size (nal_queue, 0);
1338 ret = GST_FLOW_NOT_NEGOTIATED;
1344 gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1347 const GstStructure *s;
1348 GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (payload);
1350 switch (GST_EVENT_TYPE (event)) {
1351 case GST_EVENT_FLUSH_STOP:
1352 gst_adapter_clear (rtph265pay->adapter);
1354 case GST_EVENT_CUSTOM_DOWNSTREAM:
1355 s = gst_event_get_structure (event);
1356 if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1357 gboolean resend_codec_data;
1359 if (gst_structure_get_boolean (s, "all-headers",
1360 &resend_codec_data) && resend_codec_data)
1361 rtph265pay->send_vps_sps_pps = TRUE;
1366 /* call handle_buffer with NULL to flush last NAL from adapter
1367 * in byte-stream mode
1369 gst_rtp_h265_pay_handle_buffer (payload, NULL);
1372 case GST_EVENT_STREAM_START:
1373 GST_DEBUG_OBJECT (rtph265pay,
1374 "New stream detected => Clear VPS, SPS and PPS");
1375 gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1381 res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1386 static GstStateChangeReturn
1387 gst_rtp_h265_pay_change_state (GstElement * element, GstStateChange transition)
1389 GstStateChangeReturn ret;
1390 GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (element);
1392 switch (transition) {
1393 case GST_STATE_CHANGE_READY_TO_PAUSED:
1394 rtph265pay->send_vps_sps_pps = FALSE;
1395 gst_adapter_clear (rtph265pay->adapter);
1401 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1403 switch (transition) {
1404 case GST_STATE_CHANGE_PAUSED_TO_READY:
1405 rtph265pay->last_vps_sps_pps = -1;
1406 gst_rtp_h265_pay_clear_vps_sps_pps (rtph265pay);
1416 gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
1417 const GValue * value, GParamSpec * pspec)
1419 GstRtpH265Pay *rtph265pay;
1421 rtph265pay = GST_RTP_H265_PAY (object);
1424 case PROP_CONFIG_INTERVAL:
1425 rtph265pay->vps_sps_pps_interval = g_value_get_int (value);
1428 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1434 gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
1435 GValue * value, GParamSpec * pspec)
1437 GstRtpH265Pay *rtph265pay;
1439 rtph265pay = GST_RTP_H265_PAY (object);
1442 case PROP_CONFIG_INTERVAL:
1443 g_value_set_int (value, rtph265pay->vps_sps_pps_interval);
1446 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1452 gst_rtp_h265_pay_plugin_init (GstPlugin * plugin)
1454 return gst_element_register (plugin, "rtph265pay",
1455 GST_RANK_SECONDARY, GST_TYPE_RTP_H265_PAY);