/*
Copyright (c) 2021-2025 Rupert Carmichael
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef SN76496_H
#define SN76496_H

#define NSHIFT 15 // Linear Feedback Shift Register is 16 bits, so shift 15
#define NSHIFT_SG 14 // Linear Feedback Shift Register is 15 bits, so shift 14
#define NTAP 0x0009 // Tapped bits for SMS and later are 0 and 3
#define NTAP_SG 0x0003 // Tapped bits for SG-1000 are 0 and 1

typedef struct _sn76496_t {
    // Chip State
    uint8_t clatch; // Channel latch tells which channel's registers to write
    uint8_t attenuator[4]; // Four attenuators control volume on four channels
    uint16_t frequency[3]; // Three frequency registers for Tone Generators
    uint8_t noise; // One register for the Noise Generator
    uint16_t lfsr; // Linear Feedback Shift Register, 15/16 bits (SG-1000/SMS)
    uint16_t counter[4]; // Period Counter
    int16_t output[4]; // Per-channel output volumes for mixing
    uint8_t freqff; // Four bits for four channels, 0 = Positive, 1 = Negative
    uint8_t stctrl; // Stereo Control bits

    // Variables unrelated to the Chip State, set from outside
    int16_t *buf; // Buffer for raw audio samples
    size_t bufpos; // Current write position in buffer
    unsigned stereo;
    uint16_t shift;
    uint16_t tap;
} sn76496_t;

void sn76496_init(sn76496_t* const, unsigned, uint16_t, uint16_t);
void sn76496_wr(sn76496_t* const, uint8_t);
void sn76496_wr_stereo(sn76496_t* const, uint8_t);
void sn76496_exec(sn76496_t* const);

#endif
