/*
 * This file is part of libsidplayfp, a SID player engine.
 *
 * Copyright 2011-2019 Leandro Nini <drfiemost@users.sourceforge.net>
 * Copyright 2007-2010 Antti Lankila
 * Copyright 2001 Simon White
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "residfp-emu.h"

#include <cmath>

#include "residfp/residfp.h"
#include "sidplayfp/siddefs.h"

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#define xstr(s) str(s)
#define str(s) #s

#define _VERSION(a,b,c) a ##.## b ##.## c
#define SID_VERSION(a,b,c) _VERSION(a,b,c)
#define LIBRESIDFP_VERSION \
    SID_VERSION(LIBRESIDFP_VERSION_MAJ, \
        LIBRESIDFP_VERSION_MIN, \
        LIBRESIDFP_VERSION_LEV)

namespace libsidplayfp
{

const char ERR_INVALID_CW[]     = "Invalid combined waveforms strength.";

const char* reSIDfpEmu::getCredits()
{
    return
        "reSIDfpEmu V" VERSION " Engine:\n"
        "\t(C) 1999-2002 Simon White\n"
        "libresidfp V" xstr(LIBRESIDFP_VERSION) ":\n"
        "\t(C) 1999-2002 Dag Lem\n"
        "\t(C) 2005-2011 Antti S. Lankila\n"
        "\t(C) 2010-2026 Leandro Nini\n";
}

reSIDfpEmu::reSIDfpEmu(sidbuilder *builder) :
    sidemu(builder),
    m_sid(*(new reSIDfp::residfp))
{
    reset(0);
}

reSIDfpEmu::~reSIDfpEmu()
{
    delete &m_sid;
    delete[] m_buffer;
}

// Standard component options
void reSIDfpEmu::reset(uint8_t volume)
{
    m_accessClk = 0;
    m_sid.reset();
    m_sid.write(0x18, volume);
}

uint8_t reSIDfpEmu::read(uint_least8_t addr)
{
    clock();
    return m_sid.read(addr);
}

void reSIDfpEmu::write(uint_least8_t addr, uint8_t data)
{
    clock();
    m_sid.write(addr, data);
}

void reSIDfpEmu::clock()
{
    const event_clock_t cycles = eventScheduler->getTime(EVENT_CLOCK_PHI1) - m_accessClk;
    m_accessClk += cycles;
    m_bufferpos += m_sid.clock(cycles, m_buffer+(m_bufferpos<<2));
}

void reSIDfpEmu::sampling(float systemclock, float freq,
        SidConfig::sampling_method_t method)
{
    reSIDfp::SamplingMethod sampleMethod;
    switch (method)
    {
    case SidConfig::INTERPOLATE:
        sampleMethod = reSIDfp::DECIMATE;
        break;
    case SidConfig::RESAMPLE_INTERPOLATE:
        sampleMethod = reSIDfp::RESAMPLE;
        break;
    default:
        m_status = false;
        m_error = ERR_INVALID_SAMPLING;
        return;
    }

    bool res = m_sid.setSamplingParameters(systemclock, sampleMethod, freq);
    if  (!res)
    {
        m_status = false;
        m_error = ERR_UNSUPPORTED_FREQ;
        return;
    }

    if (m_buffer)
        delete[] m_buffer;

    // 20ms buffer
    const int buffersize = std::ceil((freq / 1000.f) * 20.f);
    m_buffer = new short[buffersize*4];
    m_status = true;
}

// Set the emulated SID model
void reSIDfpEmu::model(SidConfig::sid_model_t model, bool digiboost)
{
    reSIDfp::ChipModel chipModel;
    switch (model)
    {
        case SidConfig::MOS6581:
            chipModel = reSIDfp::MOS6581;
            m_sid.input(0);
            break;
        case SidConfig::MOS8580:
            chipModel = reSIDfp::CSG8580;
            m_sid.input(digiboost ? -32768 : 0);
            break;
        default:
            m_status = false;
            m_error = ERR_INVALID_CHIP;
            return;
    }

    m_sid.setChipModel(chipModel);
    m_status = true;
}

// Set the emulated SID combined waveforms
void reSIDfpEmu::combinedWaveforms(SidConfig::sid_cw_t cws)
{
    reSIDfp::CombinedWaveforms combinedWaveforms;
    switch (cws)
    {
        case SidConfig::AVERAGE:
            combinedWaveforms = reSIDfp::AVERAGE;
            break;
        case SidConfig::WEAK:
            combinedWaveforms = reSIDfp::WEAK;
            break;
        case SidConfig::STRONG:
            combinedWaveforms = reSIDfp::STRONG;
            break;
        default:
            m_status = false;
            m_error = ERR_INVALID_CW;
            return;
    }

    m_sid.setCombinedWaveforms(combinedWaveforms);
    m_status = true;
}

void reSIDfpEmu::GetVolumes(uint8_t &a, uint8_t &b, uint8_t &c) const
{
   float _a = 0.0f;
   float _b = 0.0f;
   float _c = 0.0f;

   m_sid.volumes (_a, _b, _c);

   _a *= 0x8000;
   _b *= 0x8000;
   _c *= 0x8000;

   if (_a < 0.0) a = 0; else if (_a > 255.0) a = 255; else a = _a;
   if (_b < 0.0) b = 0; else if (_b > 255.0) b = 255; else b = _b;
   if (_c < 0.0) c = 0; else if (_c > 255.0) c = 255; else c = _c;
}

}
