<commit_before>/*
 *  gstvaapiencoder.c - VA encoder abstraction
 *
 *  Copyright (C) 2013-2014 Intel Corporation
 *    Author: <NAME> <<EMAIL>>
 *    Author: <NAME> <<EMAIL>>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301 USA
 */

#include "sysdeps.h"
#include "gstvaapicompat.h"
#include "gstvaapiencoder.h"
#include "gstvaapiencoder_priv.h"
#include "gstvaapicontext.h"
#include "gstvaapidisplay_priv.h"
#include "gstvaapiutils.h"
#include "gstvaapiutils_core.h"
#include "gstvaapivalue.h"

#define DEBUG 1
#include "gstvaapidebug.h"

/* Helper function to create a new encoder property object */
static GstVaapiEncoderPropData *
prop_new (gint id, GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!id || !pspec)
    return NULL;

  prop = g_slice_new (GstVaapiEncoderPropData);
  if (!prop)
    return NULL;

  prop->prop = id;
  prop->pspec = g_param_spec_ref_sink (pspec);
  return prop;
}

/* Helper function to release a property object and any memory held herein */
static void
prop_free (GstVaapiEncoderPropData * prop)
{
  if (!prop)
    return;

  if (prop->pspec) {
    g_param_spec_unref (prop->pspec);
    prop->pspec = NULL;
  }
  g_slice_free (GstVaapiEncoderPropData, prop);
}

/* Helper function to lookup the supplied property specification */
static GParamSpec *
prop_find_pspec (GstVaapiEncoder * encoder, gint prop_id)
{
  GPtrArray *const props = encoder->properties;
  guint i;

  if (props) {
    for (i = 0; i < props->len; i++) {
      GstVaapiEncoderPropInfo *const prop = g_ptr_array_index (props, i);
      if (prop->prop == prop_id)
        return prop->pspec;
    }
  }
  return NULL;
}

/* Create a new array of properties, or NULL on error */
GPtrArray *
gst_vaapi_encoder_properties_append (GPtrArray * props, gint prop_id,
    GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!props) {
    props = g_ptr_array_new_with_free_func ((GDestroyNotify) prop_free);
    if (!props)
      return NULL;
  }

  prop = prop_new (prop_id, pspec);
  if (!prop)
    goto error_allocation_failed;
  g_ptr_array_add (props, prop);
  return props;

  /* ERRORS */
error_allocation_failed:
  {
    GST_ERROR ("failed to allocate encoder property info structure");
    g_ptr_array_unref (props);
    return NULL;
  }
}

