/* gstreamermm - a C++ wrapper for gstreamer
 *
 * Copyright 2008-2009 The gstreamermm Development Team
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <gst/audio/audio-enumtypes.h>
#include <gstreamermm/handle_error.h>
_PINCLUDE(gstreamermm/private/object_p.h)

namespace
{

extern "C"
{

static void RingBuffer_Fill_gstreamermm_callback(GstRingBuffer*, guint8* data, guint len,
                                                 gpointer user_data)
{
  Gst::RingBuffer::SlotFill& slot_fill = *static_cast<Gst::RingBuffer::SlotFill*>(user_data);

  try
  {
    Glib::ArrayHandle<guint8> cpp_data(data, len, Glib::OWNERSHIP_NONE);
    slot_fill(cpp_data, len);
  }
  catch (...)
  {
    Glib::exception_handlers_invoke();
  }
}

} // extern "C"

} // anonymous namespace

namespace Gst
{

RingBufferSpec::RingBufferSpec()
: m_spec(g_try_new(GstRingBufferSpec, 1)),
  take_ownership(true)
{
  // Handle possible memory allocation failure.
  if(!m_spec)
  {
    gstreamermm_handle_error("Failed to allocate a new Gst::RingBufferSpec.");
    return;
  }
}

RingBufferSpec::RingBufferSpec(const Glib::RefPtr<Gst::Caps>& caps,
  Gst::BufferFormatType type, Gst::BufferFormat format, bool sign,
  bool bigend, int width, int depth, int rate, int channels,
  guint64 latency_time, guint64 buffer_time, int segsize, int segtotal,
  int seglatency)
: m_spec(g_try_new(GstRingBufferSpec, 1)),
  take_ownership(true)
  
{
  // Handle possible memory allocation failure.
  if(!m_spec)
  {
    gstreamermm_handle_error("Failed to allocate a new Gst::RingBufferSpec.");
    return;
  }

  GstRingBufferSpec* spec = gobj();

  spec->caps = Glib::unwrap(caps);

  // Keep a copy of the caps (it will be unreferenced in the destructor).
  if (caps)
    caps->reference();

  spec->type = static_cast<GstBufferFormatType>(type);
  spec->format = static_cast<GstBufferFormat>(format);
  spec->sign = static_cast<int>(sign);
  spec->bigend = static_cast<int>(bigend);
  spec->width = width;
  spec->depth = depth;
  spec->rate = rate;
  spec->channels = channels;
  spec->latency_time = latency_time;
  spec->buffer_time = buffer_time;
  spec->segsize = segsize;
  spec->segtotal = segtotal;
  spec->seglatency = seglatency;
}


RingBufferSpec::RingBufferSpec(GstRingBufferSpec& castitem, bool take_ownership)
: m_spec(&castitem),
  take_ownership(take_ownership)
{
  // Keep a copy of the caps (it will be unreferenced in the destructor).
  if(castitem.caps)
      gst_caps_ref(castitem.caps);
}

RingBufferSpec::RingBufferSpec(const RingBufferSpec& other)
: m_spec(g_try_new(GstRingBufferSpec, 1)),
  take_ownership(true)
{
  // Handle possible memory allocation failure.
  if(!m_spec)
  {
    gstreamermm_handle_error("Failed to allocate a new Gst::RingBufferSpec.");
    return;
  }

  m_spec->caps = other.m_spec->caps;

  // Keep a copy of the caps (it will be unreferenced in the destructor).
  if(m_spec->caps)
    gst_caps_ref(m_spec->caps);

  m_spec->type = other.m_spec->type;
  m_spec->format = other.m_spec->format;
  m_spec->sign = other.m_spec->sign;
  m_spec->bigend = other.m_spec->bigend;
  m_spec->width = other.m_spec->width;
  m_spec->depth = other.m_spec->depth;
  m_spec->rate = other.m_spec->rate;
  m_spec->channels = other.m_spec->channels;
  m_spec->latency_time = other.m_spec->latency_time;
  m_spec->buffer_time = other.m_spec->buffer_time;
  m_spec->segsize = other.m_spec->segsize;
  m_spec->segtotal = other.m_spec->segtotal;
  m_spec->bytes_per_sample = other.m_spec->bytes_per_sample;
  m_spec->seglatency = other.m_spec->seglatency;

  std::copy(other.m_spec->silence_sample, other.m_spec->silence_sample + GSTREAMERMM_RING_BUFFER_SPEC_SILENCE_SAMPLE, m_spec->silence_sample);
}

RingBufferSpec& RingBufferSpec::operator=(const RingBufferSpec& other)
{
  RingBufferSpec temp(other);
  swap(temp);
  return *this;
}

RingBufferSpec::~RingBufferSpec()
{
  // Unref existing reference to caps.
  if(m_spec->caps)
    gst_caps_unref(m_spec->caps);

  // Release the underlying m_spec if it is owned.
  if(take_ownership)
    g_free(m_spec);
}

void RingBufferSpec::swap(RingBufferSpec& other)
{
  GstRingBufferSpec* spec_temp = m_spec;
  m_spec = other.m_spec;
  other.m_spec = spec_temp;

  const bool take_temp = take_ownership;
  take_ownership = other.take_ownership;
  other.take_ownership = take_temp;
}

void RingBufferSpec::set_silence_sample(const Glib::ArrayHandle<guint8>& silence_sample)
{
  std::copy(silence_sample.data(),
    silence_sample.data() + GSTREAMERMM_RING_BUFFER_SPEC_SILENCE_SAMPLE,
    m_spec->silence_sample);
}

void RingBuffer::set_fill_slot(const SlotFill& slot)
{
  // The slot is dynamically allocated because according to the
  // gst_ring_buffer_set_callback() docs, the slot may be called several times.
  // A copy is hence created to avoid losing the slot.  The copy is kept in an
  // auto_ptr<> so that is released upon the ring buffer's destruction.
  m_slot.reset(new SlotFill(slot));

  gst_ring_buffer_set_callback(gobj(), &RingBuffer_Fill_gstreamermm_callback,
    m_slot.get());
}

bool RingBuffer::prepare_read(int& segment, std::vector<guint8>& readptr,
  int& len)
{
  guint8* c_readptr = 0;

  const bool result = static_cast<bool>(gst_ring_buffer_prepare_read(gobj(), &segment, &c_readptr, &len));
  readptr.assign(c_readptr, c_readptr + len);

  if (c_readptr)
    g_free(c_readptr);

  return result;
}

gboolean RingBuffer_Class::acquire_vfunc_callback(GstRingBuffer* self, GstRingBufferSpec* spec)
{
  Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
      Glib::ObjectBase::_get_current_wrapper((GObject*)self));

  // Non-gtkmmproc-generated custom classes implicitly call the default
  // Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
  // generated classes can use this optimisation, which avoids the unnecessary
  // parameter conversions if there is no possibility of the virtual function
  // being overridden:
  if(obj_base && obj_base->is_derived_())
  {
    CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
    if(obj) // This can be NULL during destruction.
    {
      try // Trap C++ exceptions which would normally be lost because this is a C callback.
      {
        Gst::RingBufferSpec cpp_spec(*spec);

        // Call the virtual member method, which derived classes might override.
        return static_cast<int>(obj->acquire_vfunc(cpp_spec));

      }
      catch(...)
      {
        Glib::exception_handlers_invoke();
      }
    }
  }
  
  BaseClassType *const base = static_cast<BaseClassType*>(
      g_type_class_peek_parent(G_OBJECT_GET_CLASS(self)) // Get the parent class of the object class (The original underlying C class).
  );

  // Call the original underlying C function:
  if(base && base->acquire)
    return (*base->acquire)(self, spec);


  typedef gboolean RType;
  return RType();
}
bool Gst::RingBuffer::acquire_vfunc(Gst::RingBufferSpec& spec) 
{
  BaseClassType *const base = static_cast<BaseClassType*>(
      g_type_class_peek_parent(G_OBJECT_GET_CLASS(gobject_)) // Get the parent class of the object class (The original underlying C class).
  );

  if(base && base->acquire)
    return static_cast<bool>((*base->acquire)(gobj(), spec.gobj()));

  typedef bool RType;
  return RType();
}
guint RingBuffer_Class::commit_vfunc_callback(GstRingBuffer* self, guint64* sample, guchar* data, gint in_samples, gint out_samples, gint* accum)
{
  Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
      Glib::ObjectBase::_get_current_wrapper((GObject*)self));

  // Non-gtkmmproc-generated custom classes implicitly call the default
  // Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
  // generated classes can use this optimisation, which avoids the unnecessary
  // parameter conversions if there is no possibility of the virtual function
  // being overridden:
  if(obj_base && obj_base->is_derived_())
  {
    CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
    if(obj) // This can be NULL during destruction.
    {
      try // Trap C++ exceptions which would normally be lost because this is a C callback.
      {
        // This formula is obtained from the definition of the data_end
        // variable in the default_commit() function of the C API
        // gstringbuffer.c file.
        size_t data_length = (self->spec.bytes_per_sample * in_samples);

        // Declare the ArrayHandle for the C++ vfunc.
        Glib::ArrayHandle<guchar> cpp_data(data, data_length, Glib::OWNERSHIP_NONE);
        // Call the virtual member method, which derived classes might override.
        return obj->commit_vfunc(*(sample), cpp_data, in_samples, out_samples,
          *(accum));
      }
      catch(...)
      {
        Glib::exception_handlers_invoke();
      }
    }
  }
  
  BaseClassType *const base = static_cast<BaseClassType*>(
      g_type_class_peek_parent(G_OBJECT_GET_CLASS(self)) // Get the parent class of the object class (The original underlying C class).
  );

  // Call the original underlying C function:
  if(base && base->commit)
    return (*base->commit)(self, sample, data, in_samples, out_samples, accum);


  typedef guint RType;
  return RType();
}
guint Gst::RingBuffer::commit_vfunc(guint64& sample, const Glib::ArrayHandle<guchar>& data, int in_samples, int out_samples, int& accum) 
{
  BaseClassType *const base = static_cast<BaseClassType*>(
      g_type_class_peek_parent(G_OBJECT_GET_CLASS(gobject_)) // Get the parent class of the object class (The original underlying C class).
  );

  if(base && base->commit)
    return (*base->commit)(gobj(),&sample,const_cast<guchar*>(data.data()),in_samples,out_samples,&accum);

  typedef guint RType;
  return RType();
}

} // namespace Gst
