/* GStreamer APEv1/2 tag reader
 * Copyright (C) 2004 Ronald Bultje <rbultje@ronald.bitfreak.net>
 * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
 *
 * 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.
 */

/**
 * SECTION:element-apedemux
 * @short_description: reads tag information from APE tag data blocks and
 * outputs them as GStreamer tag messages and events.
 *
 * <refsect2>
 * <para>
 * apedemux accepts data streams with APE tags at the start or at the end
 * (or both). The mime type of the data between the tag blocks is detected
 * using typefind functions, and the appropriate output mime type set on
 * outgoing buffers. 
 * </para>
 * <para>
 * The element is only able to read APE tags at the end of a stream from
 * a seekable stream, ie. when get_range mode is supported by the upstream
 * elements. If get_range operation is available, apedemux makes it available
 * downstream. This means that elements which require get_range mode, such as
 * wavparse or musepackdec, can operate on files containing APE tag
 * information.
 * </para>
 * <title>Example launch line</title>
 * <para>
 * <programlisting>
 * gst-launch -t filesrc location=file.mpc ! apedemux ! fakesink
 * </programlisting>
 * This pipeline should read any available APE tag information and output it.
 * The contents of the file inside the APE tag regions should be detected, and
 * the appropriate mime type set on buffers produced from apedemux.
 * </para>
 * </refsect2>
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gst/gst.h>
#include <gst/gst-i18n-plugin.h>

#include "gstapedemux.h"

#include <string.h>

#define APE_VERSION_MAJOR(ver)  ((ver)/1000)

GST_DEBUG_CATEGORY (apedemux_debug);
#define GST_CAT_DEFAULT (apedemux_debug)

static GstElementDetails gst_ape_demux_details =
GST_ELEMENT_DETAILS ("APE tag demuxer",
    "Codec/Demuxer/Metadata",
    "Read and output APE tags while demuxing the contents",
    "Ronald Bultje <rbultje@ronald.bitfreak.net>, "
    "Tim-Philipp Müller <tim centricular net>");

static gboolean gst_ape_demux_identify_tag (GstTagDemux * demux,
    GstBuffer * buffer, gboolean start_tag, guint * tag_size);
static GstTagDemuxResult gst_ape_demux_parse_tag (GstTagDemux * demux,
    GstBuffer * buffer, gboolean start_tag, guint * tag_size,
    GstTagList ** tags);
static GstCaps *gst_ape_demux_get_sink_caps (GstTagDemux * demux);

GST_BOILERPLATE(GstApeDemux,gst_ape_demux,GstTagDemux,GST_TYPE_TAG_DEMUX)

static void
gst_ape_demux_base_init (gpointer klass)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gst_element_class_set_details (element_class, &gst_ape_demux_details);

  GST_DEBUG_CATEGORY_INIT (apedemux_debug, "apedemux", 0,
      "GStreamer APE tag demuxer");
}

static void
gst_ape_demux_class_init (GstApeDemuxClass * klass)
{
  GstTagDemuxClass *tagdemux_class;

  tagdemux_class = GST_TAG_DEMUX_CLASS (klass);

  tagdemux_class->identify_tag =
      GST_DEBUG_FUNCPTR (gst_ape_demux_identify_tag);
  tagdemux_class->parse_tag =
      GST_DEBUG_FUNCPTR (gst_ape_demux_parse_tag);
  tagdemux_class->get_sink_caps =
      GST_DEBUG_FUNCPTR (gst_ape_demux_get_sink_caps);
}

static void
gst_ape_demux_init (GstApeDemux * apedemux, GstApeDemuxClass * gclass)
{
  GstTagDemux *tagdemux = GST_TAG_DEMUX (apedemux);

  tagdemux->min_start_size = 32;
  tagdemux->min_end_size = 32;

  tagdemux->prefer_start_tag = TRUE;
}

static GstTagList *
ape_demux_parse_tags (const guint8 * data, gint size)
{
  GstTagList *taglist = gst_tag_list_new ();
  gboolean have_tag = FALSE;

  GST_LOG ("Reading tags from chunk of size %u bytes", size);

  /* get rid of header/footer */
  if (!memcmp (data, "APETAGEX", 8)) {
    data += 32;
    size -= 32;
  }
  if (!memcmp (data + size - 32, "APETAGEX", 8)) {
    size -= 32;
  }

  /* read actual tags - at least 10 bytes for tag header */
  while (size >= 10) {
    guint len, n = 8;
    gchar *tag, *val;
    const gchar *type = NULL;
    gboolean i = FALSE;

    /* find tag type and size */
    len = GST_READ_UINT32_LE (data);
    while (n < size && data[n] != 0x0)
      n++;
    if (n == size)
      break;
    g_assert (data[n] == 0x0);
    n++;
    if (size - n < len)
      break;

    /* read */
    tag = g_strndup ((gchar*) data + 8, n - 9);
    val = g_strndup ((gchar*) data + n, len);
    if (!strcasecmp (tag, "title")) {
      type = GST_TAG_TITLE;
    } else if (!strcasecmp (tag, "artist")) {
      type = GST_TAG_ARTIST;
    } else if (!strcasecmp (tag, "album")) {
      type = GST_TAG_ALBUM;
    } else if (!strcasecmp (tag, "comment")) {
      type = GST_TAG_COMMENT;
    } else if (!strcasecmp (tag, "copyright")) {
      type = GST_TAG_COPYRIGHT;
    } else if (!strcasecmp (tag, "genre")) {
      type = GST_TAG_GENRE;
    } else if (!strcasecmp (tag, "isrc")) {
      type = GST_TAG_ISRC;
    } else if (!strcasecmp (tag, "track")) {
      type = GST_TAG_TRACK_NUMBER;
      i = TRUE;
    }
    if (type) {
      GValue v = { 0 };

      if (i) {
        g_value_init (&v, G_TYPE_INT);
        g_value_set_int (&v, atoi (val));
      } else {
        g_value_init (&v, G_TYPE_STRING);
        g_value_set_string (&v, val);
      }
      gst_tag_list_add_values (taglist, GST_TAG_MERGE_APPEND, type, &v, NULL);
      g_value_unset (&v);
      have_tag = TRUE;
    }
    GST_DEBUG ("Read tag %s: %s", tag, val);
    g_free (tag);
    g_free (val);

    /* move data pointer */
    size -= len + n;
    data += len + n;
  }

  return taglist;
}