/* Generate the common set of encoder properties */
GPtrArray *
gst_vaapi_encoder_properties_get_default (const GstVaapiEncoderClass * klass)
{
  const GstVaapiEncoderClassData *const cdata = klass->class_data;
  GPtrArray *props = NULL;

  g_assert (cdata->rate_control_get_type != NULL);

  /**
   * GstVaapiEncoder:rate-control:
   *
   * The desired rate control mode, expressed as a #GstVaapiRateControl.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_RATECONTROL,
      g_param_spec_enum ("rate-control",
          "Rate Control", "Rate control mode",
          cdata->rate_control_get_type (), cdata->default_rate_control,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:bitrate:
   *
   * The desired bitrate, expressed in kbps.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_BITRATE,
      g_param_spec_uint ("bitrate",
          "Bitrate (kbps)",
          "The desired bitrate expressed in kbps (0: auto-calculate)",
          0, 100 * 1024, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:keyframe-period:
   *
   * The maximal distance between two keyframes.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_KEYFRAME_PERIOD,
      g_param_spec_uint ("keyframe-period",
          "Keyframe Period",
          "Maximal distance between two keyframes (0: auto-calculate)", 1, 300,
          30, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:tune:
   *
   * The desired encoder tuning option.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_TUNE,
      g_param_spec_enum ("tune",
          "Encoder Tuning",
          "Encoder tuning option",
          cdata->encoder_tune_get_type (), cdata->default_encoder_tune,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  return props;
}

/**
 * gst_vaapi_encoder_ref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically increases the reference count of the given @encoder by one.
 *
 * Returns: The same @encoder argument
 */
GstVaapiEncoder *
gst_vaapi_encoder_ref (GstVaapiEncoder * encoder)
{
  return gst_vaapi_object_ref (encoder);
}

/**
 * gst_vaapi_encoder_unref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically decreases the reference count of the @encoder by one. If
 * the reference count reaches zero, the encoder will be free'd.
 */
void
gst_vaapi_encoder_unref (GstVaapiEncoder * encoder)
{
  gst_vaapi_object_unref (encoder);
}

/**
 * gst_vaapi_encoder_replace:
 * @old_encoder_ptr: a pointer to a #GstVaapiEncoder
 * @new_encoder: a #GstVaapiEncoder
 *
 * Atomically replaces the encoder encoder held in @old_encoder_ptr
 * with @new_encoder. This means that @old_encoder_ptr shall reference
 * a valid encoder. However, @new_encoder can be NULL.
 */
void
gst_vaapi_encoder_replace (GstVaapiEncoder ** old_encoder_ptr,
    GstVaapiEncoder * new_encoder)
{
  gst_vaapi_object_replace (old_encoder_ptr, new_encoder);
}

/* Notifies gst_vaapi_encoder_create_coded_buffer() that a new buffer is free */
static void
_coded_buffer_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->codedbuf_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA coded buffer object proxy, backed from a pool */
static GstVaapiCodedBufferProxy *
gst_vaapi_encoder_create_coded_buffer (GstVaapiEncoder * encoder)
{
  GstVaapiCodedBufferPool *const pool =
      GST_VAAPI_CODED_BUFFER_POOL (encoder->codedbuf_pool);
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  g_mutex_lock (&encoder->mutex);
  do {
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
    if (codedbuf_proxy)
      break;

    /* Wait for a free coded buffer to become available */
    g_cond_wait (&encoder->codedbuf_free, &encoder->mutex);
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
  } while (0);
  g_mutex_unlock (&encoder->mutex);
  if (!codedbuf_proxy)
    return NULL;

  gst_vaapi_coded_buffer_proxy_set_destroy_notify (codedbuf_proxy,
      (GDestroyNotify) _coded_buffer_proxy_released_notify, encoder);
  return codedbuf_proxy;
}

/* Notifies gst_vaapi_encoder_create_surface() that a new surface is free */
static void
_surface_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->surface_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA surface object proxy, backed from a pool and
   useful to allocate reconstructed surfaces */
GstVaapiSurfaceProxy *
gst_vaapi_encoder_create_surface (GstVaapiEncoder * encoder)
{
  GstVaapiSurfaceProxy *proxy;

  g_return_val_if_fail (encoder->context != NULL, NULL);

  g_mutex_lock (&encoder->mutex);
  for (;;) {
    proxy = gst_vaapi_context_get_surface_proxy (encoder->context);
    if (proxy)
      break;

    /* Wait for a free surface proxy to become available */
    g_cond_wait (&encoder->surface_free, &encoder->mutex);
  }
  g_mutex_unlock (&encoder->mutex);

  gst_vaapi_surface_proxy_set_destroy_notify (proxy,
      (GDestroyNotify) _surface_proxy_released_notify, encoder);
  return proxy;
}

/**
 * gst_vaapi_encoder_put_frame:
 * @encoder: a #GstVaapiEncoder
 * @frame: a #GstVideoCodecFrame
 *
 * Queues a #GstVideoCodedFrame to the HW encoder. The encoder holds
 * an extra reference to the @frame.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_put_frame (GstVaapiEncoder * encoder,
    GstVideoCodecFrame * frame)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);
  GstVaapiEncoderStatus status;
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  for (;;) {
    picture = NULL;
    status = klass->reordering (encoder, frame, &picture);
    if (status == GST_VAAPI_ENCODER_STATUS_NO_SURFACE)
      break;
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_reorder_frame;

    codedbuf_proxy = gst_vaapi_encoder_create_coded_buffer (encoder);
    if (!codedbuf_proxy)
      goto error_create_coded_buffer;

    status = klass->encode (encoder, picture, codedbuf_proxy);
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_encode;

    gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
        picture, (GDestroyNotify) gst_vaapi_mini_object_unref);
    g_async_queue_push (encoder->codedbuf_queue, codedbuf_proxy);
    encoder->num_codedbuf_queued++;

    /* Try again with any pending reordered frame now available for encoding */
    frame = NULL;
  }
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_reorder_frame:
  {
    GST_ERROR ("failed to process reordered frames");
    return status;
  }
