/*
 * 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: mp3decoder.h 3219 2006-04-16 15:06:35Z svntobi $
 *
 */

#ifndef ___MP3DECODER_H
#define ___MP3DECODER_H

#include <iostream>
#include "mad.h"
#include "pcmdatasource.h"
#include "madresampler.h"
#include "mp3info.h"
#include "refptr.h"

using namespace std;

class Mp3Decoder: public IPcmDataSource
{
    static const int readBufferSize = 4096;

    private:
        ref_ptr<std::istream> mp3Stream;
        struct mad_stream madStream;
        struct mad_frame madFrame;
        struct mad_synth madSynth;
        unsigned int sampleRate;
        unsigned char readBuffer[readBufferSize];
        MadResampler resampler;
        int sampleCount;
        mad_fixed_t* leftBuffer;
        mad_fixed_t* rightBuffer;
        mad_fixed_t* leftBufferReadPtr;
        mad_fixed_t* rightBufferReadPtr;
        int samplesInBuffer;
        bool eof;
        mad_timer_t timeIndex;
        Mp3Info mp3Info;

    private:
        signed int ScaleTo16Bit(mad_fixed_t sample);
        int FillReadBuffer();
        void DecodeNextChunk();
        void Resample(mad_pcm& pcm);

    public:
        Mp3Decoder(ref_ptr<std::istream> mp3Stream);
        ~Mp3Decoder();
        unsigned int GetSampleRate();
        void FillPesAudioPacket(PesAudioPacket& packet);
        bool Eof();
};

#endif
