rtp: Update codes based on 1.18.4
[platform/upstream/gst-plugins-good.git] / gst / rtp / gstrtph265depay.c
index bfc2e13..38f53e4 100644 (file)
 #include <gst/rtp/gstrtpbuffer.h>
 #include <gst/video/video.h>
 #include "gstrtph265depay.h"
+#include "gstrtputils.h"
 
 GST_DEBUG_CATEGORY_STATIC (rtph265depay_debug);
 #define GST_CAT_DEFAULT (rtph265depay_debug)
 
 /* This is what we'll default to when downstream hasn't
  * expressed a restriction or preference via caps */
-#define DEFAULT_BYTE_STREAM   TRUE
+#define DEFAULT_STREAM_FORMAT GST_H265_STREAM_FORMAT_BYTESTREAM
 #define DEFAULT_ACCESS_UNIT   FALSE
 
 /* 3 zero bytes syncword */
@@ -45,11 +46,10 @@ static GstStaticPadTemplate gst_rtp_h265_depay_src_template =
     GST_STATIC_PAD_TEMPLATE ("src",
     GST_PAD_SRC,
     GST_PAD_ALWAYS,
-    GST_STATIC_CAPS (
-        /* FIXME - hvc1 and hev1 formats are not supported yet */
-        /*"video/x-h265, "
-           "stream-format = (string) hvc1, alignment = (string) au; "
-           "video/x-h265, "
+    GST_STATIC_CAPS
+    ("video/x-h265, stream-format=(string)hvc1, alignment=(string)au; "
+        /* FIXME: hev1 format is not supported yet */
+        /* "video/x-h265, "
            "stream-format = (string) hev1, alignment = (string) au; " */
         "video/x-h265, "
         "stream-format = (string) byte-stream, alignment = (string) { nal, au }")
@@ -62,7 +62,7 @@ GST_STATIC_PAD_TEMPLATE ("sink",
     GST_STATIC_CAPS ("application/x-rtp, "
         "media = (string) \"video\", "
         "clock-rate = (int) 90000, " "encoding-name = (string) \"H265\"")
-        /** optional parameters **/
+    /* optional parameters */
     /* "profile-space = (int) [ 0, 3 ], " */
     /* "profile-id = (int) [ 0, 31 ], " */
     /* "tier-flag = (int) [ 0, 1 ], " */
@@ -109,6 +109,12 @@ static gboolean gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * filter,
     GstCaps * caps);
 static gboolean gst_rtp_h265_depay_handle_event (GstRTPBaseDepayload * depay,
     GstEvent * event);
+static GstBuffer *gst_rtp_h265_complete_au (GstRtpH265Depay * rtph265depay,
+    GstClockTime * out_timestamp, gboolean * out_keyframe);
+static void gst_rtp_h265_depay_push (GstRtpH265Depay * rtph265depay,
+    GstBuffer * outbuf, gboolean keyframe, GstClockTime timestamp,
+    gboolean marker);
+
 
 static void
 gst_rtp_h265_depay_class_init (GstRtpH265DepayClass * klass)
@@ -123,14 +129,14 @@ gst_rtp_h265_depay_class_init (GstRtpH265DepayClass * klass)
 
   gobject_class->finalize = gst_rtp_h265_depay_finalize;
 
-  gst_element_class_add_pad_template (gstelement_class,
-      gst_static_pad_template_get (&gst_rtp_h265_depay_src_template));
-  gst_element_class_add_pad_template (gstelement_class,
-      gst_static_pad_template_get (&gst_rtp_h265_depay_sink_template));
+  gst_element_class_add_static_pad_template (gstelement_class,
+      &gst_rtp_h265_depay_src_template);
+  gst_element_class_add_static_pad_template (gstelement_class,
+      &gst_rtp_h265_depay_sink_template);
 
   gst_element_class_set_static_metadata (gstelement_class,
       "RTP H265 depayloader", "Codec/Depayloader/Network/RTP",
-      "Extracts H265 video from RTP packets (draft-ietf-payload-rtp-h265-03.txt)",
+      "Extracts H265 video from RTP packets (RFC 7798)",
       "Jurgen Slowack <jurgenslowack@gmail.com>");
   gstelement_class->change_state = gst_rtp_h265_depay_change_state;
 
@@ -144,8 +150,10 @@ gst_rtp_h265_depay_init (GstRtpH265Depay * rtph265depay)
 {
   rtph265depay->adapter = gst_adapter_new ();
   rtph265depay->picture_adapter = gst_adapter_new ();
-  rtph265depay->byte_stream = DEFAULT_BYTE_STREAM;
-  rtph265depay->stream_format = (gchar *) g_malloc (10);
+  rtph265depay->output_format = DEFAULT_STREAM_FORMAT;
+  rtph265depay->byte_stream =
+      (DEFAULT_STREAM_FORMAT == GST_H265_STREAM_FORMAT_BYTESTREAM);
+  rtph265depay->stream_format = NULL;
   rtph265depay->merge = DEFAULT_ACCESS_UNIT;
   rtph265depay->vps = g_ptr_array_new_with_free_func (
       (GDestroyNotify) gst_buffer_unref);
@@ -156,7 +164,7 @@ gst_rtp_h265_depay_init (GstRtpH265Depay * rtph265depay)
 }
 
 static void
-gst_rtp_h265_depay_reset (GstRtpH265Depay * rtph265depay)
+gst_rtp_h265_depay_reset (GstRtpH265Depay * rtph265depay, gboolean hard)
 {
   gst_adapter_clear (rtph265depay->adapter);
   rtph265depay->wait_start = TRUE;
@@ -169,6 +177,29 @@ gst_rtp_h265_depay_reset (GstRtpH265Depay * rtph265depay)
   g_ptr_array_set_size (rtph265depay->vps, 0);
   g_ptr_array_set_size (rtph265depay->sps, 0);
   g_ptr_array_set_size (rtph265depay->pps, 0);
+
+  if (hard) {
+    if (rtph265depay->allocator != NULL) {
+      gst_object_unref (rtph265depay->allocator);
+      rtph265depay->allocator = NULL;
+    }
+    gst_allocation_params_init (&rtph265depay->params);
+  }
+}
+
+static void
+gst_rtp_h265_depay_drain (GstRtpH265Depay * rtph265depay)
+{
+  GstClockTime timestamp;
+  gboolean keyframe;
+  GstBuffer *outbuf;
+
+  if (!rtph265depay->picture_start)
+    return;
+
+  outbuf = gst_rtp_h265_complete_au (rtph265depay, &timestamp, &keyframe);
+  if (outbuf)
+    gst_rtp_h265_depay_push (rtph265depay, outbuf, keyframe, timestamp, FALSE);
 }
 
 static void
@@ -181,8 +212,6 @@ gst_rtp_h265_depay_finalize (GObject * object)
   if (rtph265depay->codec_data)
     gst_buffer_unref (rtph265depay->codec_data);
 
-  g_free (rtph265depay->stream_format);
-
   g_object_unref (rtph265depay->adapter);
   g_object_unref (rtph265depay->picture_adapter);
 
@@ -193,11 +222,27 @@ gst_rtp_h265_depay_finalize (GObject * object)
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
 
+static inline const gchar *
+stream_format_get_nick (GstH265StreamFormat fmt)
+{
+  switch (fmt) {
+    case GST_H265_STREAM_FORMAT_BYTESTREAM:
+      return "byte-stream";
+    case GST_H265_STREAM_FORMAT_HVC1:
+      return "hvc1";
+    case GST_H265_STREAM_FORMAT_HEV1:
+      return "hev1";
+    default:
+      break;
+  }
+  return "unknown";
+}
+
 static void
 gst_rtp_h265_depay_negotiate (GstRtpH265Depay * rtph265depay)
 {
+  GstH265StreamFormat stream_format = GST_H265_STREAM_FORMAT_UNKNOWN;
   GstCaps *caps;
-  gint byte_stream = -1;
   gint merge = -1;
 
   caps =
@@ -211,15 +256,14 @@ gst_rtp_h265_depay_negotiate (GstRtpH265Depay * rtph265depay)
       const gchar *str = NULL;
 
       if ((str = gst_structure_get_string (s, "stream-format"))) {
-
-        strcpy (rtph265depay->stream_format, str);
+        rtph265depay->stream_format = g_intern_string (str);
 
         if (strcmp (str, "hev1") == 0) {
-          byte_stream = FALSE;
+          stream_format = GST_H265_STREAM_FORMAT_HEV1;
         } else if (strcmp (str, "hvc1") == 0) {
-          byte_stream = FALSE;
+          stream_format = GST_H265_STREAM_FORMAT_HVC1;
         } else if (strcmp (str, "byte-stream") == 0) {
-          byte_stream = TRUE;
+          stream_format = GST_H265_STREAM_FORMAT_BYTESTREAM;
         } else {
           GST_DEBUG_OBJECT (rtph265depay, "unknown stream-format: %s", str);
         }
@@ -238,16 +282,20 @@ gst_rtp_h265_depay_negotiate (GstRtpH265Depay * rtph265depay)
     gst_caps_unref (caps);
   }
 
-  if (byte_stream != -1) {
-    GST_DEBUG_OBJECT (rtph265depay, "downstream requires byte-stream %d",
-        byte_stream);
-    rtph265depay->byte_stream = byte_stream;
+  if (stream_format != GST_H265_STREAM_FORMAT_UNKNOWN) {
+    GST_DEBUG_OBJECT (rtph265depay, "downstream wants stream-format %s",
+        stream_format_get_nick (stream_format));
+    rtph265depay->output_format = stream_format;
   } else {
-    GST_DEBUG_OBJECT (rtph265depay, "defaulting to byte-stream %d",
-        DEFAULT_BYTE_STREAM);
-    strcpy (rtph265depay->stream_format, "byte-stream");
-    rtph265depay->byte_stream = DEFAULT_BYTE_STREAM;
+    GST_DEBUG_OBJECT (rtph265depay, "defaulting to output stream-format %s",
+        stream_format_get_nick (DEFAULT_STREAM_FORMAT));
+    rtph265depay->stream_format =
+        stream_format_get_nick (DEFAULT_STREAM_FORMAT);
+    rtph265depay->output_format = DEFAULT_STREAM_FORMAT;
   }
+  rtph265depay->byte_stream =
+      (rtph265depay->output_format == GST_H265_STREAM_FORMAT_BYTESTREAM);
+
   if (merge != -1) {
     GST_DEBUG_OBJECT (rtph265depay, "downstream requires merge %d", merge);
     rtph265depay->merge = merge;
@@ -258,41 +306,18 @@ gst_rtp_h265_depay_negotiate (GstRtpH265Depay * rtph265depay)
   }
 }
 
-/* Stolen from bad/gst/mpegtsdemux/payloader_parsers.c */
-/* variable length Exp-Golomb parsing according to H.265 spec section 9.2*/
-static gboolean
-read_golomb (GstBitReader * br, guint32 * value)
-{
-  guint8 b, leading_zeros = -1;
-  *value = 1;
-
-  for (b = 0; !b; leading_zeros++) {
-    if (!gst_bit_reader_get_bits_uint8 (br, &b, 1))
-      return FALSE;
-    *value *= 2;
-  }
-
-  *value = (*value >> 1) - 1;
-  if (leading_zeros > 0) {
-    guint32 tmp = 0;
-    if (!gst_bit_reader_get_bits_uint32 (br, &tmp, leading_zeros))
-      return FALSE;
-    *value += tmp;
-  }
-
-  return TRUE;
-}
-
 static gboolean
 parse_sps (GstMapInfo * map, guint32 * sps_id)
 {                               /* To parse seq_parameter_set_id */
   GstBitReader br = GST_BIT_READER_INIT (map->data + 15,
       map->size - 15);
 
+  GST_MEMDUMP ("SPS", map->data, map->size);
+
   if (map->size < 16)
     return FALSE;
 
-  if (!read_golomb (&br, sps_id))
+  if (!gst_rtp_read_golomb (&br, sps_id))
     return FALSE;
 
   return TRUE;
@@ -304,23 +329,65 @@ parse_pps (GstMapInfo * map, guint32 * sps_id, guint32 * pps_id)
   GstBitReader br = GST_BIT_READER_INIT (map->data + 2,
       map->size - 2);
 
+  GST_MEMDUMP ("PPS", map->data, map->size);
+
   if (map->size < 3)
     return FALSE;
 
-  if (!read_golomb (&br, pps_id))
+  if (!gst_rtp_read_golomb (&br, pps_id))
     return FALSE;
-  if (!read_golomb (&br, sps_id))
+  if (!gst_rtp_read_golomb (&br, sps_id))
     return FALSE;
 
   return TRUE;
 }
 
+static gboolean
+gst_rtp_h265_depay_set_output_caps (GstRtpH265Depay * rtph265depay,
+    GstCaps * caps)
+{
+  GstAllocationParams params;
+  GstAllocator *allocator = NULL;
+  GstPad *srcpad;
+  gboolean res;
+
+  gst_allocation_params_init (&params);
+
+  srcpad = GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay);
+
+  res = gst_pad_set_caps (srcpad, caps);
+
+  if (res) {
+    GstQuery *query;
+
+    query = gst_query_new_allocation (caps, TRUE);
+    if (!gst_pad_peer_query (srcpad, query)) {
+      GST_DEBUG_OBJECT (rtph265depay, "downstream ALLOCATION query failed");
+    }
+
+    if (gst_query_get_n_allocation_params (query) > 0) {
+      gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
+    }
+
+    gst_query_unref (query);
+  }
+
+  if (rtph265depay->allocator)
+    gst_object_unref (rtph265depay->allocator);
+
+  rtph265depay->allocator = allocator;
+  rtph265depay->params = params;
+
+  return res;
+}
 
 static gboolean
 gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
 {
-  gboolean res;
+  gboolean res, update_caps;
+  GstCaps *old_caps;
   GstCaps *srccaps;
+  GstPad *srcpad;
 
   if (!rtph265depay->byte_stream &&
       (!rtph265depay->new_codec_data ||
@@ -329,12 +396,10 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
     return TRUE;
 
   srccaps = gst_caps_new_simple ("video/x-h265",
-      "stream-format", G_TYPE_STRING,
-      rtph265depay->stream_format,
+      "stream-format", G_TYPE_STRING, rtph265depay->stream_format,
       "alignment", G_TYPE_STRING, rtph265depay->merge ? "au" : "nal", NULL);
 
   if (!rtph265depay->byte_stream) {
-
     GstBuffer *codec_data;
     gint i = 0;
     gint len;
@@ -343,7 +408,6 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
     guint num_pps = rtph265depay->pps->len;
     GstMapInfo map, nalmap;
     guint8 *data;
-    gint nl;
     guint8 num_arrays = 0;
     guint new_size;
     GstBitReader br;
@@ -362,7 +426,7 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
     len = 23;
 
     num_arrays = (num_vps > 0) + (num_sps > 0) + (num_pps > 0);
-    len += num_arrays;
+    len += 3 * num_arrays;
 
     /* add size of vps, sps & pps */
     for (i = 0; i < num_vps; i++)
@@ -377,7 +441,6 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
         num_sps, num_pps);
 
     codec_data = gst_buffer_new_and_alloc (len);
-    g_debug ("alloc_len: %u", len);
     gst_buffer_map (codec_data, &map, GST_MAP_READWRITE);
     data = map.data;
 
@@ -393,34 +456,32 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
 
     gst_bit_reader_init (&br, nalmap.data + 15, nalmap.size - 15);
 
-    read_golomb (&br, &tmp);    /* sps_seq_parameter_set_id */
-    read_golomb (&br, &chroma_format_idc);      /* chroma_format_idc */
+    gst_rtp_read_golomb (&br, &tmp);    /* sps_seq_parameter_set_id */
+    gst_rtp_read_golomb (&br, &chroma_format_idc);      /* chroma_format_idc */
 
     if (chroma_format_idc == 3)
 
       gst_bit_reader_get_bits_uint8 (&br, &tmp8, 1);    /* separate_colour_plane_flag */
 
-    read_golomb (&br, &tmp);    /* pic_width_in_luma_samples */
-    read_golomb (&br, &tmp);    /* pic_height_in_luma_samples */
+    gst_rtp_read_golomb (&br, &tmp);    /* pic_width_in_luma_samples */
+    gst_rtp_read_golomb (&br, &tmp);    /* pic_height_in_luma_samples */
 
     gst_bit_reader_get_bits_uint8 (&br, &tmp8, 1);      /* conformance_window_flag */
     if (tmp8) {
-      read_golomb (&br, &tmp);  /* conf_win_left_offset */
-      read_golomb (&br, &tmp);  /* conf_win_right_offset */
-      read_golomb (&br, &tmp);  /* conf_win_top_offset */
-      read_golomb (&br, &tmp);  /* conf_win_bottom_offset */
+      gst_rtp_read_golomb (&br, &tmp);  /* conf_win_left_offset */
+      gst_rtp_read_golomb (&br, &tmp);  /* conf_win_right_offset */
+      gst_rtp_read_golomb (&br, &tmp);  /* conf_win_top_offset */
+      gst_rtp_read_golomb (&br, &tmp);  /* conf_win_bottom_offset */
     }
 
-    read_golomb (&br, &bit_depth_luma_minus8);  /* bit_depth_luma_minus8 */
-    read_golomb (&br, &bit_depth_chroma_minus8);        /* bit_depth_chroma_minus8 */
+    gst_rtp_read_golomb (&br, &bit_depth_luma_minus8);  /* bit_depth_luma_minus8 */
+    gst_rtp_read_golomb (&br, &bit_depth_chroma_minus8);        /* bit_depth_chroma_minus8 */
 
     GST_DEBUG_OBJECT (rtph265depay,
         "Ignoring min_spatial_segmentation for now (assuming zero)");
 
     min_spatial_segmentation_idc = 0;   /* NOTE - we ignore this for now, but in a perfect world, we should continue parsing to obtain the real value */
 
-    nl = nalmap.size;
-
     gst_buffer_unmap (g_ptr_array_index (rtph265depay->sps, 0), &nalmap);
 
     /* HEVCDecoderConfigurationVersion = 1 */
@@ -452,9 +513,10 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
      * numTemporalLayers (3 bits): number of temporal layers, value from SPS
      * TemporalIdNested (1 bit): sps_temporal_id_nesting_flag from SPS
      * lengthSizeMinusOne (2 bits): plus 1 indicates the length of the NALUnitLength */
-    data[21] =
-        0x00 | ((max_sub_layers_minus1 +
-            1) << 3) | (temporal_id_nesting_flag << 2) | (nl - 1);
+    /* we always output NALs with 4-byte nal unit length markers (or sync code) */
+    data[21] = rtph265depay->byte_stream ? 0x00 : 0x03;
+    data[21] |= ((max_sub_layers_minus1 + 1) << 3);
+    data[21] |= (temporal_id_nesting_flag << 2);
     GST_WRITE_UINT8 (data + 22, num_arrays);    /* numOfArrays */
 
     data += 23;
@@ -531,9 +593,10 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
     gst_buffer_unref (codec_data);
   }
 
-  if (gst_pad_has_current_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay))) {
-    GstCaps *old_caps =
-        gst_pad_get_current_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay));
+  srcpad = GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay);
+
+  old_caps = gst_pad_get_current_caps (srcpad);
+  if (old_caps != NULL) {
 
     /* Only update the caps if they are not equal. For
      * AVC we don't update caps if only the codec_data
@@ -541,12 +604,7 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
      * and gstrtph264depay
      */
     if (rtph265depay->byte_stream) {
-      if (!gst_caps_is_equal (srccaps, old_caps))
-        res =
-            gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
-            srccaps);
-      else
-        res = TRUE;
+      update_caps = !gst_caps_is_equal (srccaps, old_caps);
     } else {
       GstCaps *tmp_caps = gst_caps_copy (srccaps);
       GstStructure *old_s, *tmp_s;
@@ -557,25 +615,25 @@ gst_rtp_h265_set_src_caps (GstRtpH265Depay * rtph265depay)
         gst_structure_set_value (tmp_s, "codec_data",
             gst_structure_get_value (old_s, "codec_data"));
 
-      if (!gst_caps_is_equal (old_caps, tmp_caps))
-        res =
-            gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
-            srccaps);
-      else
-        res = TRUE;
-
+      update_caps = !gst_caps_is_equal (old_caps, tmp_caps);
       gst_caps_unref (tmp_caps);
     }
