/*
 * --- GSMP-COPYRIGHT-NOTE-BEGIN ---
 * 
 * This copyright note is auto-generated by ./scripts/Create-CopyPatch.
 * Please add additional copyright information _after_ the line containing
 * the GSMP-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
 * the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
 * 
 * GSMP: pcm/src/MP3Stream.cc
 * General Sound Manipulation Program is Copyright (C) 2000 - 2004
 *   Valentin Ziegler and René Rebe
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2. A copy of the GNU General
 * Public License can be found in the file LICENSE.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
 * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * --- GSMP-COPYRIGHT-NOTE-END ---
 */

#include <iostream>
#include "Logging.hh"

#include "MP3Stream.hh"

using namespace GSMP;

GSMP::Logger <DefaultLogging_MP3> GSMP::MP3Log;

/*****************
 * MP3FileStream *
 *****************/

MP3FileStream::MP3FileStream ()
{
  m_open = false;
  m_stream_pos = 0;
}

MP3FileStream::~MP3FileStream ()
{
  if (m_open)
    m_mad.Close ();
}
    
bool MP3FileStream::Open (const std::string& fname)
{
  if (m_open)
    return false;
  
  m_fname = fname;
  m_open = m_mad.Open (m_fname);
  
  if (m_open) {
    m_channels = m_mad.Channels ();
    m_rate = m_mad.Rate ();
    m_size = m_mad.Size ();
  }
  
  return m_open;
}

bool MP3FileStream::IsOpen ()
{
  return m_open;
}

bool MP3FileStream::Close ()
{
  if (!m_open)
    return false;
  
  bool t_ret = m_mad.Close ();
  m_open = false;
  return t_ret;
}

global_index MP3FileStream::Size ()
{
  if (IsOpen () )
    return m_size;
  else {
    Q_LOG(MP3Log)
	     << " unknown if not opened!" << std::endl;
    return 0;
  }
}

channel_index MP3FileStream::Channels ()
{
  if (IsOpen () )
    return m_channels;
  else {
    Q_LOG(MP3Log)
	     << " unknown if not opened!" << std::endl;
    return 0;
  }
}

sample_rate MP3FileStream::Rate ()
{
  if (IsOpen () )
    return m_rate;
  else {
    Q_LOG(MP3Log)
	     << " unknown if not opened!" << std::endl;
    return 0;
  }
}
    
local_index MP3FileStream::Read (local_index size, BasicStream* dest)
{  
  // the MADHelper now outputs our 24 bit format non-interleaved
  // so it can perform the clipping and dithering, and we do not
  // need to de-interleave
  
  mad_fixed_t* buffer [2];
  buffer [0] = (*dest) [0]->data;
  buffer [1] = (*dest) [1]->data;
  
  m_mad.Read (size, buffer);
  
  dest->SetUsedSize (size);
  
  m_stream_pos += size;
  return size;
}

global_index MP3FileStream::Seek (global_index pos)
{
  if (pos != m_stream_pos)
    {
      m_mad.Seek (pos);
      m_stream_pos = pos;
    }
  
  return m_stream_pos;
}
