/* gstreamermm - a C++ wrapper for gstreamer
 *
 * Copyright 2008 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 <stdexcept>
#include <gst/gst.h>

_PINCLUDE(gstreamermm/private/miniobject_p.h)

namespace Gst
{

Glib::RefPtr<Gst::Buffer> Buffer::copy() const
{
  return Glib::wrap(gst_buffer_copy(gobj()), true);
}

Glib::RefPtr<Gst::Buffer> Buffer::create_writable()
{
  /*
   * This function is generally used in the following pattern:
   * RefPtr<Buffer> p = (...);
   * p = p->create_writable();
   *
   * There are two cases:
   * 1. object is not writable, therefore:
   *   - somebody else may have another reference to the object (but it this might change in the meantime)
   *   - gst_buffer_make_writable may return a new copy of object
   *   - we have to make additional ref, that will be unreffed in gst_buffer_make_writable
   * 2. object is_writable, then:
   *   - our caller has the only one reference to object (therefore nobody can increase refcount in the meantime)
   *   - gst_buffer_make_writable will return the same object and will not do any reffing/unreffing
   *   - we cannot make any additional refs before calling gst_buffer_make_writable, since it would enforce unnecessary
   *     copying of the object
   *   - we are supposed to create a new RefPtr with is own reference to the object, therefore we need to "take copy"
   *   - however when caller release the pointer (implicitly, during assignment) the refcount will be 1 again
   */
  if(is_writable())
  {
    return Glib::wrap(gst_buffer_make_writable(gobj()), true); // take copy so original object is left to the current owner (and hopefully will be released soon)
  }
  else
  {
    reference(); // gst_buffer_make_writable(buf) will unref the old buffer, but our caller is still holding RefPtr to it
    return Glib::wrap(gst_buffer_make_writable(gobj()));
  }
}

Glib::RefPtr<Gst::Buffer> Buffer::create(guint size)
{
  return Glib::wrap(gst_buffer_new_allocate(NULL, size, NULL));
}

} // namespace Gst