+    gst_caps_unref (old_caps);
   } else {
-    res =
-        gst_pad_set_caps (GST_RTP_BASE_DEPAYLOAD_SRCPAD (rtph265depay),
-        srccaps);
+    update_caps = TRUE;
+  }
+
+  if (update_caps) {
+    res = gst_rtp_h265_depay_set_output_caps (rtph265depay, srccaps);
+  } else {
+    res = TRUE;
   }
 
   gst_caps_unref (srccaps);
 
   /* Insert SPS and PPS into the stream on next opportunity */
-  if (rtph265depay->sps->len > 0 || rtph265depay->pps->len > 0) {
+  if (rtph265depay->output_format != GST_H265_STREAM_FORMAT_HVC1
+      && (rtph265depay->sps->len > 0 || rtph265depay->pps->len > 0)) {
     gint i;
     GstBuffer *codec_data;
     GstMapInfo map;
@@ -778,8 +836,10 @@ gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
   gint clock_rate;
   GstStructure *structure = gst_caps_get_structure (caps, 0);
   GstRtpH265Depay *rtph265depay;
-  const gchar *ps;
-  GstBuffer *codec_data;
+  const gchar *vps;
+  const gchar *sps;
+  const gchar *pps;
+  gchar *ps;
   GstMapInfo map;
   guint8 *ptr;
 
@@ -790,7 +850,14 @@ gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
   depayload->clock_rate = clock_rate;
 
   /* Base64 encoded, comma separated config NALs */
-  ps = gst_structure_get_string (structure, "sprop-parameter-sets");
+  vps = gst_structure_get_string (structure, "sprop-vps");
+  sps = gst_structure_get_string (structure, "sprop-sps");
+  pps = gst_structure_get_string (structure, "sprop-pps");
+  if (vps == NULL || sps == NULL || pps == NULL) {
+    ps = NULL;
+  } else {
+    ps = g_strdup_printf ("%s,%s,%s", vps, sps, pps);
+  }
 
   /* negotiate with downstream w.r.t. output format and alignment */
   gst_rtp_h265_depay_negotiate (rtph265depay);
@@ -799,6 +866,7 @@ gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
     /* for bytestream we only need the parameter sets but we don't error out
      * when they are not there, we assume they are in the stream. */
     gchar **params;
+    GstBuffer *codec_data;
     guint len, total;
     gint i;
 
@@ -861,6 +929,10 @@ gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
       gint state = 0;
 
       nal_len = strlen (params[i]);
+      if (nal_len == 0) {
+        GST_WARNING_OBJECT (depayload, "empty param '%s' (#%d)", params[i], i);
+        continue;
+      }
       nal = gst_buffer_new_and_alloc (nal_len);
       gst_buffer_map (nal, &nalmap, GST_MAP_READWRITE);
 
@@ -879,10 +951,14 @@ gst_rtp_h265_depay_setcaps (GstRTPBaseDepayload * depayload, GstCaps * caps)
     }
     g_strfreev (params);
 
-    if (rtph265depay->sps->len == 0 || rtph265depay->pps->len == 0)
+    if (rtph265depay->vps->len == 0 || rtph265depay->sps->len == 0 ||
+        rtph265depay->pps->len == 0) {
       goto incomplete_caps;
+    }
   }
 
