/* GStreamer
 *
 * Copyright (C) 2005 Lutz Mueller <lutz@topfrose.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <config.h>

#include "gsttarmux.h"
#include "gsttardemux.h"

#include <gst/gstplugin.h>

#include <string.h>

static GstStaticCaps tar_caps = GST_STATIC_CAPS ("application/x-tar");

#define GST_TAR_CAPS (gst_static_caps_get (&tar_caps))

static void
gst_tar_typefind_function (GstTypeFind * tf, gpointer d)
{
  guint8 *data = NULL;
  guint i, c1, c2;

  /* Magic string */
  data = gst_type_find_peek (tf, 257, 8);
  if (!data)
    return;
  if (!memcmp (data, "ustar  \0", 8)) {
    gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, GST_TAR_CAPS);
    return;
  }

  /* Checksum */
  data = gst_type_find_peek (tf, 0, 512);
  if (!data)
    return;
  for (c1 = i = 0; i < 512; i++)
    c1 += ((i < 148 || i >= 148 + 8) ? data[i] : 32);
  for (c2 = 0, i = 148; (i < 148 + 8) && data[i]; i++)
    c2 = (8 * c2 + data[i] - 48);
  if (c1 == c2) {
    gst_type_find_suggest (tf, GST_TYPE_FIND_LIKELY, GST_TAR_CAPS);
    return;
  }
}

static gboolean
plugin_init (GstPlugin * p)
{
  static gchar *exts[] = { "tar", NULL };

  if (!gst_type_find_register (p, "application/x-tar", GST_RANK_PRIMARY,
          gst_tar_typefind_function, exts, GST_TAR_CAPS, NULL, NULL))
    return FALSE;
  if (!gst_element_register (p, "tarmux", GST_RANK_PRIMARY, GST_TYPE_TAR_MUX) ||
      !gst_element_register (p, "tardemux", GST_RANK_PRIMARY,
        GST_TYPE_TAR_DEMUX))
    return FALSE;
  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR, "tar",
    "Mux and demuxe streams in TAR format",
    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
