/*
 * vdr-podcatcher - A plugin for the Linux Video Disk Recorder
 * Copyright (c) 2006 Tobias Grimm <vdr@e-tobi.net>
 *
 * 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: mp3info.cc 3212 2006-04-14 23:30:32Z svntobi $
 *
 */

#include "mp3info.h"
#include "mpaframereader.h"

using namespace std;

Mp3Info::Mp3Info()
:totalTime(0)
{
}

int Mp3Info::GetTotalTime()
{
    return totalTime;
}

void Mp3Info::ReadFromStream(istream& mp3Stream)
{
    MpaFrameReader reader;

    ref_ptr<MpaFrameHeader> header = reader.SeekNextFrame(mp3Stream);

    if (header.get())
    {
        mp3Stream.seekg(header->GetSideInformationSize(), ios::cur);

        string vbrHeaderId = ReadVbrHeaderId(mp3Stream);

        if ((vbrHeaderId == "Xing") | (vbrHeaderId == "Info"))
        {
            mp3Stream.seekg(4, ios::cur);

            int numberOfFrames = Read32BitBigEndian(mp3Stream);
            int numberOfSamples = numberOfFrames * 1152;

            totalTime = (int) (0.5 + numberOfSamples /
              header->GetSamplingRate());
        }
        else
        {
            int byteRate = header->GetBitRate() / 8;
            if (byteRate > 0)
            {
                totalTime = (int) (0.5 + GetBytesLeftInStream(mp3Stream) /
                  byteRate);
            }
        }
    }

    mp3Stream.seekg(0, ios::beg);
}

int Mp3Info::GetBytesLeftInStream(istream& stream)
{
    int currentPosition = stream.tellg();
    int endOfStream = stream.seekg(0, ios::end).tellg();

    stream.seekg(currentPosition, ios::beg);

    return endOfStream - currentPosition;
}

string Mp3Info::ReadVbrHeaderId(std::istream& mp3Stream)
{
    char buffer[5];

    mp3Stream.read(buffer, 4);
    buffer[4] = 0;

    return buffer;
}

unsigned int Mp3Info::Read32BitBigEndian(std::istream& mp3Stream)
{
    unsigned char buffer[4];
    mp3Stream.read((char*)buffer, 4);

    unsigned int value = 0;

    for (int i=0; i < 4; i++)
    {
        value = value << 8;
        value = value + buffer[i];
    }

    return value;
}