+  g_free (ps);
+
   return gst_rtp_h265_set_src_caps (rtph265depay);
 
   /* ERRORS */
@@ -890,21 +966,76 @@ incomplete_caps:
   {
     GST_DEBUG_OBJECT (depayload, "we have incomplete caps,"
         " doing setcaps later");
+    g_free (ps);
     return TRUE;
   }
 }
 
 static GstBuffer *
+gst_rtp_h265_depay_allocate_output_buffer (GstRtpH265Depay * depay, gsize size)
+{
+  GstBuffer *buffer = NULL;
+
+  g_return_val_if_fail (size > 0, NULL);
+
+  GST_LOG_OBJECT (depay, "want output buffer of %u bytes", (guint) size);
+
+  buffer = gst_buffer_new_allocate (depay->allocator, size, &depay->params);
+  if (buffer == NULL) {
+    GST_INFO_OBJECT (depay, "couldn't allocate output buffer");
+    buffer = gst_buffer_new_allocate (NULL, size, NULL);
+  }
+
+  return buffer;
+}
+
+static GstBuffer *
 gst_rtp_h265_complete_au (GstRtpH265Depay * rtph265depay,
     GstClockTime * out_timestamp, gboolean * out_keyframe)
 {
-  guint outsize;
+  GstBufferList *list;
+  GstMapInfo outmap;
   GstBuffer *outbuf;
+  guint outsize, offset = 0;
+  gint b, n_bufs, m, n_mem;
 
   /* we had a picture in the adapter and we completed it */
   GST_DEBUG_OBJECT (rtph265depay, "taking completed AU");
   outsize = gst_adapter_available (rtph265depay->picture_adapter);
-  outbuf = gst_adapter_take_buffer (rtph265depay->picture_adapter, outsize);
+
+  outbuf = gst_rtp_h265_depay_allocate_output_buffer (rtph265depay, outsize);
+
+  if (outbuf == NULL)
+    return NULL;
+
+  if (!gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE))
+    return NULL;
+
+  list = gst_adapter_take_buffer_list (rtph265depay->picture_adapter, outsize);
+
+  n_bufs = gst_buffer_list_length (list);
+  for (b = 0; b < n_bufs; ++b) {
+    GstBuffer *buf = gst_buffer_list_get (list, b);
+
+    n_mem = gst_buffer_n_memory (buf);
+    for (m = 0; m < n_mem; ++m) {
+      GstMemory *mem = gst_buffer_peek_memory (buf, m);
+      gsize mem_size = gst_memory_get_sizes (mem, NULL, NULL);
+      GstMapInfo mem_map;
+
+      if (gst_memory_map (mem, &mem_map, GST_MAP_READ)) {
+        memcpy (outmap.data + offset, mem_map.data, mem_size);
+        gst_memory_unmap (mem, &mem_map);
+      } else {
+        memset (outmap.data + offset, 0, mem_size);
+      }
+      offset += mem_size;
+    }
+
+    gst_rtp_copy_video_meta (rtph265depay, outbuf, buf);
+  }
+  gst_buffer_list_unref (list);
+  gst_buffer_unmap (outbuf, &outmap);
 
   *out_timestamp = rtph265depay->last_ts;
   *out_keyframe = rtph265depay->last_keyframe;