error_create_coded_buffer:
  {
    GST_ERROR ("failed to allocate coded buffer");
    gst_vaapi_enc_picture_unref (picture);
    return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
  }
error_encode:
  {
    GST_ERROR ("failed to encode frame (status = %d)", status);
    gst_vaapi_enc_picture_unref (picture);
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return status;
  }
}

/**
 * gst_vaapi_encoder_get_buffer_with_timeout:
 * @encoder: a #GstVaapiEncoder
 * @out_codedbuf_proxy_ptr: the next coded buffer as a #GstVaapiCodedBufferProxy
 * @timeout: the number of microseconds to wait for the coded buffer, at most
 *
 * Upon successful return, *@out_codedbuf_proxy_ptr contains the next
 * coded buffer as a #GstVaapiCodedBufferProxy. The caller owns this
 * object, so gst_vaapi_coded_buffer_proxy_unref() shall be called
 * after usage. Otherwise, @GST_VAAPI_DECODER_STATUS_ERROR_NO_BUFFER
 * is returned if no coded buffer is available so far (timeout).
 *
 * The parent frame is available as a #GstVideoCodecFrame attached to
 * the user-data anchor of the output coded buffer. Ownership of the
 * frame is transferred to the coded buffer.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_buffer_with_timeout (GstVaapiEncoder * encoder,
    GstVaapiCodedBufferProxy ** out_codedbuf_proxy_ptr, guint64 timeout)
{
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  codedbuf_proxy = g_async_queue_timeout_pop (encoder->codedbuf_queue, timeout);
  if (!codedbuf_proxy)
    return GST_VAAPI_ENCODER_STATUS_NO_BUFFER;

  /* Wait for completion of all operations and report any error that occurred */
  picture = gst_vaapi_coded_buffer_proxy_get_user_data (codedbuf_proxy);
  if (!gst_vaapi_surface_sync (picture->surface))
    goto error_invalid_buffer;

  gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
      gst_video_codec_frame_ref (picture->frame),
      (GDestroyNotify) gst_video_codec_frame_unref);

  if (out_codedbuf_proxy_ptr)
    *out_codedbuf_proxy_ptr = gst_vaapi_coded_buffer_proxy_ref (codedbuf_proxy);
  gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_buffer:
  {
    GST_ERROR ("failed to encode the frame");
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_SURFACE;
  }
}

