/*
 * 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: mpaframereader.cc 3211 2006-04-14 21:01:37Z svntobi $
 *
 */

#include "mpaframereader.h"

using namespace std;

ref_ptr<MpaFrameHeader> MpaFrameReader::SeekNextFrame(istream& stream)
{
    while (SeekNextFrameSync(stream))
    {
        if (CheckForConsecutiveFrames(stream, 2))
        {
            return ReadHeader(stream);
        }

        stream.seekg(1, ios::cur);
    }

    return ref_ptr<MpaFrameHeader>(NULL);
}

bool MpaFrameReader::SeekNextFrameSync(istream& stream)
{
    do
    {
        if (HasFrameSyncAtCurrentPosition(stream))
        {
            return true;
        }
    }
    while(!stream.seekg(1, ios::cur).eof());

    return false;
}

ref_ptr<MpaFrameHeader>MpaFrameReader::ReadHeader(istream& stream)
{
    MpaHeaderData buffer;

    stream.read((char*)buffer, MPA_HEADER_SIZE);

    return ref_ptr<MpaFrameHeader>(new MpaFrameHeader(buffer));
}

bool MpaFrameReader::CheckForConsecutiveFrames(istream& stream,
  int numberOfFrames)
{
    long int backupPosition = stream.tellg();
    bool consecutiveFramesFound = true;

    for (int frameCount = 0; frameCount < numberOfFrames; frameCount++)
    {
        if (HasFrameSyncAtCurrentPosition(stream))
        {
            ref_ptr<MpaFrameHeader> header = ReadHeader(stream);
            stream.seekg(header->GetFrameSize() - MPA_HEADER_SIZE, ios::cur);
        }
        else
        {
            consecutiveFramesFound = false;
            break;
        }
    }

    stream.seekg(backupPosition, ios::beg);
    return consecutiveFramesFound;
}

bool MpaFrameReader::HasFrameSyncAtCurrentPosition(std::istream& stream)
{
    unsigned char frameSyncBuffer[2];
    bool frameSyncFound = false;
    long int backupPosition = stream.tellg();

    if(!stream.read((char*)frameSyncBuffer, 2).eof())
    {
        if ((frameSyncBuffer[0] == 0xFF) &&
          ((frameSyncBuffer[1] & 0xF0) == 0xF0))
        {
            frameSyncFound = true;
        }
    }

    stream.seekg(backupPosition, ios::beg);
    return frameSyncFound;
}