@@ -937,63 +1068,46 @@ gst_rtp_h265_complete_au (GstRtpH265Depay * rtph265depay,
                                                                                                ||  ((nt) == GST_H265_NAL_SLICE_IDR_N_LP)\
                                                                                                ||  ((nt) == GST_H265_NAL_SLICE_CRA_NUT)                )
 
-#define NAL_TYPE_IS_KEY(nt) (NAL_TYPE_IS_PARAMETER_SET(nt) || NAL_TYPE_IS_CODED_SLICE_SEGMENT(nt))
+/* Intra random access point */
+#define NAL_TYPE_IS_IRAP(nt)   (((nt) == GST_H265_NAL_SLICE_BLA_W_LP)   \
+                             || ((nt) == GST_H265_NAL_SLICE_BLA_W_RADL) \
+                             || ((nt) == GST_H265_NAL_SLICE_BLA_N_LP)   \
+                             || ((nt) == GST_H265_NAL_SLICE_IDR_W_RADL) \
+                             || ((nt) == GST_H265_NAL_SLICE_IDR_N_LP)   \
+                             || ((nt) == GST_H265_NAL_SLICE_CRA_NUT))
 
-static gboolean
-foreach_metadata_copy (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
+#define NAL_TYPE_IS_KEY(nt) (NAL_TYPE_IS_PARAMETER_SET(nt) || NAL_TYPE_IS_IRAP(nt))
+
+static void
+gst_rtp_h265_depay_push (GstRtpH265Depay * rtph265depay, GstBuffer * outbuf,
+    gboolean keyframe, GstClockTime timestamp, gboolean marker)
 {
-  CopyMetaData *data = user_data;
-  GstElement *element = data->element;
-  GstBuffer *outbuf = data->outbuf;
-  const GstMetaInfo *info = (*meta)->info;
-  const gchar *const *tags = gst_meta_api_type_get_tags (info->api);
-
-  if (!tags || (g_strv_length ((gchar **) tags) == 1
-          && gst_meta_api_type_has_tag (info->api,
-              g_quark_from_string (GST_META_TAG_VIDEO_STR)))) {
-    GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
-    GST_DEBUG_OBJECT (element, "copy metadata %s", g_type_name (info->api));
-    /* simply copy then */
-    info->transform_func (outbuf, *meta, inbuf,
-        _gst_meta_transform_copy, &copy_data);
-  } else {
-    GST_DEBUG_OBJECT (element, "not copying metadata %s",
-        g_type_name (info->api));
+  /* prepend codec_data */
+  if (rtph265depay->codec_data) {
+    GST_DEBUG_OBJECT (rtph265depay, "prepending codec_data");
+    gst_rtp_copy_video_meta (rtph265depay, rtph265depay->codec_data, outbuf);
+    outbuf = gst_buffer_append (rtph265depay->codec_data, outbuf);
+    rtph265depay->codec_data = NULL;
+    keyframe = TRUE;
   }
+  outbuf = gst_buffer_make_writable (outbuf);
 
-  return TRUE;
-}
+  gst_rtp_drop_non_video_meta (rtph265depay, outbuf);
 
-/* TODO: Should probably make copy_tag an array at some point */
-void
-gst_rtp_copy_meta (GstElement * element, GstBuffer * outbuf, GstBuffer * inbuf,
-    GQuark copy_tag)
-{
-  CopyMetaData data = { element, outbuf, copy_tag };
+  GST_BUFFER_PTS (outbuf) = timestamp;
 
-  gst_buffer_foreach_meta (inbuf, foreach_metadata_copy, &data);
-}
+  if (keyframe)
+    GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
+  else
+    GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
 
-static gboolean
-foreach_metadata_drop (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
-{
-  GstRtpH265Depay *depay = user_data;
-  const GstMetaInfo *info = (*meta)->info;
-  const gchar *const *tags = gst_meta_api_type_get_tags (info->api);
-
-  if (!tags || (g_strv_length ((gchar **) tags) == 1
-          && gst_meta_api_type_has_tag (info->api,
-              g_quark_from_string (GST_META_TAG_VIDEO_STR)))) {
-    GST_DEBUG_OBJECT (depay, "keeping metadata %s", g_type_name (info->api));
-  } else {
-    GST_DEBUG_OBJECT (depay, "dropping metadata %s", g_type_name (info->api));
-    *meta = NULL;
-  }
+  if (marker)
+    GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_MARKER);
 
-  return TRUE;
+  gst_rtp_base_depayload_push (GST_RTP_BASE_DEPAYLOAD (rtph265depay), outbuf);
 }
 
-static GstBuffer *
+static void
 gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
     GstClockTime in_timestamp, gboolean marker)
 {
@@ -1024,7 +1138,7 @@ gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
               4, gst_buffer_get_size (nal) - 4));
       gst_buffer_unmap (nal, &map);
       gst_buffer_unref (nal);
