1 /* GStreamer
2  * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com>
3  * Copyright (C) <2014> Jurgen Slowack <jurgenslowack@gmail.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24 
25 #include <string.h>
26 #include <stdlib.h>
27 
28 #include <gst/rtp/gstrtpbuffer.h>
29 #include <gst/pbutils/pbutils.h>
30 #include <gst/video/video.h>
31 
32 /* Included to not duplicate gst_rtp_h265_add_vps_sps_pps () */
33 #include "gstrtph265depay.h"
34 
35 #include "gstrtph265pay.h"
36 #include "gstrtputils.h"
37 
38 GST_DEBUG_CATEGORY_STATIC (rtph265pay_debug);
39 #define GST_CAT_DEFAULT (rtph265pay_debug)
40 
41 /* references:
42  *
43  * Internet Draft RTP Payload Format for High Efficiency Video Coding
44  *
45  *                   draft-ietf-payload-rtp-h265-03.txt
46  *
47  * This draft will be replaced with an RFC, so some details may change.
48  *
49  */
50 
51 static GstStaticPadTemplate gst_rtp_h265_pay_sink_template =
52     GST_STATIC_PAD_TEMPLATE ("sink",
53     GST_PAD_SINK,
54     GST_PAD_ALWAYS,
55     GST_STATIC_CAPS (
56         /* only hvc1 and byte-stream formats supported for now */
57         "video/x-h265, stream-format = (string) hvc1, alignment = (string) au; "
58         /* "video/x-h265, "
59            "stream-format = (string) hev1, alignment = (string) au; " */
60         "video/x-h265, stream-format = (string) byte-stream, "
61         "alignment = (string) { nal, au }")
62     );
63 
64 static GstStaticPadTemplate gst_rtp_h265_pay_src_template =
65 GST_STATIC_PAD_TEMPLATE ("src",
66     GST_PAD_SRC,
67     GST_PAD_ALWAYS,
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, " */
102     );
103 
104 #define DEFAULT_CONFIG_INTERVAL		      0
105 
106 enum
107 {
108   PROP_0,
109   PROP_CONFIG_INTERVAL
110 };
111 
112 static void gst_rtp_h265_pay_finalize (GObject * object);
113 
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);
118 
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,
122     GstCaps * caps);
123 static GstFlowReturn gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * pad,
124     GstBuffer * buffer);
125 static gboolean gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload,
126     GstEvent * event);
127 static GstStateChangeReturn gst_rtp_h265_pay_change_state (GstElement *
128     element, GstStateChange transition);
129 
130 #define gst_rtp_h265_pay_parent_class parent_class
131 G_DEFINE_TYPE (GstRtpH265Pay, gst_rtp_h265_pay, GST_TYPE_RTP_BASE_PAYLOAD);
132 
133 static void
gst_rtp_h265_pay_class_init(GstRtpH265PayClass * klass)134 gst_rtp_h265_pay_class_init (GstRtpH265PayClass * klass)
135 {
136   GObjectClass *gobject_class;
137   GstElementClass *gstelement_class;
138   GstRTPBasePayloadClass *gstrtpbasepayload_class;
139 
140   gobject_class = (GObjectClass *) klass;
141   gstelement_class = (GstElementClass *) klass;
142   gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass;
143 
144   gobject_class->set_property = gst_rtp_h265_pay_set_property;
145   gobject_class->get_property = gst_rtp_h265_pay_get_property;
146 
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)
156       );
157 
158   gobject_class->finalize = gst_rtp_h265_pay_finalize;
159 
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);
164 
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>");
169 
170   gstelement_class->change_state =
171       GST_DEBUG_FUNCPTR (gst_rtp_h265_pay_change_state);
172 
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;
177 
178   GST_DEBUG_CATEGORY_INIT (rtph265pay_debug, "rtph265pay", 0,
179       "H265 RTP Payloader");
180 }
181 
182 static void
gst_rtp_h265_pay_init(GstRtpH265Pay * rtph265pay)183 gst_rtp_h265_pay_init (GstRtpH265Pay * rtph265pay)
184 {
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;
194 
195   rtph265pay->adapter = gst_adapter_new ();
196 }
197 
198 static void
gst_rtp_h265_pay_clear_vps_sps_pps(GstRtpH265Pay * rtph265pay)199 gst_rtp_h265_pay_clear_vps_sps_pps (GstRtpH265Pay * rtph265pay)
200 {
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);
204 }
205 
206 static void
gst_rtp_h265_pay_finalize(GObject * object)207 gst_rtp_h265_pay_finalize (GObject * object)
208 {
209   GstRtpH265Pay *rtph265pay;
210 
211   rtph265pay = GST_RTP_H265_PAY (object);
212 
213   g_array_free (rtph265pay->queue, TRUE);
214 
215   g_ptr_array_free (rtph265pay->sps, TRUE);
216   g_ptr_array_free (rtph265pay->pps, TRUE);
217   g_ptr_array_free (rtph265pay->vps, TRUE);
218 
219   g_object_unref (rtph265pay->adapter);
220 
221   G_OBJECT_CLASS (parent_class)->finalize (object);
222 }
223 
224 static const gchar all_levels[][4] = {
225   "1",
226   "2",
227   "2.1",
228   "3",
229   "3.1",
230   "4",
231   "4.1",
232   "5",
233   "5.1",
234   "5.2",
235   "6",
236   "6.1",
237   "6.2"
238 };
239 
240 static gboolean
parse_field(GstStructure * s,const gchar * field,gulong min,gulong max,guint8 * result)241 parse_field (GstStructure * s, const gchar * field, gulong min, gulong max,
242     guint8 * result)
243 {
244   const gchar *str;
245 
246   g_assert (result != NULL);
247 
248   str = gst_structure_get_string (s, field);
249   if (str != NULL && *str != '\0') {
250     gulong value;
251     gchar *end;
252 
253     value = strtoul (str, &end, 10);
254     if (*end == '\0' && value >= min && value <= max) {
255       *result = (guint8) value;
256     } else {
257       return FALSE;
258     }
259   } else {
260     return FALSE;
261   }
262 
263   return TRUE;
264 }
265 
266 static GstCaps *
gst_rtp_h265_pay_getcaps(GstRTPBasePayload * payload,GstPad * pad,GstCaps * filter)267 gst_rtp_h265_pay_getcaps (GstRTPBasePayload * payload, GstPad * pad,
268     GstCaps * filter)
269 {
270   GstCaps *template_caps;
271   GstCaps *allowed_caps;
272   GstCaps *caps;
273   GstCaps *icaps;
274   guint i;
275 
276   allowed_caps =
277       gst_pad_peer_query_caps (GST_RTP_BASE_PAYLOAD_SRCPAD (payload), NULL);
278 
279   if (allowed_caps == NULL)
280     return NULL;
281 
282   template_caps =
283       gst_static_pad_template_get_caps (&gst_rtp_h265_pay_sink_template);
284 
285   if (gst_caps_is_any (allowed_caps)) {
286     caps = gst_caps_ref (template_caps);
287     goto done;
288   }
289 
290   if (gst_caps_is_empty (allowed_caps)) {
291     caps = gst_caps_ref (allowed_caps);
292     goto done;
293   }
294 
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, };
300     guint8 value;
301 
302     if (parse_field (s, "profile-id", 0, 31, &value)) {
303       const gchar *profile;
304 
305       ptl[0] = value;
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);
310       } else {
311         GST_WARNING_OBJECT (payload, "invalid profile-id %d in caps", value);
312       }
313     } else {
314       GST_DEBUG_OBJECT (payload, "no valid profile-id in caps");
315     }
316 
317     if (parse_field (s, "tier-flag", 0, 1, &value)) {
318       const gchar *tier;
319 
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);
324     } else {
325       GST_DEBUG_OBJECT (payload, "no valid tier-flag in caps");
326     }
327 
328     if (parse_field (s, "level-id", 0, 255, &value)) {
329       const gchar *level;
330 
331       ptl[11] = value;
332       level = gst_codec_utils_h265_get_level (ptl, sizeof (ptl));
333       if (level != NULL) {
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);
337         } else {
338           GValue levels = { 0, };
339           GValue val = { 0, };
340           int j;
341 
342           g_value_init (&levels, GST_TYPE_LIST);
343           g_value_init (&val, G_TYPE_STRING);
344 
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]))
349               break;
350           }
351           gst_structure_take_value (new_s, "level", &levels);
352         }
353       } else {
354         GST_WARNING_OBJECT (payload, "invalid level-id %d in caps", value);
355       }
356     } else {
357       GST_DEBUG_OBJECT (payload, "no valid level-id in caps");
358     }
359 
360     caps = gst_caps_merge_structure (caps, new_s);
361   }
362 
363   icaps = gst_caps_intersect (caps, template_caps);
364   gst_caps_unref (caps);
365   caps = icaps;
366 
367 done:
368 
369   if (filter) {
370     GstCaps *tmp;
371 
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);
376     caps = tmp;
377   }
378 
379   gst_caps_unref (template_caps);
380   gst_caps_unref (allowed_caps);
381 
382   GST_LOG_OBJECT (payload, "returning caps %" GST_PTR_FORMAT, caps);
383   return caps;
384 }
385 
386 /* take the currently configured VPS, SPS and PPS lists and set them on the
387  * caps */
388 static gboolean
gst_rtp_h265_pay_set_vps_sps_pps(GstRTPBasePayload * basepayload)389 gst_rtp_h265_pay_set_vps_sps_pps (GstRTPBasePayload * basepayload)
390 {
391   GstRtpH265Pay *payloader = GST_RTP_H265_PAY (basepayload);
392   gchar *set;
393   GString *vps;
394   GString *sps;
395   GString *pps;
396   guint count;
397   gboolean res;
398   GstMapInfo map;
399   guint i;
400 
401   vps = g_string_new ("");
402   sps = g_string_new ("");
403   pps = g_string_new ("");
404   count = 0;
405 
406   for (i = 0; i < payloader->vps->len; i++) {
407     GstBuffer *vps_buf =
408         GST_BUFFER_CAST (g_ptr_array_index (payloader->vps, i));
409 
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);
413 
414     g_string_append_printf (vps, "%s%s", i ? "," : "", set);
415     g_free (set);
416     count++;
417   }
418   for (i = 0; i < payloader->sps->len; i++) {
419     GstBuffer *sps_buf =
420         GST_BUFFER_CAST (g_ptr_array_index (payloader->sps, i));
421 
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);
425 
426     g_string_append_printf (sps, "%s%s", i ? "," : "", set);
427     g_free (set);
428     count++;
429   }
430   for (i = 0; i < payloader->pps->len; i++) {
431     GstBuffer *pps_buf =
432         GST_BUFFER_CAST (g_ptr_array_index (payloader->pps, i));
433 
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);
437 
438     g_string_append_printf (pps, "%s%s", i ? "," : "", set);
439     g_free (set);
440     count++;
441   }
442 
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);
449   } else {
450     res = gst_rtp_base_payload_set_outcaps (basepayload, NULL);
451   }
452   g_string_free (vps, TRUE);
453   g_string_free (sps, TRUE);
454   g_string_free (pps, TRUE);
455 
456   return res;
457 }
458 
459 
460 static gboolean
gst_rtp_h265_pay_setcaps(GstRTPBasePayload * basepayload,GstCaps * caps)461 gst_rtp_h265_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps)
462 {
463   GstRtpH265Pay *rtph265pay;
464   GstStructure *str;
465   const GValue *value;
466   GstMapInfo map;
467   guint8 *data;
468   gsize size;
469   GstBuffer *buffer;
470   const gchar *alignment, *stream_format;
471   guint8 num_arrays;
472 
473   rtph265pay = GST_RTP_H265_PAY (basepayload);
474 
475   str = gst_caps_get_structure (caps, 0);
476 
477   /* we can only set the output caps when we found the sprops and profile
478    * NALs */
479   gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "H265", 90000);
480 
481   rtph265pay->alignment = GST_H265_ALIGNMENT_UNKNOWN;
482   alignment = gst_structure_get_string (str, "alignment");
483   if (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;
488   }
489 
490   rtph265pay->stream_format = GST_H265_STREAM_FORMAT_UNKNOWN;
491   stream_format = gst_structure_get_string (str, "stream-format");
492   if (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;
499   }
500 
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;
504     gint i, j, nal_size;
505 
506     GST_DEBUG_OBJECT (rtph265pay, "have packetized h265");
507 
508     buffer = gst_value_get_buffer (value);
509 
510     gst_buffer_map (buffer, &map, GST_MAP_READ);
511     data = map.data;
512     size = map.size;
513 
514     /* parse the hevcC data */
515     if (size < 23)
516       goto hevcc_too_small;
517     /* HEVCDecoderConfigurationVersion (must be 1) */
518     if (data[0] != 1)
519       goto wrong_version;
520 
521     /* profile_space | tier_flag | profile_idc */
522     GST_DEBUG_OBJECT (rtph265pay, "profile %06x", data[1]);
523 
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",
528             (data[i] >> j) & 1);
529       }
530     }
531 
532     GST_DEBUG_OBJECT (rtph265pay, "progressive_source_flag %06x",
533         (data[6] >> 7) & 1);
534     GST_DEBUG_OBJECT (rtph265pay, "interlaced_source_flag %06x",
535         (data[6] >> 6) & 1);
536     GST_DEBUG_OBJECT (rtph265pay, "non_packed_constraint_flag %06x",
537         (data[6] >> 5) & 1);
538     GST_DEBUG_OBJECT (rtph265pay, "frame_only_constraint_flag %06x",
539         (data[6] >> 4) & 1);
540 
541     GST_DEBUG_OBJECT (rtph265pay, "level_idc %06x", data[12]);
542 
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)",
546         data[15]);
547 
548     GST_DEBUG_OBJECT (rtph265pay, "sps_chroma_format_idc %06x",
549         data[16] ^ 0xfc);
550     GST_DEBUG_OBJECT (rtph265pay, "bit_depth_luma_minus8 %06x",
551         data[17] ^ 0xf8);
552     GST_DEBUG_OBJECT (rtph265pay, "bit_depth_chroma_minus8 %06x",
553         data[18] ^ 0xf8);
554     GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[19]);
555     GST_DEBUG_OBJECT (rtph265pay, "avgFrameRate %06x", data[20]);
556 
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);
567 
568     rtph265pay->nal_length_size = (data[21] & 0x3) + 1;
569     GST_DEBUG_OBJECT (rtph265pay, "nal length %u", rtph265pay->nal_length_size);
570 
571     num_arrays = GST_READ_UINT8 (data + 22);
572 
573     data += 23;
574     size -= 23;
575 
576     if (num_arrays > 0) {
577       if ((data[0] & 0x3f) == 0x20) {   /* VPS */
578 
579         data++;
580         num_vps = data[0] << 8 | data[1];
581         data += 2;
582         size -= 2;
583 
584         for (i = 0; i < num_vps; i++) {
585 
586           GstBuffer *vps_buf;
587 
588           if (size < 2)
589             goto hevcc_error;
590 
591           nal_size = (data[0] << 8) | data[1];
592           data += 2;
593           size -= 2;
594 
595           GST_LOG_OBJECT (rtph265pay, "VPS %d size %d", i, nal_size);
596 
597           if (size < nal_size)
598             goto hevcc_error;
599 
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);
605           data += nal_size;
606           size -= nal_size;
607         }
608       }
609 
610       --num_arrays;
611     }
612 
613     if (num_arrays > 0) {
614       if ((data[0] & 0x3f) == 0x21) {   /* SPS */
615 
616         data++;
617         num_sps = data[0] << 8 | data[1];
618         data += 2;
619         size -= 2;
620 
621         for (i = 0; i < num_sps; i++) {
622 
623           GstBuffer *sps_buf;
624 
625           if (size < 2)
626             goto hevcc_error;
627 
628           nal_size = (data[0] << 8) | data[1];
629           data += 2;
630           size -= 2;
631 
632           GST_LOG_OBJECT (rtph265pay, "SPS %d size %d", i, nal_size);
633 
634           if (size < nal_size)
635             goto hevcc_error;
636 
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);
642           data += nal_size;
643           size -= nal_size;
644         }
645       }
646 
647       --num_arrays;
648     }
649 
650     if (num_arrays > 0) {
651       if ((data[0] & 0x3f) == 0x22) {   /* PPS */
652 
653         data++;
654         num_pps = data[0] << 8 | data[1];
655         data += 2;
656         size -= 2;
657 
658         for (i = 0; i < num_pps; i++) {
659 
660           GstBuffer *pps_buf;
661 
662           if (size < 2)
663             goto hevcc_error;
664 
665           nal_size = (data[0] << 8) | data[1];
666           data += 2;
667           size -= 2;
668 
669           GST_LOG_OBJECT (rtph265pay, "PPS %d size %d", i, nal_size);
670 
671           if (size < nal_size)
672             goto hevcc_error;
673 
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);
679           data += nal_size;
680           size -= nal_size;
681         }
682       }
683 
684       --num_arrays;
685     }
686 
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;
690 
691     GST_DEBUG_OBJECT (rtph265pay, "Caps have been set");
692 
693     gst_buffer_unmap (buffer, &map);
694   } else {
695     GST_DEBUG_OBJECT (rtph265pay, "have bytestream h265");
696   }
697 
698   return TRUE;
699 
700 hevcc_too_small:
701   {
702     GST_ERROR_OBJECT (rtph265pay, "hevcC size %" G_GSIZE_FORMAT " < 7", size);
703     goto error;
704   }
705 wrong_version:
706   {
707     GST_ERROR_OBJECT (rtph265pay, "wrong hevcC version");
708     goto error;
709   }
710 hevcc_error:
711   {
712     GST_ERROR_OBJECT (rtph265pay, "hevcC too small ");
713     goto error;
714   }
715 set_vps_sps_pps_failed:
716   {
717     GST_ERROR_OBJECT (rtph265pay, "failed to set vps/sps/pps");
718     goto error;
719   }
720 error:
721   {
722     gst_buffer_unmap (buffer, &map);
723     return FALSE;
724   }
725 }
726 
727 static guint
next_start_code(const guint8 * data,guint size)728 next_start_code (const guint8 * data, guint size)
729 {
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
733    * simple form. */
734   /* assume 1 is in the 3rd byte */
735   guint offset = 2;
736 
737   while (offset < size) {
738     if (1 == data[offset]) {
739       unsigned int shift = offset;
740 
741       if (0 == data[--shift]) {
742         if (0 == data[--shift]) {
743           return shift;
744         }
745       }
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 */
748       offset += 3;
749     } else if (0 == data[offset]) {
750       /* maybe next byte is 1? */
751       offset++;
752     } else {
753       /* can jump 3 bytes forward */
754       offset += 3;
755     }
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 */
760   }
761   GST_DEBUG ("Cannot find next NAL start code. returning %u", size);
762 
763   return size;
764 }
765 
766 static gboolean
gst_rtp_h265_pay_decode_nal(GstRtpH265Pay * payloader,const guint8 * data,guint size,GstClockTime dts,GstClockTime pts)767 gst_rtp_h265_pay_decode_nal (GstRtpH265Pay * payloader,
768     const guint8 * data, guint size, GstClockTime dts, GstClockTime pts)
769 {
770   guint8 type;
771   gboolean updated;
772 
773   /* default is no update */
774   updated = FALSE;
775 
776   GST_DEBUG_OBJECT (payloader, "NAL payload size %u", size);
777 
778   type = (data[0] >> 1) & 0x3f;
779 
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) {
784     GstBuffer *nal;
785 
786     /* trailing 0x0 are not part of the VPS/SPS/PPS */
787     while (size > 0 && data[size - 1] == 0x0)
788       size--;
789 
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);
794 
795     nal = gst_buffer_new_allocate (NULL, size, NULL);
796     gst_buffer_fill (nal, 0, data, size);
797 
798     updated = gst_rtp_h265_add_vps_sps_pps (GST_ELEMENT (payloader),
799         payloader->vps, payloader->sps, payloader->pps, nal);
800 
801     /* remember when we last saw VPS */
802     if (pts != -1)
803       payloader->last_vps_sps_pps =
804           gst_segment_to_running_time (&GST_RTP_BASE_PAYLOAD_CAST
805           (payloader)->segment, GST_FORMAT_TIME, pts);
806   } else {
807     GST_DEBUG_OBJECT (payloader, "NALU type 0x%x, size %u", type, size);
808   }
809 
810   return updated;
811 }
812 
813 static GstFlowReturn
814 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
815     GPtrArray * paybufs, GstClockTime dts, GstClockTime pts);
816 
817 static GstFlowReturn
gst_rtp_h265_pay_send_vps_sps_pps(GstRTPBasePayload * basepayload,GstRtpH265Pay * rtph265pay,GstClockTime dts,GstClockTime pts)818 gst_rtp_h265_pay_send_vps_sps_pps (GstRTPBasePayload * basepayload,
819     GstRtpH265Pay * rtph265pay, GstClockTime dts, GstClockTime pts)
820 {
821   GstFlowReturn ret = GST_FLOW_OK;
822   gboolean sent_all_vps_sps_pps = TRUE;
823   guint i;
824   GPtrArray *bufs;
825 
826   bufs = g_ptr_array_new ();
827 
828   for (i = 0; i < rtph265pay->vps->len; i++) {
829     GstBuffer *vps_buf =
830         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->vps, i));
831 
832     GST_DEBUG_OBJECT (rtph265pay, "inserting VPS in the stream");
833     g_ptr_array_add (bufs, gst_buffer_ref (vps_buf));
834   }
835   for (i = 0; i < rtph265pay->sps->len; i++) {
836     GstBuffer *sps_buf =
837         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->sps, i));
838 
839     GST_DEBUG_OBJECT (rtph265pay, "inserting SPS in the stream");
840     g_ptr_array_add (bufs, gst_buffer_ref (sps_buf));
841   }
842   for (i = 0; i < rtph265pay->pps->len; i++) {
843     GstBuffer *pps_buf =
844         GST_BUFFER_CAST (g_ptr_array_index (rtph265pay->pps, i));
845 
846     GST_DEBUG_OBJECT (rtph265pay, "inserting PPS in the stream");
847     g_ptr_array_add (bufs, gst_buffer_ref (pps_buf));
848   }
849 
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");
854 
855     sent_all_vps_sps_pps = FALSE;
856   }
857 
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,
861         pts);
862 
863   return ret;
864 }
865 
866 static GstFlowReturn
gst_rtp_h265_pay_payload_nal(GstRTPBasePayload * basepayload,GPtrArray * paybufs,GstClockTime dts,GstClockTime pts)867 gst_rtp_h265_pay_payload_nal (GstRTPBasePayload * basepayload,
868     GPtrArray * paybufs, GstClockTime dts, GstClockTime pts)
869 {
870   GstRtpH265Pay *rtph265pay;
871   guint mtu;
872   GstFlowReturn ret;
873   gint i;
874   gboolean sent_ps;
875 
876   rtph265pay = GST_RTP_H265_PAY (basepayload);
877   mtu = GST_RTP_BASE_PAYLOAD_MTU (rtph265pay);
878 
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
882               (basepayload))))
883     gst_rtp_h265_pay_set_vps_sps_pps (basepayload);
884 
885   ret = GST_FLOW_OK;
886   sent_ps = FALSE;
887   for (i = 0; i < paybufs->len; i++) {
888     guint8 nalHeader[2];
889     guint8 nalType;
890     guint packet_len, payload_len;
891     GstBuffer *paybuf;
892     GstBuffer *outbuf;
893     guint8 *payload;
894     GstBufferList *outlist = NULL;
895     gboolean send_ps;
896     GstRTPBuffer rtp = { NULL };
897     guint size;
898     gboolean marker;
899 
900     paybuf = g_ptr_array_index (paybufs, i);
901 
902     if (ret != GST_FLOW_OK) {
903       /* unref buffers that will not be payloaded after a flow error */
904       gst_buffer_unref (paybuf);
905       continue;
906     }
907 
908     marker = GST_BUFFER_FLAG_IS_SET (paybuf, GST_BUFFER_FLAG_MARKER);
909 
910     size = gst_buffer_get_size (paybuf);
911     gst_buffer_extract (paybuf, 0, nalHeader, 2);
912     nalType = (nalHeader[0] >> 1) & 0x3f;
913 
914     GST_DEBUG_OBJECT (rtph265pay, "Processing Buffer with NAL TYPE=%d",
915         nalType);
916 
917     send_ps = FALSE;
918 
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) {
936           guint64 diff;
937           GstClockTime running_time =
938               gst_segment_to_running_time (&basepayload->segment,
939               GST_FORMAT_TIME, pts);
940 
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));
945 
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;
949           else
950             diff = 0;
951 
952           GST_DEBUG_OBJECT (rtph265pay,
953               "interval since last VPS/SPS/PPS %" GST_TIME_FORMAT,
954               GST_TIME_ARGS (diff));
955 
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");
959             send_ps = TRUE;
960           }
961         } else {
962           /* no known previous SPS/PPS time, send now */
963           GST_DEBUG_OBJECT (rtph265pay,
964               "no previous VPS/SPS/PPS time, send now");
965           send_ps = TRUE;
966         }
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 */
971         send_ps = TRUE;
972       }
973     }
974 
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
978        * first */
979       rtph265pay->send_vps_sps_pps = FALSE;
980       sent_ps = TRUE;
981       GST_DEBUG_OBJECT (rtph265pay, "sending VPS/SPS/PPS before current frame");
982       ret =
983           gst_rtp_h265_pay_send_vps_sps_pps (basepayload, rtph265pay, dts, pts);
984       if (ret != GST_FLOW_OK) {
985         gst_buffer_unref (paybuf);
986         continue;
987       }
988     }
989 
990     packet_len = gst_rtp_buffer_calc_packet_len (size, 0, 0);
991 
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 */
996 
997       /* use buffer lists
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);
1001 
1002       gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1003 
1004       /* Mark the end of a frame */
1005       gst_rtp_buffer_set_marker (&rtp, marker);
1006 
1007       /* timestamp the outbuffer */
1008       GST_BUFFER_PTS (outbuf) = pts;
1009       GST_BUFFER_DTS (outbuf) = dts;
1010 
1011       /* insert payload memory block */
1012       gst_rtp_copy_video_meta (rtph265pay, outbuf, paybuf);
1013       outbuf = gst_buffer_append (outbuf, paybuf);
1014 
1015       outlist = gst_buffer_list_new ();
1016 
1017       /* add the buffer to the buffer list */
1018       gst_buffer_list_add (outlist, outbuf);
1019 
1020       gst_rtp_buffer_unmap (&rtp);
1021 
1022       /* push the list to the next element in the pipe */
1023       ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1024     } else {
1025       /* fragmentation Units */
1026       guint limitedSize;
1027       int ii = 0, start = 1, end = 0, pos = 0;
1028 
1029       GST_DEBUG_OBJECT (basepayload,
1030           "NAL Unit DOES NOT fit in one packet datasize=%d mtu=%d", size, mtu);
1031 
1032       pos += 2;
1033       size -= 2;
1034 
1035       GST_DEBUG_OBJECT (basepayload, "Using FU fragmentation for data size=%d",
1036           size);
1037 
1038       /* We keep 3 bytes for PayloadHdr and FU Header */
1039       payload_len = gst_rtp_buffer_calc_payload_len (mtu - 3, 0, 0);
1040 
1041       outlist = gst_buffer_list_new ();
1042 
1043       while (end == 0) {
1044         limitedSize = size < payload_len ? size : payload_len;
1045         GST_DEBUG_OBJECT (basepayload,
1046             "Inside  FU fragmentation limitedSize=%d iteration=%d", limitedSize,
1047             ii);
1048 
1049         /* use buffer lists
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);
1053 
1054         gst_rtp_buffer_map (outbuf, GST_MAP_WRITE, &rtp);
1055 
1056         GST_BUFFER_DTS (outbuf) = dts;
1057         GST_BUFFER_PTS (outbuf) = pts;
1058         payload = gst_rtp_buffer_get_payload (&rtp);
1059 
1060         if (limitedSize == size) {
1061           GST_DEBUG_OBJECT (basepayload, "end size=%d iteration=%d", size, ii);
1062           end = 1;
1063         }
1064 
1065         /* PayloadHdr (type = 49) */
1066         payload[0] = (nalHeader[0] & 0x81) | (49 << 1);
1067         payload[1] = nalHeader[1];
1068 
1069         /* If it's the last fragment and the end of this au, mark the end of
1070          * slice */
1071         gst_rtp_buffer_set_marker (&rtp, end && marker);
1072 
1073         /* FU Header */
1074         payload[2] = (start << 7) | (end << 6) | (nalType & 0x3f);
1075 
1076         gst_rtp_buffer_unmap (&rtp);
1077 
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,
1081             limitedSize);
1082         /* add the buffer to the buffer list */
1083         gst_buffer_list_add (outlist, outbuf);
1084 
1085         size -= limitedSize;
1086         pos += limitedSize;
1087         ii++;
1088         start = 0;
1089       }
1090 
1091       ret = gst_rtp_base_payload_push_list (basepayload, outlist);
1092       gst_buffer_unref (paybuf);
1093     }
1094   }
1095 
1096   g_ptr_array_free (paybufs, TRUE);
1097 
1098   return ret;
1099 }
1100 
1101 static GstFlowReturn
gst_rtp_h265_pay_handle_buffer(GstRTPBasePayload * basepayload,GstBuffer * buffer)1102 gst_rtp_h265_pay_handle_buffer (GstRTPBasePayload * basepayload,
1103     GstBuffer * buffer)
1104 {
1105   GstRtpH265Pay *rtph265pay;
1106   GstFlowReturn ret;
1107   gsize size;
1108   guint nal_len, i;
1109   GstMapInfo map;
1110   const guint8 *data;
1111   GstClockTime dts, pts;
1112   GArray *nal_queue;
1113   gboolean hevc;
1114   GstBuffer *paybuf = NULL;
1115   gsize skip;
1116   gboolean marker = FALSE;
1117   gboolean draining = (buffer == NULL);
1118 
1119   rtph265pay = GST_RTP_H265_PAY (basepayload);
1120 
1121   /* the input buffer contains one or more NAL units */
1122 
1123   hevc = (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HEV1)
1124       || (rtph265pay->stream_format == GST_H265_STREAM_FORMAT_HVC1);
1125 
1126   if (hevc) {
1127     /* In hevc mode, there is no adapter, so nothing to drain */
1128     if (draining)
1129       return GST_FLOW_OK;
1130     gst_buffer_map (buffer, &map, GST_MAP_READ);
1131     data = map.data;
1132     size = map.size;
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);
1137   } else {
1138     if (buffer) {
1139       marker = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_MARKER);
1140       gst_adapter_push (rtph265pay->adapter, buffer);
1141       buffer = NULL;
1142     }
1143 
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);
1147 
1148     size = gst_adapter_available (rtph265pay->adapter);
1149     /* Nothing to do here if the adapter is empty, e.g. on EOS */
1150     if (size == 0)
1151       return GST_FLOW_OK;
1152     data = gst_adapter_map (rtph265pay->adapter, size);
1153     GST_DEBUG_OBJECT (basepayload, "got %" G_GSIZE_FORMAT " bytes", size);
1154   }
1155 
1156   ret = GST_FLOW_OK;
1157 
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
1161    * latency. */
1162   if (hevc) {
1163     guint nal_length_size;
1164     gsize offset = 0;
1165     GPtrArray *paybufs;
1166 
1167     paybufs = g_ptr_array_new ();
1168     nal_length_size = rtph265pay->nal_length_size;
1169 
1170     while (size > nal_length_size) {
1171       gint i;
1172 
1173       nal_len = 0;
1174       for (i = 0; i < nal_length_size; i++) {
1175         nal_len = ((nal_len << 8) + data[i]);
1176       }
1177 
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;
1182 
1183       if (size >= nal_len) {
1184         GST_DEBUG_OBJECT (basepayload, "got NAL of size %u", nal_len);
1185       } else {
1186         nal_len = size;
1187         GST_DEBUG_OBJECT (basepayload, "got incomplete NAL of size %u",
1188             nal_len);
1189       }
1190 
1191       paybuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset,
1192           nal_len);
1193       g_ptr_array_add (paybufs, paybuf);
1194 
1195       /* If we're at the end of the buffer, then we're at the end of the
1196        * access unit
1197        */
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);
1202       }
1203 
1204       data += nal_len;
1205       offset += nal_len;
1206       size -= nal_len;
1207     }
1208     ret = gst_rtp_h265_pay_payload_nal (basepayload, paybufs, dts, pts);
1209   } else {
1210     guint next;
1211     gboolean update = FALSE;
1212     GPtrArray *paybufs;
1213 
1214     /* get offset of first start code */
1215     next = next_start_code (data, size);
1216 
1217     /* skip to start code, if no start code is found, next will be size and we
1218      * will not collect data. */
1219     data += next;
1220     size -= next;
1221     nal_queue = rtph265pay->queue;
1222     skip = next;
1223 
1224     /* array must be empty when we get here */
1225     g_assert (nal_queue->len == 0);
1226 
1227     GST_DEBUG_OBJECT (basepayload,
1228         "found first start at %u, bytes left %" G_GSIZE_FORMAT, next, size);
1229 
1230     paybufs = g_ptr_array_new ();
1231 
1232     /* first pass to locate NALs and parse VPS/SPS/PPS */
1233     while (size > 4) {
1234       /* skip start code */
1235       data += 3;
1236       size -= 3;
1237 
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
1242        * 'size' parameter.
1243        * data is unchanged by the call to next_start_code()
1244        */
1245       next = next_start_code (data, size);
1246 
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 */
1252         break;
1253       }
1254 
1255       /* nal length is distance to next start code */
1256       nal_len = next;
1257 
1258       GST_DEBUG_OBJECT (basepayload, "found next start at %u of size %u", next,
1259           nal_len);
1260 
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)
1265           || update;
1266 
1267       /* move to next NAL packet */
1268       data += nal_len;
1269       size -= nal_len;
1270 
1271       g_array_append_val (nal_queue, nal_len);
1272     }
1273 
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))
1277         goto caps_rejected;
1278 
1279     /* second pass to payload and push */
1280 
1281     if (nal_queue->len != 0)
1282       gst_adapter_flush (rtph265pay->adapter, skip);
1283 
1284     for (i = 0; i < nal_queue->len; i++) {
1285       guint size;
1286 
1287       nal_len = g_array_index (nal_queue, guint, i);
1288       /* skip start code */
1289       gst_adapter_flush (rtph265pay->adapter, 3);
1290 
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 */
1295       size = nal_len;
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--)
1299           /* skip */ ;
1300 
1301       paybuf = gst_adapter_take_buffer (rtph265pay->adapter, size);
1302       g_assert (paybuf);
1303       g_ptr_array_add (paybufs, paybuf);
1304 
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 ||
1310             marker || draining)
1311           GST_BUFFER_FLAG_SET (paybuf, GST_BUFFER_FLAG_MARKER);
1312       }
1313 
1314       /* move to next NAL packet */
1315       /* Skips the trailing zeros */
1316       gst_adapter_flush (rtph265pay->adapter, nal_len - size);
1317     }
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);
1321   }
1322 
1323 done:
1324   if (hevc) {
1325     gst_buffer_unmap (buffer, &map);
1326     gst_buffer_unref (buffer);
1327   } else {
1328     gst_adapter_unmap (rtph265pay->adapter);
1329   }
1330 
1331   return ret;
1332 
1333 caps_rejected:
1334   {
1335     GST_WARNING_OBJECT (basepayload, "Could not set outcaps");
1336     g_array_set_size (nal_queue, 0);
1337     ret = GST_FLOW_NOT_NEGOTIATED;
1338     goto done;
1339   }
1340 }
1341 
1342 static gboolean
gst_rtp_h265_pay_sink_event(GstRTPBasePayload * payload,GstEvent * event)1343 gst_rtp_h265_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event)
1344 {
1345   gboolean res;
1346   const GstStructure *s;
1347   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (payload);
1348 
1349   switch (GST_EVENT_TYPE (event)) {
1350     case GST_EVENT_FLUSH_STOP:
1351       gst_adapter_clear (rtph265pay->adapter);
1352       break;
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;
1357 
1358         if (gst_structure_get_boolean (s, "all-headers",
1359                 &resend_codec_data) && resend_codec_data)
1360           rtph265pay->send_vps_sps_pps = TRUE;
1361       }
1362       break;
1363     case GST_EVENT_EOS:
1364     {
1365       /* call handle_buffer with NULL to flush last NAL from adapter
1366        * in byte-stream mode
1367        */
1368       gst_rtp_h265_pay_handle_buffer (payload, NULL);
1369       break;
1370     }
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);
1375       break;
1376     default:
1377       break;
1378   }
1379 
1380   res = GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event);
1381 
1382   return res;
1383 }
1384 
1385 static GstStateChangeReturn
gst_rtp_h265_pay_change_state(GstElement * element,GstStateChange transition)1386 gst_rtp_h265_pay_change_state (GstElement * element, GstStateChange transition)
1387 {
1388   GstStateChangeReturn ret;
1389   GstRtpH265Pay *rtph265pay = GST_RTP_H265_PAY (element);
1390 
1391   switch (transition) {
1392     case GST_STATE_CHANGE_READY_TO_PAUSED:
1393       rtph265pay->send_vps_sps_pps = FALSE;
1394       gst_adapter_clear (rtph265pay->adapter);
1395       break;
1396     default:
1397       break;
1398   }
1399 
1400   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1401 
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);
1406       break;
1407     default:
1408       break;
1409   }
1410 
1411   return ret;
1412 }
1413 
1414 static void
gst_rtp_h265_pay_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)1415 gst_rtp_h265_pay_set_property (GObject * object, guint prop_id,
1416     const GValue * value, GParamSpec * pspec)
1417 {
1418   GstRtpH265Pay *rtph265pay;
1419 
1420   rtph265pay = GST_RTP_H265_PAY (object);
1421 
1422   switch (prop_id) {
1423     case PROP_CONFIG_INTERVAL:
1424       rtph265pay->vps_sps_pps_interval = g_value_get_int (value);
1425       break;
1426     default:
1427       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1428       break;
1429   }
1430 }
1431 
1432 static void
gst_rtp_h265_pay_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)1433 gst_rtp_h265_pay_get_property (GObject * object, guint prop_id,
1434     GValue * value, GParamSpec * pspec)
1435 {
1436   GstRtpH265Pay *rtph265pay;
1437 
1438   rtph265pay = GST_RTP_H265_PAY (object);
1439 
1440   switch (prop_id) {
1441     case PROP_CONFIG_INTERVAL:
1442       g_value_set_int (value, rtph265pay->vps_sps_pps_interval);
1443       break;
1444     default:
1445       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1446       break;
1447   }
1448 }
1449 
1450 gboolean
gst_rtp_h265_pay_plugin_init(GstPlugin * plugin)1451 gst_rtp_h265_pay_plugin_init (GstPlugin * plugin)
1452 {
1453   return gst_element_register (plugin, "rtph265pay",
1454       GST_RANK_SECONDARY, GST_TYPE_RTP_H265_PAY);
1455 }
1456