static gboolean
gst_ape_demux_identify_tag (GstTagDemux * demux, GstBuffer * buffer,
    gboolean start_tag, guint * tag_size)
{
  if (memcmp (GST_BUFFER_DATA (buffer), "APETAGEX", 8) != 0) {
    GST_DEBUG_OBJECT (demux, "No APETAGEX marker at %s - not an APE file",
        (start_tag) ? "start" : "end");
    return FALSE;
  }

  *tag_size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buffer) + 12);

  /* size is without header, so add 32 to account for that */
  *tag_size += 32;

  return TRUE;
}

static GstTagDemuxResult
gst_ape_demux_parse_tag (GstTagDemux * demux, GstBuffer * buffer,
    gboolean start_tag, guint * tag_size, GstTagList ** tags)
{
  const guint8 *data;
  const guint8 *footer;
  gboolean have_header;
  guint version;

  data = GST_BUFFER_DATA (buffer);
  footer = GST_BUFFER_DATA (buffer) + GST_BUFFER_SIZE (buffer) - 32;

  if (memcmp (footer, "APETAGEX", 8) != 0) {
    GST_DEBUG_OBJECT (demux, "Tag at %s of file without footer!",
        (start_tag) ? "beginning" : "end");
    return GST_TAG_DEMUX_RESULT_BROKEN_TAG;
  }

  /* don't trust the header/footer flags, better detect them ourselves */
  have_header = (memcmp (data, "APETAGEX", 8) == 0);

  if (start_tag && !have_header) {
    GST_DEBUG_OBJECT (demux, "Tag at beginning of file without header!");
    return GST_TAG_DEMUX_RESULT_BROKEN_TAG;
  }

  if (!start_tag && !have_header) {
    GST_DEBUG_OBJECT (demux, "Tag at end of file has no header (APEv1)");
    *tag_size -= 32; /* adjust tag size */
  }

  if (have_header) {
    version = GST_READ_UINT32_LE (data + 8);
  } else {
    version = GST_READ_UINT32_LE (footer + 8);
  }

  /* skip header */
  if (have_header) {
    data += 32;
  }

  GST_DEBUG_OBJECT (demux, "APE tag with version %u, size %u at offset 0x%08"
      G_GINT64_MODIFIER "x", version, *tag_size,
      GST_BUFFER_OFFSET (buffer) + ((have_header) ? 0 : 32));

  if (APE_VERSION_MAJOR (version) != 1 && APE_VERSION_MAJOR (version) != 2) {
    GST_WARNING ("APE tag is version %u.%03u, but decoder only supports "
        "v1 or v2. Ignoring.", APE_VERSION_MAJOR (version), version % 1000);
    return GST_TAG_DEMUX_RESULT_OK;
  }

  *tags = ape_demux_parse_tags (data, *tag_size - 32); /* minus footer */

  return GST_TAG_DEMUX_RESULT_OK;
}

static GstCaps *
gst_ape_demux_get_sink_caps (GstTagDemux * demux)
{
  return gst_caps_from_string ("application/x-apetag");
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  return gst_element_register (plugin, "apedemux",
      GST_RANK_PRIMARY, GST_TYPE_APE_DEMUX);
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "apetag",
    "APEv1/2 tag reader",
    plugin_init, VERSION, "LGPL", GST_PACKAGE, GST_ORIGIN)