-      return NULL;
+      return;
     } else if (rtph265depay->sps->len == 0 || rtph265depay->pps->len == 0) {
       /* Down push down any buffer in non-bytestream mode if the SPS/PPS haven't
        * go through yet
@@ -1035,7 +1149,7 @@ gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
                   "all-headers", G_TYPE_BOOLEAN, TRUE, NULL)));
       gst_buffer_unmap (nal, &map);
       gst_buffer_unref (nal);
-      return NULL;
+      return;
     }
 
     if (rtph265depay->new_codec_data &&
@@ -1049,14 +1163,12 @@ gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
     /* marker bit isn't mandatory so in the following code we try to detect
      * an AU boundary (see H.265 spec section 7.4.2.4.4) */
     if (!marker) {
-
       if (NAL_TYPE_IS_CODED_SLICE_SEGMENT (nal_type)) {
         /* A NAL unit (X) ends an access unit if the next-occurring VCL NAL unit (Y) has the high-order bit of the first byte after its NAL unit header equal to 1 */
         start = TRUE;
         if (((map.data[6] >> 7) & 0x01) == 1) {
           complete = TRUE;
         }
-        complete = TRUE;
       } else if ((nal_type >= 32 && nal_type <= 35)
           || nal_type == 39 || (nal_type >= 41 && nal_type <= 44)
           || (nal_type >= 48 && nal_type <= 55)) {
@@ -1089,29 +1201,11 @@ gst_rtp_h265_depay_handle_nal (GstRtpH265Depay * rtph265depay, GstBuffer * nal,
   }
 
   if (outbuf) {
-    /* prepend codec_data */
-    if (rtph265depay->codec_data) {
-      GST_DEBUG_OBJECT (depayload, "prepending codec_data");
-      gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay),
-          rtph265depay->codec_data, outbuf,
-          g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
-      outbuf = gst_buffer_append (rtph265depay->codec_data, outbuf);
-      rtph265depay->codec_data = NULL;
-      out_keyframe = TRUE;
-    }
-    outbuf = gst_buffer_make_writable (outbuf);
-
-    gst_buffer_foreach_meta (outbuf, foreach_metadata_drop, depayload);
-
-    GST_BUFFER_PTS (outbuf) = out_timestamp;
-
-    if (out_keyframe)
-      GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
-    else
-      GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DELTA_UNIT);
+    gst_rtp_h265_depay_push (rtph265depay, outbuf, out_keyframe, out_timestamp,
+        marker);
   }
 
-  return outbuf;
+  return;
 
   /* ERRORS */
 short_nal:
@@ -1119,19 +1213,20 @@ short_nal:
     GST_WARNING_OBJECT (depayload, "dropping short NAL");
     gst_buffer_unmap (nal, &map);
     gst_buffer_unref (nal);
-    return NULL;
+    return;
   }
 }
 
