static GstFlowReturn
gst_jp2k_decimator_decimate_jpc (GstJP2kDecimator * self, GstBuffer * inbuf,
    GstBuffer ** outbuf_)
{
  GstBuffer *outbuf = NULL;
  GstFlowReturn ret = GST_FLOW_OK;
  GstMapInfo info;
  GstByteReader reader;
  GstByteWriter writer;
  MainHeader main_header;


  if (!gst_buffer_map (inbuf, &info, GST_MAP_READ)) {
    GST_ELEMENT_ERROR (self, STREAM, WRONG_TYPE, ("Unable to map memory"),
        (NULL));
    gst_buffer_unref (inbuf);
    return GST_FLOW_ERROR;
  }

  gst_byte_reader_init (&reader, info.data, info.size);
  gst_byte_writer_init_with_size (&writer, gst_buffer_get_size (inbuf), FALSE);

  /* main header */
  memset (&main_header, 0, sizeof (MainHeader));
  ret = parse_main_header (self, &reader, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  ret = decimate_main_header (self, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  ret = write_main_header (self, &writer, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  outbuf = gst_byte_writer_reset_and_get_buffer (&writer);
  gst_buffer_copy_into (outbuf, inbuf, GST_BUFFER_COPY_METADATA, 0, -1);

  GST_DEBUG_OBJECT (self,
      "Decimated buffer from %" G_GSIZE_FORMAT " bytes to %" G_GSIZE_FORMAT
      " bytes (%.2lf%%)",
      gst_buffer_get_size (inbuf), gst_buffer_get_size (outbuf),
      (100 * gst_buffer_get_size (outbuf)) /
      ((gdouble) gst_buffer_get_size (inbuf)));

done:
  gst_buffer_unmap (inbuf, &info);

  *outbuf_ = outbuf;
  reset_main_header (self, &main_header);
  gst_buffer_unref (inbuf);

  return ret;
}
static GstFlowReturn
gst_jp2k_decimator_decimate_jpc (GstJP2kDecimator * self, GstBuffer * inbuf,
    GstBuffer ** outbuf_)
{
  GstBuffer *outbuf = NULL;
  GstFlowReturn ret = GST_FLOW_OK;
  GstByteReader reader = GST_BYTE_READER_INIT_FROM_BUFFER (inbuf);
  GstByteWriter writer;
  MainHeader main_header;

  gst_byte_writer_init_with_size (&writer, GST_BUFFER_SIZE (inbuf), FALSE);

  /* main header */
  memset (&main_header, 0, sizeof (MainHeader));
  ret = parse_main_header (self, &reader, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  ret = decimate_main_header (self, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  ret = write_main_header (self, &writer, &main_header);
  if (ret != GST_FLOW_OK)
    goto done;

  outbuf = gst_byte_writer_reset_and_get_buffer (&writer);
  gst_buffer_copy_metadata (outbuf, inbuf, GST_BUFFER_COPY_ALL);

  GST_DEBUG_OBJECT (self,
      "Decimated buffer from %u bytes to %u bytes (%.2lf%%)",
      GST_BUFFER_SIZE (inbuf), GST_BUFFER_SIZE (outbuf),
      (100 * GST_BUFFER_SIZE (outbuf)) / ((gdouble) GST_BUFFER_SIZE (inbuf)));

done:
  *outbuf_ = outbuf;
  reset_main_header (self, &main_header);
  gst_buffer_unref (inbuf);

  return ret;
}