/**
 * gst_vaapi_encoder_flush:
 * @encoder: a #GstVaapiEncoder
 *
 * Submits any pending (reordered) frame for encoding.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_flush (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  return klass->flush (encoder);
}

/**
 * gst_vaapi_encoder_get_codec_data:
 * @encoder: a #GstVaapiEncoder
 * @out_codec_data_ptr: the pointer to the resulting codec-data (#GstBuffer)
 *
 * Returns a codec-data buffer that best represents the encoded
 * bitstream. Upon successful return, and if the @out_codec_data_ptr
 * contents is not NULL, then the caller function shall deallocates
 * that buffer with gst_buffer_unref().
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_codec_data (GstVaapiEncoder * encoder,
    GstBuffer ** out_codec_data_ptr)
{
  GstVaapiEncoderStatus ret = GST_VAAPI_ENCODER_STATUS_SUCCESS;
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  *out_codec_data_ptr = NULL;
  if (!klass->get_codec_data)
    return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  ret = klass->get_codec_data (encoder, out_codec_data_ptr);
  return ret;
}

/* Checks video info */
static GstVaapiEncoderStatus
check_video_info (GstVaapiEncoder * encoder, const GstVideoInfo * vip)
{
  if (!vip->width || !vip->height)
    goto error_invalid_resolution;
  if (vip->fps_n < 0 || vip->fps_d <= 0)
    goto error_invalid_framerate;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_resolution:
  {
    GST_ERROR ("invalid resolution (%dx%d)", vip->width, vip->height);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
error_invalid_framerate:
  {
    GST_ERROR ("invalid framerate (%d/%d)", vip->fps_n, vip->fps_d);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
}

/* Gets a compatible profile for the active codec */
static GstVaapiProfile
get_compatible_profile (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  GstVaapiProfile profile;
  GArray *profiles;
  guint i;

  profiles = gst_vaapi_display_get_encode_profiles (encoder->display);
  if (!profiles)
    return GST_VAAPI_PROFILE_UNKNOWN;

  // Pick a profile matching the class codec
  for (i = 0; i < profiles->len; i++) {
    profile = g_array_index (profiles, GstVaapiProfile, i);
    if (gst_vaapi_profile_get_codec (profile) == cdata->codec)
      break;
  }
  if (i == profiles->len)
    profile = GST_VAAPI_PROFILE_UNKNOWN;

  g_array_unref (profiles);
  return profile;
}

/* Gets a supported profile for the active codec */
static GstVaapiProfile
get_profile (GstVaapiEncoder * encoder)
{
  if (!encoder->profile)
    encoder->profile = get_compatible_profile (encoder);
  return encoder->profile;
}

/* Gets config attribute for the supplied profile */
static gboolean
get_config_attribute (GstVaapiEncoder * encoder, VAConfigAttribType type,
    guint * out_value_ptr)
{
  GstVaapiProfile profile;
  VAProfile va_profile;
  VAEntrypoint va_entrypoint;
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;

  profile = get_profile (encoder);
  if (!profile)
    return FALSE;
  va_profile = gst_vaapi_profile_get_va_profile (profile);

  if (cdata->codec != GST_VAAPI_CODEC_JPEG)
    va_entrypoint = VAEntrypointEncSlice;
  else
    va_entrypoint = VAEntrypointEncPicture;

  return gst_vaapi_get_config_attribute (encoder->display, va_profile,
      va_entrypoint, type, out_value_ptr);
}

/* Determines the set of supported packed headers */
static guint
get_packed_headers (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  guint value;

  if (encoder->got_packed_headers)
    return encoder->packed_headers;

  if (!get_config_attribute (encoder, VAConfigAttribEncPackedHeaders, &value))
    value = 0;
  GST_INFO ("supported packed headers: 0x%08x", value);<commit_msg>gstvaapiencoder:Use internal api to dervie configured VAEntrypoint<commit_after>/*
 *  gstvaapiencoder.c - VA encoder abstraction
 *
 *  Copyright (C) 2013-2014 Intel Corporation
 *    Author: <NAME> <<EMAIL>>
 *    Author: <NAME> <<EMAIL>>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free
 *  Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301 USA
 */

#include "sysdeps.h"
#include "gstvaapicompat.h"
#include "gstvaapiencoder.h"
#include "gstvaapiencoder_priv.h"
#include "gstvaapicontext.h"
#include "gstvaapidisplay_priv.h"
#include "gstvaapiutils.h"
#include "gstvaapiutils_core.h"
#include "gstvaapivalue.h"

#define DEBUG 1
#include "gstvaapidebug.h"

/* Helper function to create a new encoder property object */
static GstVaapiEncoderPropData *
prop_new (gint id, GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!id || !pspec)
    return NULL;

  prop = g_slice_new (GstVaapiEncoderPropData);
  if (!prop)
    return NULL;

  prop->prop = id;
  prop->pspec = g_param_spec_ref_sink (pspec);
  return prop;
}

/* Helper function to release a property object and any memory held herein */
static void
prop_free (GstVaapiEncoderPropData * prop)
{
  if (!prop)
    return;

  if (prop->pspec) {
    g_param_spec_unref (prop->pspec);
    prop->pspec = NULL;
  }
  g_slice_free (GstVaapiEncoderPropData, prop);
}

/* Helper function to lookup the supplied property specification */
static GParamSpec *
prop_find_pspec (GstVaapiEncoder * encoder, gint prop_id)
{
  GPtrArray *const props = encoder->properties;
  guint i;

  if (props) {
    for (i = 0; i < props->len; i++) {
      GstVaapiEncoderPropInfo *const prop = g_ptr_array_index (props, i);
      if (prop->prop == prop_id)
        return prop->pspec;
    }
  }
  return NULL;
}

/* Create a new array of properties, or NULL on error */
GPtrArray *
gst_vaapi_encoder_properties_append (GPtrArray * props, gint prop_id,
    GParamSpec * pspec)
{
  GstVaapiEncoderPropData *prop;

  if (!props) {
    props = g_ptr_array_new_with_free_func ((GDestroyNotify) prop_free);
    if (!props)
      return NULL;
  }

  prop = prop_new (prop_id, pspec);
  if (!prop)
    goto error_allocation_failed;
  g_ptr_array_add (props, prop);
  return props;

  /* ERRORS */
error_allocation_failed:
  {
    GST_ERROR ("failed to allocate encoder property info structure");
    g_ptr_array_unref (props);
    return NULL;
  }
}

/* Generate the common set of encoder properties */
GPtrArray *
gst_vaapi_encoder_properties_get_default (const GstVaapiEncoderClass * klass)
{
  const GstVaapiEncoderClassData *const cdata = klass->class_data;
  GPtrArray *props = NULL;

  g_assert (cdata->rate_control_get_type != NULL);

  /**
   * GstVaapiEncoder:rate-control:
   *
   * The desired rate control mode, expressed as a #GstVaapiRateControl.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_RATECONTROL,
      g_param_spec_enum ("rate-control",
          "Rate Control", "Rate control mode",
          cdata->rate_control_get_type (), cdata->default_rate_control,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:bitrate:
   *
   * The desired bitrate, expressed in kbps.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_BITRATE,
      g_param_spec_uint ("bitrate",
          "Bitrate (kbps)",
          "The desired bitrate expressed in kbps (0: auto-calculate)",
          0, 100 * 1024, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:keyframe-period:
   *
   * The maximal distance between two keyframes.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_KEYFRAME_PERIOD,
      g_param_spec_uint ("keyframe-period",
          "Keyframe Period",
          "Maximal distance between two keyframes (0: auto-calculate)", 1, 300,
          30, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  /**
   * GstVaapiEncoder:tune:
   *
   * The desired encoder tuning option.
   */
  GST_VAAPI_ENCODER_PROPERTIES_APPEND (props,
      GST_VAAPI_ENCODER_PROP_TUNE,
      g_param_spec_enum ("tune",
          "Encoder Tuning",
          "Encoder tuning option",
          cdata->encoder_tune_get_type (), cdata->default_encoder_tune,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  return props;
}

/**
 * gst_vaapi_encoder_ref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically increases the reference count of the given @encoder by one.
 *
 * Returns: The same @encoder argument
 */
GstVaapiEncoder *
gst_vaapi_encoder_ref (GstVaapiEncoder * encoder)
{
  return gst_vaapi_object_ref (encoder);
}

/**
 * gst_vaapi_encoder_unref:
 * @encoder: a #GstVaapiEncoder
 *
 * Atomically decreases the reference count of the @encoder by one. If
 * the reference count reaches zero, the encoder will be free'd.
 */
void
gst_vaapi_encoder_unref (GstVaapiEncoder * encoder)
{
  gst_vaapi_object_unref (encoder);
}

/**
 * gst_vaapi_encoder_replace:
 * @old_encoder_ptr: a pointer to a #GstVaapiEncoder
 * @new_encoder: a #GstVaapiEncoder
 *
 * Atomically replaces the encoder encoder held in @old_encoder_ptr
 * with @new_encoder. This means that @old_encoder_ptr shall reference
 * a valid encoder. However, @new_encoder can be NULL.
 */
void
gst_vaapi_encoder_replace (GstVaapiEncoder ** old_encoder_ptr,
    GstVaapiEncoder * new_encoder)
{
  gst_vaapi_object_replace (old_encoder_ptr, new_encoder);
}

/* Notifies gst_vaapi_encoder_create_coded_buffer() that a new buffer is free */
static void
_coded_buffer_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->codedbuf_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA coded buffer object proxy, backed from a pool */
static GstVaapiCodedBufferProxy *
gst_vaapi_encoder_create_coded_buffer (GstVaapiEncoder * encoder)
{
  GstVaapiCodedBufferPool *const pool =
      GST_VAAPI_CODED_BUFFER_POOL (encoder->codedbuf_pool);
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  g_mutex_lock (&encoder->mutex);
  do {
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
    if (codedbuf_proxy)
      break;

    /* Wait for a free coded buffer to become available */
    g_cond_wait (&encoder->codedbuf_free, &encoder->mutex);
    codedbuf_proxy = gst_vaapi_coded_buffer_proxy_new_from_pool (pool);
  } while (0);
  g_mutex_unlock (&encoder->mutex);
  if (!codedbuf_proxy)
    return NULL;

  gst_vaapi_coded_buffer_proxy_set_destroy_notify (codedbuf_proxy,
      (GDestroyNotify) _coded_buffer_proxy_released_notify, encoder);
  return codedbuf_proxy;
}

/* Notifies gst_vaapi_encoder_create_surface() that a new surface is free */
static void
_surface_proxy_released_notify (GstVaapiEncoder * encoder)
{
  g_mutex_lock (&encoder->mutex);
  g_cond_signal (&encoder->surface_free);
  g_mutex_unlock (&encoder->mutex);
}

/* Creates a new VA surface object proxy, backed from a pool and
   useful to allocate reconstructed surfaces */
GstVaapiSurfaceProxy *
gst_vaapi_encoder_create_surface (GstVaapiEncoder * encoder)
{
  GstVaapiSurfaceProxy *proxy;

  g_return_val_if_fail (encoder->context != NULL, NULL);

  g_mutex_lock (&encoder->mutex);
  for (;;) {
    proxy = gst_vaapi_context_get_surface_proxy (encoder->context);
    if (proxy)
      break;

    /* Wait for a free surface proxy to become available */
    g_cond_wait (&encoder->surface_free, &encoder->mutex);
  }
  g_mutex_unlock (&encoder->mutex);

  gst_vaapi_surface_proxy_set_destroy_notify (proxy,
      (GDestroyNotify) _surface_proxy_released_notify, encoder);
  return proxy;
}

/**
 * gst_vaapi_encoder_put_frame:
 * @encoder: a #GstVaapiEncoder
 * @frame: a #GstVideoCodecFrame
 *
 * Queues a #GstVideoCodedFrame to the HW encoder. The encoder holds
 * an extra reference to the @frame.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_put_frame (GstVaapiEncoder * encoder,
    GstVideoCodecFrame * frame)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);
  GstVaapiEncoderStatus status;
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  for (;;) {
    picture = NULL;
    status = klass->reordering (encoder, frame, &picture);
    if (status == GST_VAAPI_ENCODER_STATUS_NO_SURFACE)
      break;
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_reorder_frame;

    codedbuf_proxy = gst_vaapi_encoder_create_coded_buffer (encoder);
    if (!codedbuf_proxy)
      goto error_create_coded_buffer;

    status = klass->encode (encoder, picture, codedbuf_proxy);
    if (status != GST_VAAPI_ENCODER_STATUS_SUCCESS)
      goto error_encode;

    gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
        picture, (GDestroyNotify) gst_vaapi_mini_object_unref);
    g_async_queue_push (encoder->codedbuf_queue, codedbuf_proxy);
    encoder->num_codedbuf_queued++;

    /* Try again with any pending reordered frame now available for encoding */
    frame = NULL;
  }
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_reorder_frame:
  {
    GST_ERROR ("failed to process reordered frames");
    return status;
  }
error_create_coded_buffer:
  {
    GST_ERROR ("failed to allocate coded buffer");
    gst_vaapi_enc_picture_unref (picture);
    return GST_VAAPI_ENCODER_STATUS_ERROR_ALLOCATION_FAILED;
  }
error_encode:
  {
    GST_ERROR ("failed to encode frame (status = %d)", status);
    gst_vaapi_enc_picture_unref (picture);
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return status;
  }
}

/**
 * gst_vaapi_encoder_get_buffer_with_timeout:
 * @encoder: a #GstVaapiEncoder
 * @out_codedbuf_proxy_ptr: the next coded buffer as a #GstVaapiCodedBufferProxy
 * @timeout: the number of microseconds to wait for the coded buffer, at most
 *
 * Upon successful return, *@out_codedbuf_proxy_ptr contains the next
 * coded buffer as a #GstVaapiCodedBufferProxy. The caller owns this
 * object, so gst_vaapi_coded_buffer_proxy_unref() shall be called
 * after usage. Otherwise, @GST_VAAPI_DECODER_STATUS_ERROR_NO_BUFFER
 * is returned if no coded buffer is available so far (timeout).
 *
 * The parent frame is available as a #GstVideoCodecFrame attached to
 * the user-data anchor of the output coded buffer. Ownership of the
 * frame is transferred to the coded buffer.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_buffer_with_timeout (GstVaapiEncoder * encoder,
    GstVaapiCodedBufferProxy ** out_codedbuf_proxy_ptr, guint64 timeout)
{
  GstVaapiEncPicture *picture;
  GstVaapiCodedBufferProxy *codedbuf_proxy;

  codedbuf_proxy = g_async_queue_timeout_pop (encoder->codedbuf_queue, timeout);
  if (!codedbuf_proxy)
    return GST_VAAPI_ENCODER_STATUS_NO_BUFFER;

  /* Wait for completion of all operations and report any error that occurred */
  picture = gst_vaapi_coded_buffer_proxy_get_user_data (codedbuf_proxy);
  if (!gst_vaapi_surface_sync (picture->surface))
    goto error_invalid_buffer;

  gst_vaapi_coded_buffer_proxy_set_user_data (codedbuf_proxy,
      gst_video_codec_frame_ref (picture->frame),
      (GDestroyNotify) gst_video_codec_frame_unref);

  if (out_codedbuf_proxy_ptr)
    *out_codedbuf_proxy_ptr = gst_vaapi_coded_buffer_proxy_ref (codedbuf_proxy);
  gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_buffer:
  {
    GST_ERROR ("failed to encode the frame");
    gst_vaapi_coded_buffer_proxy_unref (codedbuf_proxy);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_SURFACE;
  }
}

/**
 * gst_vaapi_encoder_flush:
 * @encoder: a #GstVaapiEncoder
 *
 * Submits any pending (reordered) frame for encoding.
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_flush (GstVaapiEncoder * encoder)
{
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  return klass->flush (encoder);
}

/**
 * gst_vaapi_encoder_get_codec_data:
 * @encoder: a #GstVaapiEncoder
 * @out_codec_data_ptr: the pointer to the resulting codec-data (#GstBuffer)
 *
 * Returns a codec-data buffer that best represents the encoded
 * bitstream. Upon successful return, and if the @out_codec_data_ptr
 * contents is not NULL, then the caller function shall deallocates
 * that buffer with gst_buffer_unref().
 *
 * Return value: a #GstVaapiEncoderStatus
 */
GstVaapiEncoderStatus
gst_vaapi_encoder_get_codec_data (GstVaapiEncoder * encoder,
    GstBuffer ** out_codec_data_ptr)
{
  GstVaapiEncoderStatus ret = GST_VAAPI_ENCODER_STATUS_SUCCESS;
  GstVaapiEncoderClass *const klass = GST_VAAPI_ENCODER_GET_CLASS (encoder);

  *out_codec_data_ptr = NULL;
  if (!klass->get_codec_data)
    return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  ret = klass->get_codec_data (encoder, out_codec_data_ptr);
  return ret;
}

/* Checks video info */
static GstVaapiEncoderStatus
check_video_info (GstVaapiEncoder * encoder, const GstVideoInfo * vip)
{
  if (!vip->width || !vip->height)
    goto error_invalid_resolution;
  if (vip->fps_n < 0 || vip->fps_d <= 0)
    goto error_invalid_framerate;
  return GST_VAAPI_ENCODER_STATUS_SUCCESS;

  /* ERRORS */
error_invalid_resolution:
  {
    GST_ERROR ("invalid resolution (%dx%d)", vip->width, vip->height);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
error_invalid_framerate:
  {
    GST_ERROR ("invalid framerate (%d/%d)", vip->fps_n, vip->fps_d);
    return GST_VAAPI_ENCODER_STATUS_ERROR_INVALID_PARAMETER;
  }
}

/* Gets a compatible profile for the active codec */
static GstVaapiProfile
get_compatible_profile (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  GstVaapiProfile profile;
  GArray *profiles;
  guint i;

  profiles = gst_vaapi_display_get_encode_profiles (encoder->display);
  if (!profiles)
    return GST_VAAPI_PROFILE_UNKNOWN;

  // Pick a profile matching the class codec
  for (i = 0; i < profiles->len; i++) {
    profile = g_array_index (profiles, GstVaapiProfile, i);
    if (gst_vaapi_profile_get_codec (profile) == cdata->codec)
      break;
  }
  if (i == profiles->len)
    profile = GST_VAAPI_PROFILE_UNKNOWN;

  g_array_unref (profiles);
  return profile;
}

/* Gets a supported profile for the active codec */
static GstVaapiProfile
get_profile (GstVaapiEncoder * encoder)
{
  if (!encoder->profile)
    encoder->profile = get_compatible_profile (encoder);
  return encoder->profile;
}

/* Gets config attribute for the supplied profile */
static gboolean
get_config_attribute (GstVaapiEncoder * encoder, VAConfigAttribType type,
    guint * out_value_ptr)
{
  GstVaapiProfile profile;
  VAProfile va_profile;
  VAEntrypoint va_entrypoint;

  profile = get_profile (encoder);
  if (!profile)
    return FALSE;
  va_profile = gst_vaapi_profile_get_va_profile (profile);

  va_entrypoint =
      gst_vaapi_entrypoint_get_va_entrypoint (encoder->context_info.entrypoint);

  return gst_vaapi_get_config_attribute (encoder->display, va_profile,
      va_entrypoint, type, out_value_ptr);
}

/* Determines the set of supported packed headers */
static guint
get_packed_headers (GstVaapiEncoder * encoder)
{
  const GstVaapiEncoderClassData *const cdata =
      GST_VAAPI_ENCODER_GET_CLASS (encoder)->class_data;
  guint value;

  if (encoder->got_packed_headers)
    return encoder->packed_headers;

  if (!get_config_attribute (encoder, VAConfigAttribEncPackedHeaders, &value))
    value = 0;
  GST_INFO ("supported packed headers: 0x%08x", value);
{'fraction_non_alphanumeric': 0.08715314095859227, 'fraction_numerical': 0.0030763551344367194, 'mean_word_length': 4.550110978316544, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 142, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2998464', 'n_tokens_mistral': 11550, 'n_tokens_neox': 11006, 'n_words': 2632}