-static GstBuffer *
-gst_rtp_h265_push_fragmentation_unit (GstRtpH265Depay * rtph265depay,
-    gboolean send)
+static void
+gst_rtp_h265_finish_fragmentation_unit (GstRtpH265Depay * rtph265depay)
 {
   guint outsize;
   GstMapInfo map;
   GstBuffer *outbuf;
 
   outsize = gst_adapter_available (rtph265depay->adapter);
+  g_assert (outsize >= 4);
+
   outbuf = gst_adapter_take_buffer (rtph265depay->adapter, outsize);
 
   gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
@@ -1140,35 +1235,20 @@ gst_rtp_h265_push_fragmentation_unit (GstRtpH265Depay * rtph265depay,
   if (rtph265depay->byte_stream) {
     memcpy (map.data, sync_bytes, sizeof (sync_bytes));
   } else {
-    goto not_implemented;
+    GST_WRITE_UINT32_BE (map.data, outsize - 4);
   }
   gst_buffer_unmap (outbuf, &map);
 
   rtph265depay->current_fu_type = 0;
 
-  outbuf = gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf,
+  gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf,
       rtph265depay->fu_timestamp, rtph265depay->fu_marker);
-
-  if (send && outbuf) {
-    gst_rtp_base_depayload_push (GST_RTP_BASE_DEPAYLOAD (rtph265depay), outbuf);
-    outbuf = NULL;
-  }
-  return outbuf;
-
-not_implemented:
-  {
-    GST_ERROR_OBJECT (rtph265depay,
-        ("Only bytestream format is currently supported."));
-    gst_buffer_unmap (outbuf, &map);
-    return NULL;
-  }
 }
 
 static GstBuffer *
 gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
 {
   GstRtpH265Depay *rtph265depay;
-  GstBuffer *buf;
   GstBuffer *outbuf = NULL;
   guint8 nal_unit_type;
 
@@ -1179,6 +1259,7 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
     gst_adapter_clear (rtph265depay->adapter);
     rtph265depay->wait_start = TRUE;
     rtph265depay->current_fu_type = 0;
+    rtph265depay->last_fu_seqnum = 0;
   }
 
   {
@@ -1200,7 +1281,6 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
 
     payload_len = gst_rtp_buffer_get_payload_len (rtp);
     payload = gst_rtp_buffer_get_payload (rtp);
-    buf = gst_rtp_buffer_get_payload_buffer (rtp);
     marker = gst_rtp_buffer_get_marker (rtp);
 
     GST_DEBUG_OBJECT (rtph265depay, "receiving %d bytes", payload_len);
@@ -1238,7 +1318,7 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
      * when the FU ended) and send out what we gathered thusfar */
     if (G_UNLIKELY (rtph265depay->current_fu_type != 0 &&
             nal_unit_type != rtph265depay->current_fu_type))
