1 /* ex: set tabstop=2 shiftwidth=2 expandtab: */
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
27 #include <gst/rtp/gstrtpbuffer.h>
28 #include <gst/pbutils/pbutils.h>
29 #include <gst/video/video.h>
31 /* Included to not duplicate gst_rtp_h264_add_sps_pps () */
32 #include "gstrtph264depay.h"
34 #include "gstrtph264pay.h"
35 #include "gstrtputils.h"
42 GST_DEBUG_CATEGORY_STATIC (rtph264pay_debug);
43 #define GST_CAT_DEFAULT (rtph264pay_debug)
50 static GstStaticPadTemplate gst_rtp_h264_pay_sink_template =
51 GST_STATIC_PAD_TEMPLATE ("sink",
54 GST_STATIC_CAPS ("video/x-h264, "
55 "stream-format = (string) avc, alignment = (string) au;"
57 "stream-format = (string) byte-stream, alignment = (string) { nal, au }")
60 static GstStaticPadTemplate gst_rtp_h264_pay_src_template =
61 GST_STATIC_PAD_TEMPLATE ("src",
64 GST_STATIC_CAPS ("application/x-rtp, "
65 "media = (string) \"video\", "
66 "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", "
67 "clock-rate = (int) 90000, " "encoding-name = (string) \"H264\"")
70 #define DEFAULT_SPROP_PARAMETER_SETS NULL
71 #define DEFAULT_CONFIG_INTERVAL 0
76 PROP_SPROP_PARAMETER_SETS,
80 #define IS_ACCESS_UNIT(x) (((x) > 0x00) && ((x) < 0x06))
82 static void gst_rtp_h264_pay_finalize (GObject * object);
84 static void gst_rtp_h264_pay_set_property (GObject * object, guint prop_id,
85 const GValue * value, GParamSpec * pspec);
86 static void gst_rtp_h264_pay_get_property (GObject * object, guint prop_id,
87 GValue * value, GParamSpec * pspec);
89 static GstCaps *gst_rtp_h264_pay_getcaps (GstRTPBasePayload * payload,
90 GstPad * pad, GstCaps * filter);
91 static gboolean gst_rtp_h264_pay_setcaps (GstRTPBasePayload * basepayload,
93 static GstFlowReturn gst_rtp_h264_pay_handle_buffer (GstRTPBasePayload * pad,
95 static gboolean gst_rtp_h264_pay_sink_event (GstRTPBasePayload * payload,
97 static GstStateChangeReturn gst_rtp_h264_pay_change_state (GstElement *
98 element, GstStateChange transition);
100 #define gst_rtp_h264_pay_parent_class parent_class
101 G_DEFINE_TYPE (GstRtpH264Pay, gst_rtp_h264_pay, GST_TYPE_RTP_BASE_PAYLOAD);
104 gst_rtp_h264_pay_class_init (GstRtpH264PayClass * klass)
106 GObjectClass *gobject_class;
107 GstElementClass *gstelement_class;
108 GstRTPBasePayloadClass *gstrtpbasepayload_class;
110 gobject_class = (GObjectClass *) klass;
111 gstelement_class = (GstElementClass *) klass;
112 gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
114 gobject_class->set_property = gst_rtp_h264_pay_set_property;
115 gobject_class->get_property = gst_rtp_h264_pay_get_property;
117 g_object_class_install_property (G_OBJECT_CLASS (klass),
118 PROP_SPROP_PARAMETER_SETS, g_param_spec_string ("sprop-parameter-sets",
119 "sprop-parameter-sets",
120 "The base64 sprop-parameter-sets to set in out caps (set to NULL to "
121 "extract from stream)",
122 DEFAULT_SPROP_PARAMETER_SETS,
123 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
125 g_object_class_install_property (G_OBJECT_CLASS (klass),
126 PROP_CONFIG_INTERVAL,
127 g_param_spec_int ("config-interval",
128 "SPS PPS Send Interval",
129 "Send SPS and PPS Insertion Interval in seconds (sprop parameter sets "
130 "will be multiplexed in the data stream when detected.) "
131 "(0 = disabled, -1 = send with every IDR frame)",
132 -1, 3600, DEFAULT_CONFIG_INTERVAL,
133 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
136 gobject_class->finalize = gst_rtp_h264_pay_finalize;
138 gst_element_class_add_static_pad_template (gstelement_class,
139 &gst_rtp_h264_pay_src_template);
140 gst_element_class_add_static_pad_template (gstelement_class,
141 &gst_rtp_h264_pay_sink_template);
143 gst_element_class_set_static_metadata (gstelement_class, "RTP H264 payloader",
144 "Codec/Payloader/Network/RTP",
145 "Payload-encode H264 video into RTP packets (RFC 3984)",
146 "Laurent Glayal <spglegle@yahoo.fr>");
148 gstelement_class->change_state =
149 GST_DEBUG_FUNCPTR (gst_rtp_h264_pay_change_state);
151 gstrtpbasepayload_class->get_caps = gst_rtp_h264_pay_getcaps;
152 gstrtpbasepayload_class->set_caps = gst_rtp_h264_pay_setcaps;
153 gstrtpbasepayload_class->handle_buffer = gst_rtp_h264_pay_handle_buffer;
154 gstrtpbasepayload_class->sink_event = gst_rtp_h264_pay_sink_event;
156 GST_DEBUG_CATEGORY_INIT (rtph264pay_debug, "rtph264pay", 0,
157 "H264 RTP Payloader");
161 gst_rtp_h264_pay_init (GstRtpH264Pay * rtph264pay)
163 rtph264pay->queue = g_array_new (FALSE, FALSE, sizeof (guint));
164 rtph264pay->profile = 0;
165 rtph264pay->sps = g_ptr_array_new_with_free_func (
166 (GDestroyNotify) gst_buffer_unref);
167 rtph264pay->pps = g_ptr_array_new_with_free_func (
168 (GDestroyNotify) gst_buffer_unref);
169 rtph264pay->last_spspps = -1;
170 rtph264pay->spspps_interval = DEFAULT_CONFIG_INTERVAL;
171 rtph264pay->delta_unit = FALSE;
172 rtph264pay->discont = FALSE;
174 rtph264pay->adapter = gst_adapter_new ();
178 gst_rtp_h264_pay_clear_sps_pps (GstRtpH264Pay * rtph264pay)
180 g_ptr_array_set_size (rtph264pay->sps, 0);
181 g_ptr_array_set_size (rtph264pay->pps, 0);
185 gst_rtp_h264_pay_finalize (GObject * object)
187 GstRtpH264Pay *rtph264pay;
189 rtph264pay = GST_RTP_H264_PAY (object);
191 g_array_free (rtph264pay->queue, TRUE);
193 g_ptr_array_free (rtph264pay->sps, TRUE);
194 g_ptr_array_free (rtph264pay->pps, TRUE);
196 g_free (rtph264pay->sprop_parameter_sets);
198 g_object_unref (rtph264pay->adapter);
200 G_OBJECT_CLASS (parent_class)->finalize (object);
203 static const gchar all_levels[][4] = {
223 gst_rtp_h264_pay_getcaps (GstRTPBasePayload * payload, GstPad * pad,
226 GstCaps *template_caps;
227 GstCaps *allowed_caps;
228 GstCaps *caps, *icaps;
229 gboolean append_unrestricted;
233 gst_pad_peer_query_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), NULL);
235 if (allowed_caps == NULL)
239 gst_static_pad_template_get_caps (&gst_rtp_h264_pay_sink_template);
241 if (gst_caps_is_any (allowed_caps)) {
242 caps = gst_caps_ref (template_caps);
246 if (gst_caps_is_empty (allowed_caps)) {
247 caps = gst_caps_ref (allowed_caps);
251 caps = gst_caps_new_empty ();
253 append_unrestricted = FALSE;
254 for (i = 0; i < gst_caps_get_size (allowed_caps); i++) {
255 GstStructure *s = gst_caps_get_structure (allowed_caps, i);
256 GstStructure *new_s = gst_structure_new_empty ("video/x-h264");
257 const gchar *profile_level_id;
259 profile_level_id = gst_structure_get_string (s, "profile-level-id");
261 if (profile_level_id && strlen (profile_level_id) == 6) {
262 const gchar *profile;
267 spsint = strtol (profile_level_id, NULL, 16);
268 sps[0] = spsint >> 16;
269 sps[1] = spsint >> 8;
272 profile = gst_codec_utils_h264_get_profile (sps, 3);
273 level = gst_codec_utils_h264_get_level (sps, 3);
275 if (profile && level) {
276 GST_LOG_OBJECT (payload, "In caps, have profile %s and level %s",
279 if (!strcmp (profile, "constrained-baseline"))
280 gst_structure_set (new_s, "profile", G_TYPE_STRING, profile, NULL);
283 GValue profiles = { 0, };
285 g_value_init (&profiles, GST_TYPE_LIST);
286 g_value_init (&val, G_TYPE_STRING);
288 g_value_set_static_string (&val, profile);
289 gst_value_list_append_value (&profiles, &val);
291 g_value_set_static_string (&val, "constrained-baseline");
292 gst_value_list_append_value (&profiles, &val);
294 gst_structure_take_value (new_s, "profile", &profiles);
297 if (!strcmp (level, "1"))
298 gst_structure_set (new_s, "level", G_TYPE_STRING, level, NULL);
300 GValue levels = { 0, };
304 g_value_init (&levels, GST_TYPE_LIST);
305 g_value_init (&val, G_TYPE_STRING);
307 for (j = 0; j < G_N_ELEMENTS (all_levels); j++) {
308 g_value_set_static_string (&val, all_levels[j]);
309 gst_value_list_prepend_value (&levels, &val);
310 if (!strcmp (level, all_levels[j]))
313 gst_structure_take_value (new_s, "level", &levels);
316 /* Invalid profile-level-id means baseline */
318 gst_structure_set (new_s,
319 "profile", G_TYPE_STRING, "constrained-baseline", NULL);
322 /* No profile-level-id means baseline or unrestricted */
324 gst_structure_set (new_s,
325 "profile", G_TYPE_STRING, "constrained-baseline", NULL);
326 append_unrestricted = TRUE;
329 caps = gst_caps_merge_structure (caps, new_s);
332 if (append_unrestricted) {
334 gst_caps_merge_structure (caps, gst_structure_new ("video/x-h264", NULL,
338 icaps = gst_caps_intersect (caps, template_caps);
339 gst_caps_unref (caps);
344 gst_caps_unref (template_caps);
345 gst_caps_unref (allowed_caps);
347 GST_LOG_OBJECT (payload, "returning caps %" GST_PTR_FORMAT, caps);
351 /* take the currently configured SPS and PPS lists and set them on the caps as
352 * sprop-parameter-sets */
354 gst_rtp_h264_pay_set_sps_pps (GstRTPBasePayload * basepayload)
356 GstRtpH264Pay *payloader = GST_RTP_H264_PAY (basepayload);
365 sprops = g_string_new ("");
368 /* build the sprop-parameter-sets */
369 for (i = 0; i < payloader->sps->len; i++) {
371 GST_BUFFER_CAST (g_ptr_array_index (payloader->sps, i));
373 gst_buffer_map (sps_buf, &map, GST_MAP_READ);
374 set = g_base64_encode (map.data, map.size);
375 gst_buffer_unmap (sps_buf, &map);
377 g_string_append_printf (sprops, "%s%s", count ? "," : "", set);
381 for (i = 0; i < payloader->pps->len; i++) {
383 GST_BUFFER_CAST (g_ptr_array_index (payloader->pps, i));
385 gst_buffer_map (pps_buf, &map, GST_MAP_READ);
386 set = g_base64_encode (map.data, map.size);
387 gst_buffer_unmap (pps_buf, &map);
389 g_string_append_printf (sprops, "%s%s", count ? "," : "", set);
394 if (G_LIKELY (count)) {
395 if (payloader->profile != 0) {
396 /* profile is 24 bit. Force it to respect the limit */
397 profile = g_strdup_printf ("%06x", payloader->profile & 0xffffff);
398 /* combine into output caps */
399 res = gst_rtp_base_payload_set_outcaps (basepayload,
400 "packetization-mode", G_TYPE_STRING, "1",
401 "profile-level-id", G_TYPE_STRING, profile,
402 "sprop-parameter-sets", G_TYPE_STRING, sprops->str, NULL);
405 res = gst_rtp_base_payload_set_outcaps (basepayload,
406 "packetization-mode", G_TYPE_STRING, "1",
407 "sprop-parameter-sets", G_TYPE_STRING, sprops->str, NULL);
411 res = gst_rtp_base_payload_set_outcaps (basepayload, NULL);
413 g_string_free (sprops, TRUE);
420 gst_rtp_h264_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
422 GstRtpH264Pay *rtph264pay;
429 const gchar *alignment, *stream_format;
431 rtph264pay = GST_RTP_H264_PAY (basepayload);
433 str = gst_caps_get_structure (caps, 0);
435 /* we can only set the output caps when we found the sprops and profile
437 gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "H264", 90000);
439 rtph264pay->alignment = GST_H264_ALIGNMENT_UNKNOWN;
440 alignment = gst_structure_get_string (str, "alignment");
442 if (g_str_equal (alignment, "au"))
443 rtph264pay->alignment = GST_H264_ALIGNMENT_AU;
444 if (g_str_equal (alignment, "nal"))
445 rtph264pay->alignment = GST_H264_ALIGNMENT_NAL;
448 rtph264pay->stream_format = GST_H264_STREAM_FORMAT_UNKNOWN;
449 stream_format = gst_structure_get_string (str, "stream-format");
451 if (g_str_equal (stream_format, "avc"))
452 rtph264pay->stream_format = GST_H264_STREAM_FORMAT_AVC;
453 if (g_str_equal (stream_format, "byte-stream"))
454 rtph264pay->stream_format = GST_H264_STREAM_FORMAT_BYTESTREAM;
457 /* packetized AVC video has a codec_data */
458 if ((value = gst_structure_get_value (str, "codec_data"))) {
459 guint num_sps, num_pps;
462 GST_DEBUG_OBJECT (rtph264pay, "have packetized h264");
464 buffer = gst_value_get_buffer (value);
466 gst_buffer_map (buffer, &map, GST_MAP_READ);
470 /* parse the avcC data */
473 /* parse the version, this must be 1 */
477 /* AVCProfileIndication */
479 /* AVCLevelIndication */
480 rtph264pay->profile = (data[1] << 16) | (data[2] << 8) | data[3];
481 GST_DEBUG_OBJECT (rtph264pay, "profile %06x", rtph264pay->profile);
483 /* 6 bits reserved | 2 bits lengthSizeMinusOne */
484 /* this is the number of bytes in front of the NAL units to mark their
486 rtph264pay->nal_length_size = (data[4] & 0x03) + 1;
487 GST_DEBUG_OBJECT (rtph264pay, "nal length %u", rtph264pay->nal_length_size);
488 /* 3 bits reserved | 5 bits numOfSequenceParameterSets */
489 num_sps = data[5] & 0x1f;
490 GST_DEBUG_OBJECT (rtph264pay, "num SPS %u", num_sps);
495 /* create the sprop-parameter-sets */
496 for (i = 0; i < num_sps; i++) {
502 nal_size = (data[0] << 8) | data[1];
506 GST_LOG_OBJECT (rtph264pay, "SPS %d size %d", i, nal_size);
511 /* make a buffer out of it and add to SPS list */
512 sps_buf = gst_buffer_new_and_alloc (nal_size);
513 gst_buffer_fill (sps_buf, 0, data, nal_size);
514 gst_rtp_h264_add_sps_pps (GST_ELEMENT (rtph264pay), rtph264pay->sps,
515 rtph264pay->pps, sps_buf);
522 /* 8 bits numOfPictureParameterSets */
527 GST_DEBUG_OBJECT (rtph264pay, "num PPS %u", num_pps);
528 for (i = 0; i < num_pps; i++) {
534 nal_size = (data[0] << 8) | data[1];
538 GST_LOG_OBJECT (rtph264pay, "PPS %d size %d", i, nal_size);
543 /* make a buffer out of it and add to PPS list */
544 pps_buf = gst_buffer_new_and_alloc (nal_size);
545 gst_buffer_fill (pps_buf, 0, data, nal_size);
546 gst_rtp_h264_add_sps_pps (GST_ELEMENT (rtph264pay), rtph264pay->sps,
547 rtph264pay->pps, pps_buf);
553 /* and update the caps with the collected data */
554 if (!gst_rtp_h264_pay_set_sps_pps (basepayload))
555 goto set_sps_pps_failed;
557 gst_buffer_unmap (buffer, &map);
559 GST_DEBUG_OBJECT (rtph264pay, "have bytestream h264");
566 GST_ERROR_OBJECT (rtph264pay, "avcC size %" G_GSIZE_FORMAT " < 7", size);
571 GST_ERROR_OBJECT (rtph264pay, "wrong avcC version");
576 GST_ERROR_OBJECT (rtph264pay, "avcC too small ");
581 GST_ERROR_OBJECT (rtph264pay, "failed to set sps/pps");
586 gst_buffer_unmap (buffer, &map);
592 gst_rtp_h264_pay_parse_sprop_parameter_sets (GstRtpH264Pay * rtph264pay)
600 ps = rtph264pay->sprop_parameter_sets;
604 gst_rtp_h264_pay_clear_sps_pps (rtph264pay);
606 params = g_strsplit (ps, ",", 0);
607 len = g_strv_length (params);
609 GST_DEBUG_OBJECT (rtph264pay, "we have %d params", len);
611 for (i = 0; params[i]; i++) {
618 nal_len = strlen (params[i]);
619 buf = gst_buffer_new_and_alloc (nal_len);
621 gst_buffer_map (buf, &map, GST_MAP_WRITE);
623 nal_len = g_base64_decode_step (params[i], nal_len, nalp, &state, &save);
624 gst_buffer_unmap (buf, &map);
625 gst_buffer_resize (buf, 0, nal_len);
628 gst_buffer_unref (buf);
632 gst_rtp_h264_add_sps_pps (GST_ELEMENT (rtph264pay), rtph264pay->sps,
633 rtph264pay->pps, buf);
639 next_start_code (const guint8 * data, guint size)
641 /* Boyer-Moore string matching algorithm, in a degenerative
642 * sense because our search 'alphabet' is binary - 0 & 1 only.
643 * This allow us to simplify the general BM algorithm to a very
645 /* assume 1 is in the 3th byte */
648 while (offset < size) {
649 if (1 == data[offset]) {
650 unsigned int shift = offset;
652 if (0 == data[--shift]) {
653 if (0 == data[--shift]) {
657 /* The jump is always 3 because of the 1 previously matched.
658 * All the 0's must be after this '1' matched at offset */
660 } else if (0 == data[offset]) {
661 /* maybe next byte is 1? */
664 /* can jump 3 bytes forward */
667 /* at each iteration, we rescan in a backward manner until
668 * we match 0.0.1 in reverse order. Since our search string
669 * has only 2 'alpabets' (i.e. 0 & 1), we know that any
670 * mismatch will force us to shift a fixed number of steps */
672 GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
678 gst_rtp_h264_pay_decode_nal (GstRtpH264Pay * payloader,
679 const guint8 * data, guint size, GstClockTime dts, GstClockTime pts)
684 /* default is no update */
687 GST_DEBUG ("NAL payload len=%u", size);
690 type = header & 0x1f;
692 /* We record the timestamp of the last SPS/PPS so
693 * that we can insert them at regular intervals and when needed. */
694 if (SPS_TYPE_ID == type || PPS_TYPE_ID == type) {
697 /* encode the entire SPS NAL in base64 */
698 GST_DEBUG ("Found %s %x %x %x Len=%u", type == SPS_TYPE_ID ? "SPS" : "PPS",
699 (header >> 7), (header >> 5) & 3, type, size);
701 nal = gst_buffer_new_allocate (NULL, size, NULL);
702 gst_buffer_fill (nal, 0, data, size);
704 updated = gst_rtp_h264_add_sps_pps (GST_ELEMENT (payloader),
705 payloader->sps, payloader->pps, nal);
707 /* remember when we last saw SPS */
708 if (updated && pts != -1)
709 payloader->last_spspps = pts;
711 GST_DEBUG ("NAL: %x %x %x Len = %u", (header >> 7),
712 (header >> 5) & 3, type, size);
719 gst_rtp_h264_pay_payload_nal (GstRTPBasePayload * basepayload,
720 GstBuffer * paybuf, GstClockTime dts, GstClockTime pts, gboolean end_of_au,
721 gboolean delta_unit, gboolean discont);
724 gst_rtp_h264_pay_send_sps_pps (GstRTPBasePayload * basepayload,
725 GstRtpH264Pay * rtph264pay, GstClockTime dts, GstClockTime pts)
727 GstFlowReturn ret = GST_FLOW_OK;
728 gboolean sent_all_sps_pps = TRUE;
731 for (i = 0; i < rtph264pay->sps->len; i++) {
733 GST_BUFFER_CAST (g_ptr_array_index (rtph264pay->sps, i));
735 GST_DEBUG_OBJECT (rtph264pay, "inserting SPS in the stream");
737 ret = gst_rtp_h264_pay_payload_nal (basepayload, gst_buffer_ref (sps_buf),
738 dts, pts, FALSE, FALSE, FALSE);
739 /* Not critical here; but throw a warning */
740 if (ret != GST_FLOW_OK) {
741 sent_all_sps_pps = FALSE;
742 GST_WARNING_OBJECT (basepayload, "Problem pushing SPS");
745 for (i = 0; i < rtph264pay->pps->len; i++) {
747 GST_BUFFER_CAST (g_ptr_array_index (rtph264pay->pps, i));
749 GST_DEBUG_OBJECT (rtph264pay, "inserting PPS in the stream");
751 ret = gst_rtp_h264_pay_payload_nal (basepayload, gst_buffer_ref (pps_buf),
752 dts, pts, FALSE, FALSE, FALSE);
753 /* Not critical here; but throw a warning */
754 if (ret != GST_FLOW_OK) {
755 sent_all_sps_pps = FALSE;
756 GST_WARNING_OBJECT (basepayload, "Problem pushing PPS");
760 if (pts != -1 && sent_all_sps_pps)
761 rtph264pay->last_spspps = pts;
766 /* @delta_unit: if %FALSE the first packet sent won't have the
767 * GST_BUFFER_FLAG_DELTA_UNIT flag.
768 * @discont: if %TRUE the first packet sent will have the
769 * GST_BUFFER_FLAG_DISCONT flag.
772 gst_rtp_h264_pay_payload_nal (GstRTPBasePayload * basepayload,
773 GstBuffer * paybuf, GstClockTime dts, GstClockTime pts, gboolean end_of_au,
774 gboolean delta_unit, gboolean discont)
776 GstRtpH264Pay *rtph264pay;
780 guint packet_len, payload_len, mtu;
783 GstBufferList *list = NULL;
784 gboolean send_spspps;
785 GstRTPBuffer rtp = { NULL };
786 guint size = gst_buffer_get_size (paybuf);
788 rtph264pay = GST_RTP_H264_PAY (basepayload);
789 mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph264pay);
791 gst_buffer_extract (paybuf, 0, &nalHeader, 1);
792 nalType = nalHeader & 0x1f;
794 GST_DEBUG_OBJECT (rtph264pay, "Processing Buffer with NAL TYPE=%d", nalType);
796 /* should set src caps before pushing stuff,
797 * and if we did not see enough SPS/PPS, that may not be the case */
798 if (G_UNLIKELY (!gst_pad_has_current_caps (GST_RTP_BASE_PAYLOAD_SRCPAD
800 gst_rtp_h264_pay_set_sps_pps (basepayload);
804 /* check if we need to emit an SPS/PPS now */
805 if (nalType == IDR_TYPE_ID && rtph264pay->spspps_interval > 0) {
806 if (rtph264pay->last_spspps != -1) {
809 GST_LOG_OBJECT (rtph264pay,
810 "now %" GST_TIME_FORMAT ", last SPS/PPS %" GST_TIME_FORMAT,
811 GST_TIME_ARGS (pts), GST_TIME_ARGS (rtph264pay->last_spspps));
813 /* calculate diff between last SPS/PPS in milliseconds */
814 if (pts > rtph264pay->last_spspps)
815 diff = pts - rtph264pay->last_spspps;
819 GST_DEBUG_OBJECT (rtph264pay,
820 "interval since last SPS/PPS %" GST_TIME_FORMAT,
821 GST_TIME_ARGS (diff));
823 /* bigger than interval, queue SPS/PPS */
824 if (GST_TIME_AS_SECONDS (diff) >= rtph264pay->spspps_interval) {
825 GST_DEBUG_OBJECT (rtph264pay, "time to send SPS/PPS");
829 /* no know previous SPS/PPS time, send now */
830 GST_DEBUG_OBJECT (rtph264pay, "no previous SPS/PPS time, send now");
833 } else if (nalType == IDR_TYPE_ID && rtph264pay->spspps_interval == -1) {
834 GST_DEBUG_OBJECT (rtph264pay, "sending SPS/PPS before current IDR frame");
835 /* send SPS/PPS before every IDR frame */
839 if (send_spspps || rtph264pay->send_spspps) {
840 /* we need to send SPS/PPS now first. FIXME, don't use the pts for
841 * checking when we need to send SPS/PPS but convert to running_time first. */
842 rtph264pay->send_spspps = FALSE;
843 ret = gst_rtp_h264_pay_send_sps_pps (basepayload, rtph264pay, dts, pts);
844 if (ret != GST_FLOW_OK) {
845 gst_buffer_unref (paybuf);
850 packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
852 if (packet_len < mtu) {
853 /* will fit in one packet */
854 GST_DEBUG_OBJECT (basepayload,
855 "NAL Unit fit in one packet datasize=%d mtu=%d", size, mtu);
857 /* create buffer without payload containing only the RTP header
858 * (memory block at index 0) */
859 outbuf = gst_rtp_buffer_new_allocate (0, 0, 0);
861 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
863 /* only set the marker bit on packets containing access units */
864 if (IS_ACCESS_UNIT (nalType) && end_of_au) {
865 gst_rtp_buffer_set_marker (&rtp, 1);
868 /* timestamp the outbuffer */
869 GST_BUFFER_PTS (outbuf) = pts;
870 GST_BUFFER_DTS (outbuf) = dts;
873 /* Only the first packet sent should not have the flag */
876 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
879 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
880 /* Only the first packet sent should have the flag */
884 gst_rtp_buffer_unmap (&rtp);
886 /* insert payload memory block */
887 gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph264pay), outbuf, paybuf,
888 g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
889 outbuf = gst_buffer_append (outbuf, paybuf);
891 /* push the buffer to the next element */
892 ret = gst_rtp_base_payload_push (basepayload, outbuf);
894 /* fragmentation Units FU-A */
896 int ii = 0, start = 1, end = 0, pos = 0;
898 GST_DEBUG_OBJECT (basepayload,
899 "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
906 GST_DEBUG_OBJECT (basepayload, "Using FU-A fragmentation for data size=%d",
909 /* We keep 2 bytes for FU indicator and FU Header */
910 payload_len = gst_rtp_buffer_calc_payload_len (mtu - 2, 0, 0);
912 list = gst_buffer_list_new_sized ((size / payload_len) + 1);
915 limitedSize = size < payload_len ? size : payload_len;
916 GST_DEBUG_OBJECT (basepayload,
917 "Inside FU-A fragmentation limitedSize=%d iteration=%d", limitedSize,
921 * create buffer without payload containing only the RTP header
922 * (memory block at index 0) */
923 outbuf = gst_rtp_buffer_new_allocate (2, 0, 0);
925 gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
927 GST_BUFFER_DTS (outbuf) = dts;
928 GST_BUFFER_PTS (outbuf) = pts;
929 payload = gst_rtp_buffer_get_payload (&rtp);
931 if (limitedSize == size) {
932 GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
935 if (IS_ACCESS_UNIT (nalType)) {
936 gst_rtp_buffer_set_marker (&rtp, end && end_of_au);
940 payload[0] = (nalHeader & 0x60) | 28;
943 payload[1] = (start << 7) | (end << 6) | (nalHeader & 0x1f);
945 gst_rtp_buffer_unmap (&rtp);
947 /* insert payload memory block */
948 gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph264pay), outbuf, paybuf,
949 g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
950 gst_buffer_copy_into (outbuf, paybuf, GST_BUFFER_COPY_MEMORY, pos,
954 /* Only the first packet sent should not have the flag */
957 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
960 GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
961 /* Only the first packet sent should have the flag */
965 /* add the buffer to the buffer list */
966 gst_buffer_list_add (list, outbuf);
975 ret = gst_rtp_base_payload_push_list (basepayload, list);
976 gst_buffer_unref (paybuf);
982 gst_rtp_h264_pay_handle_buffer (GstRTPBasePayload * basepayload,
985 GstRtpH264Pay *rtph264pay;
991 GstClockTime dts, pts;
994 GstBuffer *paybuf = NULL;
996 gboolean delayed_not_delta_unit = FALSE;
997 gboolean delayed_discont = FALSE;
999 rtph264pay = GST_RTP_H264_PAY (basepayload);
1001 /* the input buffer contains one or more NAL units */
1003 avc = rtph264pay->stream_format == GST_H264_STREAM_FORMAT_AVC;
1006 /* In AVC mode, there is no adapter, so nothign to flush */
1009 gst_buffer_map (buffer, &map, GST_MAP_READ);
1012 pts = GST_BUFFER_PTS (buffer);
1013 dts = GST_BUFFER_DTS (buffer);
1014 rtph264pay->delta_unit = GST_BUFFER_FLAG_IS_SET (buffer,
1015 GST_BUFFER_FLAG_DELTA_UNIT);
1016 rtph264pay->discont = GST_BUFFER_IS_DISCONT (buffer);
1017 GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1019 dts = gst_adapter_prev_dts (rtph264pay->adapter, NULL);
1020 pts = gst_adapter_prev_pts (rtph264pay->adapter, NULL);
1022 if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
1023 if (gst_adapter_available (rtph264pay->adapter) == 0)
1024 rtph264pay->delta_unit = FALSE;
1026 /* This buffer contains a key frame but the adapter isn't empty. So
1027 * we'll purge it first by sending a first packet and then the second
1028 * one won't have the DELTA_UNIT flag. */
1029 delayed_not_delta_unit = TRUE;
1032 if (GST_BUFFER_IS_DISCONT (buffer)) {
1033 if (gst_adapter_available (rtph264pay->adapter) == 0)
1034 rtph264pay->discont = TRUE;
1036 /* This buffer has the DISCONT flag but the adapter isn't empty. So
1037 * we'll purge it first by sending a first packet and then the second
1038 * one will have the DISCONT flag set. */
1039 delayed_discont = TRUE;
1042 if (!GST_CLOCK_TIME_IS_VALID (dts))
1043 dts = GST_BUFFER_DTS (buffer);
1044 if (!GST_CLOCK_TIME_IS_VALID (pts))
1045 pts = GST_BUFFER_PTS (buffer);
1047 gst_adapter_push (rtph264pay->adapter, buffer);
1049 size = gst_adapter_available (rtph264pay->adapter);
1050 /* Nothing to do here if the adapter is empty, e.g. on EOS */
1053 data = gst_adapter_map (rtph264pay->adapter, size);
1054 GST_DEBUG_OBJECT (basepayload,
1055 "got %" G_GSIZE_FORMAT " bytes (%" G_GSIZE_FORMAT ")", size,
1056 buffer ? gst_buffer_get_size (buffer) : 0);
1061 /* now loop over all NAL units and put them in a packet
1062 * FIXME, we should really try to pack multiple NAL units into one RTP packet
1063 * if we can, especially for the config packets that wont't cause decoder
1066 guint nal_length_size;
1069 nal_length_size = rtph264pay->nal_length_size;
1071 while (size > nal_length_size) {
1073 gboolean end_of_au = FALSE;
1076 for (i = 0; i < nal_length_size; i++) {
1077 nal_len = ((nal_len << 8) + data[i]);
1080 /* skip the length bytes, make sure we don't run past the buffer size */
1081 data += nal_length_size;
1082 offset += nal_length_size;
1083 size -= nal_length_size;
1085 if (size >= nal_len) {
1086 GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1089 GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1093 /* If we're at the end of the buffer, then we're at the end of the
1096 if (rtph264pay->alignment == GST_H264_ALIGNMENT_AU
1097 && size - nal_len <= nal_length_size) {
1101 paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1104 gst_rtp_h264_pay_payload_nal (basepayload, paybuf, dts, pts,
1105 end_of_au, rtph264pay->delta_unit, rtph264pay->discont);
1107 if (!rtph264pay->delta_unit)
1108 /* Only the first outgoing packet doesn't have the DELTA_UNIT flag */
1109 rtph264pay->delta_unit = TRUE;
1111 if (rtph264pay->discont)
1112 /* Only the first outgoing packet have the DISCONT flag */
1113 rtph264pay->discont = FALSE;
1115 if (ret != GST_FLOW_OK)
1124 gboolean update = FALSE;
1126 /* get offset of first start code */
1127 next = next_start_code (data, size);
1129 /* skip to start code, if no start code is found, next will be size and we
1130 * will not collect data. */
1133 nal_queue = rtph264pay->queue;
1136 /* array must be empty when we get here */
1137 g_assert (nal_queue->len == 0);
1139 GST_DEBUG_OBJECT (basepayload,
1140 "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1142 /* first pass to locate NALs and parse SPS/PPS */
1144 /* skip start code */
1148 /* use next_start_code() to scan buffer.
1149 * next_start_code() returns the offset in data,
1150 * starting from zero to the first byte of 0.0.0.1
1151 * If no start code is found, it returns the value of the
1153 * data is unchanged by the call to next_start_code()
1155 next = next_start_code (data, size);
1157 /* nal or au aligned input needs no delaying until next time */
1158 if (next == size && buffer != NULL &&
1159 rtph264pay->alignment == GST_H264_ALIGNMENT_UNKNOWN) {
1160 /* Didn't find the start of next NAL and it's not EOS,
1161 * handle it next time */
1165 /* nal length is distance to next start code */
1168 GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1171 if (rtph264pay->sprop_parameter_sets != NULL) {
1172 /* explicitly set profile and sprop, use those */
1173 if (rtph264pay->update_caps) {
1174 if (!gst_rtp_base_payload_set_outcaps (basepayload,
1175 "sprop-parameter-sets", G_TYPE_STRING,
1176 rtph264pay->sprop_parameter_sets, NULL))
1179 /* parse SPS and PPS from provided parameter set (for insertion) */
1180 gst_rtp_h264_pay_parse_sprop_parameter_sets (rtph264pay);
1182 rtph264pay->update_caps = FALSE;
1184 GST_DEBUG ("outcaps update: sprop-parameter-sets=%s",
1185 rtph264pay->sprop_parameter_sets);
1188 /* We know our stream is a valid H264 NAL packet,
1189 * go parse it for SPS/PPS to enrich the caps */
1190 /* order: make sure to check nal */
1192 gst_rtp_h264_pay_decode_nal (rtph264pay, data, nal_len, dts, pts)
1195 /* move to next NAL packet */
1199 g_array_append_val (nal_queue, nal_len);
1202 /* if has new SPS & PPS, update the output caps */
1203 if (G_UNLIKELY (update))
1204 if (!gst_rtp_h264_pay_set_sps_pps (basepayload))
1207 /* second pass to payload and push */
1209 if (nal_queue->len != 0)
1210 gst_adapter_flush (rtph264pay->adapter, skip);
1212 for (i = 0; i < nal_queue->len; i++) {
1214 gboolean end_of_au = FALSE;
1216 nal_len = g_array_index (nal_queue, guint, i);
1217 /* skip start code */
1218 gst_adapter_flush (rtph264pay->adapter, 3);
1220 /* Trim the end unless we're the last NAL in the stream.
1221 * In case we're not at the end of the buffer we know the next block
1222 * starts with 0x000001 so all the 0x00 bytes at the end of this one are
1223 * trailing 0x0 that can be discarded */
1225 data = gst_adapter_map (rtph264pay->adapter, size);
1226 if (i + 1 != nal_queue->len || buffer != NULL)
1227 for (; size > 1 && data[size - 1] == 0x0; size--)
1231 /* If it's the last nal unit we have in non-bytestream mode, we can
1232 * assume it's the end of an access-unit
1234 * FIXME: We need to wait until the next packet or EOS to
1235 * actually payload the NAL so we can know if the current NAL is
1236 * the last one of an access unit or not if we are in bytestream mode
1238 if ((rtph264pay->alignment == GST_H264_ALIGNMENT_AU || buffer == NULL) &&
1239 i == nal_queue->len - 1)
1241 paybuf = gst_adapter_take_buffer (rtph264pay->adapter, size);
1244 /* put the data in one or more RTP packets */
1246 gst_rtp_h264_pay_payload_nal (basepayload, paybuf, dts, pts,
1247 end_of_au, rtph264pay->delta_unit, rtph264pay->discont);
1249 if (delayed_not_delta_unit) {
1250 rtph264pay->delta_unit = FALSE;
1251 delayed_not_delta_unit = FALSE;
1253 /* Only the first outgoing packet doesn't have the DELTA_UNIT flag */
1254 rtph264pay->delta_unit = TRUE;
1257 if (delayed_discont) {
1258 rtph264pay->discont = TRUE;
1259 delayed_discont = FALSE;
1261 /* Only the first outgoing packet have the DISCONT flag */
1262 rtph264pay->discont = FALSE;
1265 if (ret != GST_FLOW_OK) {
1269 /* move to next NAL packet */
1270 /* Skips the trailing zeros */
1271 gst_adapter_flush (rtph264pay->adapter, nal_len - size);
1273 g_array_set_size (nal_queue, 0);
1278 gst_buffer_unmap (buffer, &map);
1279 gst_buffer_unref (buffer);
1281 gst_adapter_unmap (rtph264pay->adapter);
1288 GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1289 g_array_set_size (nal_queue, 0);
1290 ret = GST_FLOW_NOT_NEGOTIATED;
1296 gst_rtp_h264_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1299 const GstStructure *s;
1300 GstRtpH264Pay *rtph264pay = GST_RTP_H264_PAY (payload);
1302 switch (GST_EVENT_TYPE (event)) {
1303 case GST_EVENT_FLUSH_STOP:
1304 gst_adapter_clear (rtph264pay->adapter);
1306 case GST_EVENT_CUSTOM_DOWNSTREAM:
1307 s = gst_event_get_structure (event);
1308 if (gst_structure_has_name (s, "GstForceKeyUnit")) {
1309 gboolean resend_codec_data;
1311 if (gst_structure_get_boolean (s, "all-headers",
1312 &resend_codec_data) && resend_codec_data)
1313 rtph264pay->send_spspps = TRUE;
1318 /* call handle_buffer with NULL to flush last NAL from adapter
1319 * in byte-stream mode
1321 gst_rtp_h264_pay_handle_buffer (payload, NULL);
1324 case GST_EVENT_STREAM_START:
1325 GST_DEBUG_OBJECT (rtph264pay, "New stream detected => Clear SPS and PPS");
1326 gst_rtp_h264_pay_clear_sps_pps (rtph264pay);
1332 res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1337 static GstStateChangeReturn
1338 gst_rtp_h264_pay_change_state (GstElement * element, GstStateChange transition)
1340 GstStateChangeReturn ret;
1341 GstRtpH264Pay *rtph264pay = GST_RTP_H264_PAY (element);
1343 switch (transition) {
1344 case GST_STATE_CHANGE_READY_TO_PAUSED:
1345 rtph264pay->send_spspps = FALSE;
1346 gst_adapter_clear (rtph264pay->adapter);
1352 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1354 switch (transition) {
1355 case GST_STATE_CHANGE_PAUSED_TO_READY:
1356 rtph264pay->last_spspps = -1;
1357 gst_rtp_h264_pay_clear_sps_pps (rtph264pay);
1367 gst_rtp_h264_pay_set_property (GObject * object, guint prop_id,
1368 const GValue * value, GParamSpec * pspec)
1370 GstRtpH264Pay *rtph264pay;
1372 rtph264pay = GST_RTP_H264_PAY (object);
1375 case PROP_SPROP_PARAMETER_SETS:
1376 g_free (rtph264pay->sprop_parameter_sets);
1377 rtph264pay->sprop_parameter_sets = g_value_dup_string (value);
1378 rtph264pay->update_caps = TRUE;
1380 case PROP_CONFIG_INTERVAL:
1381 rtph264pay->spspps_interval = g_value_get_int (value);
1384 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1390 gst_rtp_h264_pay_get_property (GObject * object, guint prop_id,
1391 GValue * value, GParamSpec * pspec)
1393 GstRtpH264Pay *rtph264pay;
1395 rtph264pay = GST_RTP_H264_PAY (object);
1398 case PROP_SPROP_PARAMETER_SETS:
1399 g_value_set_string (value, rtph264pay->sprop_parameter_sets);
1401 case PROP_CONFIG_INTERVAL:
1402 g_value_set_int (value, rtph264pay->spspps_interval);
1405 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1411 gst_rtp_h264_pay_plugin_init (GstPlugin * plugin)
1413 return gst_element_register (plugin, "rtph264pay",
1414 GST_RANK_SECONDARY, GST_TYPE_RTP_H264_PAY);