-      gst_rtp_h265_push_fragmentation_unit (rtph265depay, TRUE);
+      gst_rtp_h265_finish_fragmentation_unit (rtph265depay);
 
     switch (nal_unit_type) {
       case 48:
@@ -1284,10 +1364,11 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
 #endif
 
         while (payload_len > 2) {
+          gboolean last = FALSE;
 
           nalu_size = (payload[0] << 8) | payload[1];
 
-          /* dont include nalu_size */
+          /* don't include nalu_size */
           if (nalu_size > (payload_len - 2))
             nalu_size = payload_len - 2;
 
@@ -1298,7 +1379,7 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
           if (rtph265depay->byte_stream) {
             memcpy (map.data, sync_bytes, sizeof (sync_bytes));
           } else {
-            goto not_implemented;
+            GST_WRITE_UINT32_BE (map.data, nalu_size);
           }
 
           /* strip NALU size */
@@ -1308,26 +1389,17 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
           gst_buffer_unmap (outbuf, &map);
 
-          gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
-              g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
+          gst_rtp_copy_video_meta (rtph265depay, outbuf, rtp->buffer);
 
-          outbuf =
-              gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
-              marker);
-          if (outbuf)
-            gst_adapter_push (rtph265depay->adapter, outbuf);
+          if (payload_len - nalu_size <= 2)
+            last = TRUE;
+
+          gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
+              marker && last);
 
           payload += nalu_size;
           payload_len -= nalu_size;
         }
-
-        outsize = gst_adapter_available (rtph265depay->adapter);
-        if (outsize > 0) {
-          outbuf = gst_adapter_take_buffer (rtph265depay->adapter, outsize);
-          outbuf =
-              gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
-              marker);
-        }
         break;
       }
       case 49:
@@ -1381,10 +1453,11 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
            * Assume that the remote payloader is buggy (doesn't set the end
            * bit) and send out what we've gathered thusfar */
           if (G_UNLIKELY (rtph265depay->current_fu_type != 0))
-            gst_rtp_h265_push_fragmentation_unit (rtph265depay, TRUE);
+            gst_rtp_h265_finish_fragmentation_unit (rtph265depay);
 
           rtph265depay->current_fu_type = nal_unit_type;
           rtph265depay->fu_timestamp = timestamp;
+          rtph265depay->last_fu_seqnum = gst_rtp_buffer_get_seq (rtp);
 
           rtph265depay->wait_start = FALSE;
 
@@ -1404,19 +1477,42 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
           outbuf = gst_buffer_new_and_alloc (outsize);
 
           gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
+          if (rtph265depay->byte_stream) {
+            GST_WRITE_UINT32_BE (map.data, 0x00000001);
+          } else {
+            /* will be fixed up in finish_fragmentation_unit() */
+            GST_WRITE_UINT32_BE (map.data, 0xffffffff);
+          }
           memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
-          map.data[sizeof (sync_bytes)] = nal_header >> 8;
-          map.data[sizeof (sync_bytes) + 1] = nal_header & 0xff;
+          map.data[4] = nal_header >> 8;
+          map.data[5] = nal_header & 0xff;
           gst_buffer_unmap (outbuf, &map);
 
-          gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
-              g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
+          gst_rtp_copy_video_meta (rtph265depay, outbuf, rtp->buffer);
 
           GST_DEBUG_OBJECT (rtph265depay, "queueing %d bytes", outsize);
 
           /* and assemble in the adapter */
           gst_adapter_push (rtph265depay->adapter, outbuf);
         } else {
+          if (rtph265depay->current_fu_type == 0) {
+            /* previous FU packet missing start bit? */
+            GST_WARNING_OBJECT (rtph265depay, "missing FU start bit on an "
+                "earlier packet. Dropping.");
+            gst_adapter_clear (rtph265depay->adapter);
+            return NULL;
+          }
+          if (gst_rtp_buffer_compare_seqnum (rtph265depay->last_fu_seqnum,
+                  gst_rtp_buffer_get_seq (rtp)) != 1) {
+            /* jump in sequence numbers within an FU is cause for discarding */
+            GST_WARNING_OBJECT (rtph265depay, "Jump in sequence numbers from "
+                "%u to %u within Fragmentation Unit. Data was lost, dropping "
+                "stored.", rtph265depay->last_fu_seqnum,
+                gst_rtp_buffer_get_seq (rtp));
+            gst_adapter_clear (rtph265depay->adapter);
+            return NULL;
+          }
+          rtph265depay->last_fu_seqnum = gst_rtp_buffer_get_seq (rtp);
 
           GST_DEBUG_OBJECT (rtph265depay,
               "Following part of Fragmentation Unit");
@@ -1429,8 +1525,7 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
           outbuf = gst_buffer_new_and_alloc (outsize);
           gst_buffer_fill (outbuf, 0, payload, outsize);
 
-          gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
-              g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
+          gst_rtp_copy_video_meta (rtph265depay, outbuf, rtp->buffer);
 
           GST_DEBUG_OBJECT (rtph265depay, "queueing %d bytes", outsize);
 
@@ -1443,7 +1538,7 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
 
         /* if NAL unit ends, flush the adapter */
         if (E) {
-          outbuf = gst_rtp_h265_push_fragmentation_unit (rtph265depay, FALSE);
+          gst_rtp_h265_finish_fragmentation_unit (rtph265depay);
           GST_DEBUG_OBJECT (rtph265depay, "End of Fragmentation Unit");
         }
         break;
@@ -1470,36 +1565,30 @@ gst_rtp_h265_depay_process (GstRTPBaseDepayload * depayload, GstRTPBuffer * rtp)
         if (rtph265depay->byte_stream) {
           memcpy (map.data, sync_bytes, sizeof (sync_bytes));
         } else {
-          goto not_implemented;
+          GST_WRITE_UINT32_BE (map.data, nalu_size);
         }
-        memcpy (map.data + sizeof (sync_bytes), payload, nalu_size);
+        memcpy (map.data + 4, payload, nalu_size);
         gst_buffer_unmap (outbuf, &map);
 
-        gst_rtp_copy_meta (GST_ELEMENT_CAST (rtph265depay), outbuf, buf,
-            g_quark_from_static_string (GST_META_TAG_VIDEO_STR));
+        gst_rtp_copy_video_meta (rtph265depay, outbuf, rtp->buffer);
 
-        outbuf = gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp,
-            marker);
+        gst_rtp_h265_depay_handle_nal (rtph265depay, outbuf, timestamp, marker);
         break;
       }
     }
   }
 
-  gst_buffer_unref (buf);
-
-  return outbuf;
+  return NULL;
 
   /* ERRORS */
 empty_packet:
   {
     GST_DEBUG_OBJECT (rtph265depay, "empty packet");
-    gst_buffer_unref (buf);
     return NULL;
   }
 waiting_start:
   {
     GST_DEBUG_OBJECT (rtph265depay, "waiting for start");
-    gst_buffer_unref (buf);
     return NULL;
   }
 #if 0
@@ -1507,7 +1596,6 @@ not_implemented_donl_present:
   {
     GST_ELEMENT_ERROR (rtph265depay, STREAM, FORMAT,
         (NULL), ("DONL field present not supported yet"));
-    gst_buffer_unref (buf);
     return NULL;
   }
 #endif
@@ -1515,7 +1603,6 @@ not_implemented:
   {
     GST_ELEMENT_ERROR (rtph265depay, STREAM, FORMAT,
         (NULL), ("NAL unit type %d not supported yet", nal_unit_type));
-    gst_buffer_unref (buf);
     return NULL;
   }
 }
@@ -1529,7 +1616,10 @@ gst_rtp_h265_depay_handle_event (GstRTPBaseDepayload * depay, GstEvent * event)
 
   switch (GST_EVENT_TYPE (event)) {
     case GST_EVENT_FLUSH_STOP:
-      gst_rtp_h265_depay_reset (rtph265depay);
+      gst_rtp_h265_depay_reset (rtph265depay, FALSE);
+      break;
+    case GST_EVENT_EOS:
+      gst_rtp_h265_depay_drain (rtph265depay);
       break;
     default:
       break;
@@ -1552,7 +1642,7 @@ gst_rtp_h265_depay_change_state (GstElement * element,
     case GST_STATE_CHANGE_NULL_TO_READY:
       break;
     case GST_STATE_CHANGE_READY_TO_PAUSED:
-      gst_rtp_h265_depay_reset (rtph265depay);
+      gst_rtp_h265_depay_reset (rtph265depay, TRUE);
       break;
     default:
       break;
@@ -1561,6 +1651,9 @@ gst_rtp_h265_depay_change_state (GstElement * element,
   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
 
   switch (transition) {
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      gst_rtp_h265_depay_reset (rtph265depay, TRUE);
+      break;
     case GST_STATE_CHANGE_READY_TO_NULL:
       break;
     default: