Update to bsnes v045r09 release.

[No changelog available]
This commit is contained in:
byuu 2009-04-30 20:58:39 +00:00
parent 5f96547beb
commit 3c42e6caa0
333 changed files with 34968 additions and 5315 deletions

View File

@ -93,9 +93,9 @@ link += $(if $(findstring input.rawinput,$(ruby)),$(call mklib,xinput) $(call mk
####################
objects = libco ruby libfilter string \
reader cart cheat \
memory smemory cpu cpucore scpu smp ssmp sdsp ppu bppu snes \
sa1 bsx srtc sdd1 spc7110 cx4 dsp1 dsp2 dsp3 dsp4 obc1 st010
reader cartridge cheat \
memory smemory cpu cpucore scpu smp smpcore ssmp sdsp ppu bppu system \
sgb sa1 bsx srtc sdd1 spc7110 cx4 dsp1 dsp2 dsp3 dsp4 obc1 st010
ifeq ($(enable_gzip),true)
objects += adler32 compress crc32 deflate gzio inffast inflate inftrees ioapi trees unzip zip zutil
@ -107,6 +107,13 @@ ifeq ($(enable_jma),true)
flags += $(call mkdef,JMA_SUPPORT)
endif
sgbflags =
ifeq ($(sgb),gambatte)
sgbflags += $(call mkdef,SGB_GAMBATTE)
link += $(call mklibpath,lib/libgambatte)
link += $(call mklib,gambatte)
endif
######################
### implicit rules ###
######################
@ -139,14 +146,14 @@ obj/libco.$(obj): lib/libco/libco.c lib/libco/*
$(c) $(libcoflags) $(rule)
obj/libfilter.$(obj): lib/libfilter/libfilter.cpp lib/libfilter/*
obj/string.$(obj): lib/nall/string.cpp lib/nall/*
obj/reader.$(obj): lib/reader/reader.cpp lib/reader/*
#################
### utilities ###
#################
obj/reader.$(obj): reader/reader.cpp reader/*
obj/cart.$(obj) : cart/cart.cpp cart/*
obj/cheat.$(obj) : cheat/cheat.cpp cheat/*
obj/cartridge.$(obj): cartridge/cartridge.cpp cartridge/*
obj/cheat.$(obj) : cheat/cheat.cpp cheat/*
##############
### memory ###
@ -167,8 +174,9 @@ obj/scpu.$(obj) : cpu/scpu/scpu.cpp cpu/scpu/* cpu/scpu/dma/* cpu/scpu/memory/
### smp ###
###########
obj/smp.$(obj) : smp/smp.cpp smp/*
obj/ssmp.$(obj): smp/ssmp/ssmp.cpp smp/ssmp/* smp/ssmp/core/* smp/ssmp/memory/* smp/ssmp/timing/*
obj/smp.$(obj) : smp/smp.cpp smp/*
obj/smpcore.$(obj): smp/core/core.cpp smp/core/* smp/core/disasm/*
obj/ssmp.$(obj) : smp/ssmp/ssmp.cpp smp/ssmp/* smp/ssmp/memory/* smp/ssmp/timing/*
###########
### dsp ###
@ -184,16 +192,18 @@ obj/sdsp.$(obj): dsp/sdsp/sdsp.cpp dsp/sdsp/*
obj/ppu.$(obj) : ppu/ppu.cpp ppu/*
obj/bppu.$(obj): ppu/bppu/bppu.cpp ppu/bppu/*
############
### snes ###
############
##############
### system ###
##############
obj/snes.$(obj): snes/snes.cpp snes/* snes/scheduler/* snes/video/* snes/audio/* snes/input/*
obj/system.$(obj): system/system.cpp system/* system/scheduler/* system/video/* system/audio/* system/input/*
#####################
### special chips ###
#####################
obj/sgb.$(obj): chip/sgb/sgb.cpp chip/sgb/* chip/sgb/interface/*
$(call compile,$(sgbflags))
obj/sa1.$(obj) : chip/sa1/sa1.cpp chip/sa1/* chip/sa1/bus/* chip/sa1/dma/* chip/sa1/memory/* chip/sa1/mmio/*
obj/bsx.$(obj) : chip/bsx/bsx.cpp chip/bsx/*
obj/srtc.$(obj) : chip/srtc/srtc.cpp chip/srtc/*
@ -211,32 +221,32 @@ obj/st010.$(obj) : chip/st010/st010.cpp chip/st010/*
### zlib ###
############
obj/adler32.$(obj) : reader/zlib/adler32.c reader/zlib/*
obj/compress.$(obj): reader/zlib/compress.c reader/zlib/*
obj/crc32.$(obj) : reader/zlib/crc32.c reader/zlib/*
obj/deflate.$(obj) : reader/zlib/deflate.c reader/zlib/*
obj/gzio.$(obj) : reader/zlib/gzio.c reader/zlib/*
obj/inffast.$(obj) : reader/zlib/inffast.c reader/zlib/*
obj/inflate.$(obj) : reader/zlib/inflate.c reader/zlib/*
obj/inftrees.$(obj): reader/zlib/inftrees.c reader/zlib/*
obj/ioapi.$(obj) : reader/zlib/ioapi.c reader/zlib/*
obj/trees.$(obj) : reader/zlib/trees.c reader/zlib/*
obj/unzip.$(obj) : reader/zlib/unzip.c reader/zlib/*
obj/zip.$(obj) : reader/zlib/zip.c reader/zlib/*
obj/zutil.$(obj) : reader/zlib/zutil.c reader/zlib/*
obj/adler32.$(obj) : lib/zlib/adler32.c lib/zlib/*
obj/compress.$(obj): lib/zlib/compress.c lib/zlib/*
obj/crc32.$(obj) : lib/zlib/crc32.c lib/zlib/*
obj/deflate.$(obj) : lib/zlib/deflate.c lib/zlib/*
obj/gzio.$(obj) : lib/zlib/gzio.c lib/zlib/*
obj/inffast.$(obj) : lib/zlib/inffast.c lib/zlib/*
obj/inflate.$(obj) : lib/zlib/inflate.c lib/zlib/*
obj/inftrees.$(obj): lib/zlib/inftrees.c lib/zlib/*
obj/ioapi.$(obj) : lib/zlib/ioapi.c lib/zlib/*
obj/trees.$(obj) : lib/zlib/trees.c lib/zlib/*
obj/unzip.$(obj) : lib/zlib/unzip.c lib/zlib/*
obj/zip.$(obj) : lib/zlib/zip.c lib/zlib/*
obj/zutil.$(obj) : lib/zlib/zutil.c lib/zlib/*
###########
### jma ###
###########
##############
### libjma ###
##############
obj/jma.$(obj) : reader/jma/jma.cpp reader/jma/*
obj/jcrc32.$(obj) : reader/jma/jcrc32.cpp reader/jma/*
obj/lzmadec.$(obj): reader/jma/lzmadec.cpp reader/jma/*
obj/7zlzma.$(obj) : reader/jma/7zlzma.cpp reader/jma/*
obj/iiostrm.$(obj): reader/jma/iiostrm.cpp reader/jma/*
obj/inbyte.$(obj) : reader/jma/inbyte.cpp reader/jma/*
obj/lzma.$(obj) : reader/jma/lzma.cpp reader/jma/*
obj/winout.$(obj) : reader/jma/winout.cpp reader/jma/*
obj/jma.$(obj) : lib/libjma/jma.cpp lib/libjma/*
obj/jcrc32.$(obj) : lib/libjma/jcrc32.cpp lib/libjma/*
obj/lzmadec.$(obj): lib/libjma/lzmadec.cpp lib/libjma/*
obj/7zlzma.$(obj) : lib/libjma/7zlzma.cpp lib/libjma/*
obj/iiostrm.$(obj): lib/libjma/iiostrm.cpp lib/libjma/*
obj/inbyte.$(obj) : lib/libjma/inbyte.cpp lib/libjma/*
obj/lzma.$(obj) : lib/libjma/lzma.cpp lib/libjma/*
obj/winout.$(obj) : lib/libjma/winout.cpp lib/libjma/*
###############
### targets ###

View File

@ -1,4 +1,4 @@
#define BSNES_VERSION "0.045"
#define BSNES_VERSION "0.045.09"
#define BSNES_TITLE "bsnes v" BSNES_VERSION
#define BUSCORE sBus

View File

@ -1,234 +0,0 @@
#include <../base.hpp>
#include <../chip/chip.hpp>
#include <../reader/reader.hpp>
#define CART_CPP
#include <nall/crc32.hpp>
#include <nall/ups.hpp>
#include "cart.hpp"
#include "cart_file.cpp"
#include "cart_header.cpp"
#include "cart_loader.cpp"
namespace memory {
MappedRAM cartrom, cartram, cartrtc;
MappedRAM bscram;
MappedRAM stArom, stAram;
MappedRAM stBrom, stBram;
};
Cartridge cartridge;
void Cartridge::load_begin(Mode cartridge_mode) {
cart.rom = cart.ram = cart.rtc = 0;
bs.ram = 0;
stA.rom = stA.ram = 0;
stB.rom = stB.ram = 0;
cart.rom_size = cart.ram_size = cart.rtc_size = 0;
bs.ram_size = 0;
stA.rom_size = stA.ram_size = 0;
stB.rom_size = stB.ram_size = 0;
set(loaded, false);
set(bsx_flash_loaded, false);
set(patched, false);
set(mode, cartridge_mode);
}
void Cartridge::load_end() {
memory::cartrom.map(cart.rom, cart.rom_size);
memory::cartram.map(cart.ram, cart.ram_size);
memory::cartrtc.map(cart.rtc, cart.rtc_size);
memory::bscram.map(bs.ram, bs.ram_size);
memory::stArom.map(stA.rom, stA.rom_size);
memory::stAram.map(stA.ram, stA.ram_size);
memory::stBrom.map(stB.rom, stB.rom_size);
memory::stBram.map(stB.ram, stB.ram_size);
memory::cartrom.write_protect(true);
memory::cartram.write_protect(false);
memory::bscram.write_protect(true);
memory::stArom.write_protect(true);
memory::stAram.write_protect(false);
memory::stBrom.write_protect(true);
memory::stBram.write_protect(false);
string cheat_file = get_filename(cart.filename, "cht", snes.config.path.cheat);
if(file::exists(cheat_file)) {
cheat.clear();
cheat.load(cheat_file);
}
bus.load_cart();
set(loaded, true);
}
void Cartridge::unload() {
if(loaded() == false) return;
bus.unload_cart();
switch(mode()) {
case ModeNormal: unload_normal(); break;
case ModeBsxSlotted: unload_bsx_slotted(); break;
case ModeBsx: unload_bsx(); break;
case ModeSufamiTurbo: unload_sufami_turbo(); break;
}
if(cart.rom) { delete[] cart.rom; cart.rom = 0; }
if(cart.ram) { delete[] cart.ram; cart.ram = 0; }
if(cart.rtc) { delete[] cart.rtc; cart.rtc = 0; }
if(bs.ram) { delete[] bs.ram; bs.ram = 0; }
if(stA.rom) { delete[] stA.rom; stA.rom = 0; }
if(stA.ram) { delete[] stA.ram; stA.ram = 0; }
if(stB.rom) { delete[] stB.rom; stB.rom = 0; }
if(stB.ram) { delete[] stB.ram; stB.ram = 0; }
string cheat_file = get_filename(cart.filename, "cht", snes.config.path.cheat);
if(cheat.count() > 0 || file::exists(cheat_file)) {
cheat.save(cheat_file);
cheat.clear();
}
set(loaded, false);
}
Cartridge::Cartridge() {
set(loaded, false);
}
Cartridge::~Cartridge() {
if(loaded() == true) unload();
}
void Cartridge::set_cartinfo(const Cartridge::cartinfo_t &source) {
set(region, source.region);
set(mapper, source.mapper);
set(dsp1_mapper, source.dsp1_mapper);
set(has_bsx_slot, source.bsx_slot);
set(has_superfx, source.superfx);
set(has_sa1, source.sa1);
set(has_srtc, source.srtc);
set(has_sdd1, source.sdd1);
set(has_spc7110, source.spc7110);
set(has_spc7110rtc, source.spc7110rtc);
set(has_cx4, source.cx4);
set(has_dsp1, source.dsp1);
set(has_dsp2, source.dsp2);
set(has_dsp3, source.dsp3);
set(has_dsp4, source.dsp4);
set(has_obc1, source.obc1);
set(has_st010, source.st010);
set(has_st011, source.st011);
set(has_st018, source.st018);
}
//==========
//cartinfo_t
//==========
void Cartridge::cartinfo_t::reset() {
type = TypeUnknown;
mapper = LoROM;
dsp1_mapper = DSP1Unmapped;
region = NTSC;
rom_size = 0;
ram_size = 0;
bsx_slot = false;
superfx = false;
sa1 = false;
srtc = false;
sdd1 = false;
spc7110 = false;
spc7110rtc = false;
cx4 = false;
dsp1 = false;
dsp2 = false;
dsp3 = false;
dsp4 = false;
obc1 = false;
st010 = false;
st011 = false;
st018 = false;
}
Cartridge::cartinfo_t::cartinfo_t() {
reset();
}
//=======
//utility
//=======
//ensure file path is absolute (eg resolve relative paths)
string Cartridge::filepath(const char *filename, const char *pathname) {
//if no pathname, return filename as-is
string file(filename);
file.replace("\\", "/");
string path = (!pathname || !*pathname) ? (const char*)snes.config.path.current : pathname;
//ensure path ends with trailing '/'
path.replace("\\", "/");
if(!strend(path, "/")) path.append("/");
//replace relative path with absolute path
if(strbegin(path, "./")) {
ltrim(path, "./");
path = string() << snes.config.path.base << path;
}
//remove folder part of filename
lstring part;
part.split("/", file);
return path << part[part.size() - 1];
}
//remove directory information and file extension ("/foo/bar.ext" -> "bar")
string Cartridge::basename(const char *filename) {
string name(filename);
//remove extension
for(signed i = strlen(name) - 1; i >= 0; i--) {
if(name[i] == '.') {
name[i] = 0;
break;
}
}
//remove directory information
for(signed i = strlen(name) - 1; i >= 0; i--) {
if(name[i] == '/' || name[i] == '\\') {
i++;
char *output = name();
while(true) {
*output++ = name[i];
if(!name[i]) break;
i++;
}
break;
}
}
return name;
}
//remove filename and return path only ("/foo/bar.ext" -> "/foo/bar/")
string Cartridge::basepath(const char *filename) {
string path(filename);
path.replace("\\", "/");
//remove filename
for(signed i = strlen(path) - 1; i >= 0; i--) {
if(path[i] == '/') {
path[i] = 0;
break;
}
}
if(!strend(path, "/")) path.append("/");
return path;
}

View File

@ -1,179 +0,0 @@
class Cartridge : public property {
public:
enum Mode {
ModeNormal,
ModeBsxSlotted,
ModeBsx,
ModeSufamiTurbo,
};
enum Type {
TypeNormal,
TypeBsxSlotted,
TypeBsxBios,
TypeBsx,
TypeSufamiTurboBios,
TypeSufamiTurbo,
TypeUnknown,
};
enum Region {
NTSC,
PAL,
};
enum MemoryMapper {
LoROM,
HiROM,
ExLoROM,
ExHiROM,
SA1ROM,
SPC7110ROM,
BSCLoROM,
BSCHiROM,
BSXROM,
STROM,
};
enum DSP1MemoryMapper {
DSP1Unmapped,
DSP1LoROM1MB,
DSP1LoROM2MB,
DSP1HiROM,
};
//properties can be read via operator(), eg "if(cartridge.loaded() == true)";
//warning: if loaded() == false, no other property is considered valid!
property_t<bool> loaded; //is a base cartridge inserted?
property_t<bool> bsx_flash_loaded; //is a BS-X flash cart connected?
property_t<bool> patched; //has a UPS patch been applied?
property_t<string> name; //display name (filename sans path and extension)
property_t<Mode> mode;
property_t<Region> region;
property_t<MemoryMapper> mapper;
property_t<DSP1MemoryMapper> dsp1_mapper;
property_t<bool> has_bsx_slot;
property_t<bool> has_superfx;
property_t<bool> has_sa1;
property_t<bool> has_srtc;
property_t<bool> has_sdd1;
property_t<bool> has_spc7110, has_spc7110rtc;
property_t<bool> has_cx4;
property_t<bool> has_dsp1, has_dsp2, has_dsp3, has_dsp4;
property_t<bool> has_obc1;
property_t<bool> has_st010, has_st011, has_st018;
//main interface
bool load_normal (const char *base);
bool load_bsx_slotted (const char *base, const char *slot = "");
bool load_bsx (const char *base, const char *slot = "");
bool load_sufami_turbo(const char *base, const char *slotA = "", const char *slotB = "");
void unload();
//utility functions
static string filepath(const char *filename, const char *pathname); //"./bar.ext" -> "/foo/bar.ext"
static string basename(const char *filename); //"/foo/bar.ext" -> "bar"
static string basepath(const char *filename); //"/foo/bar.ext" -> "/foo/bar/"
//this function will load 'filename', decompress it if needed, and determine what type of
//image file 'filename' refers to (eg normal cart, BS-X flash cart, Sufami Turbo cart, etc.)
//warning: this operation is very expensive, use sparingly!
Type detect_image_type(const char *filename) const;
Cartridge();
~Cartridge();
private:
void load_begin(Mode);
void load_end();
void unload_normal();
void unload_bsx_slotted();
void unload_bsx();
void unload_sufami_turbo();
struct cartinfo_t {
Type type;
Region region;
MemoryMapper mapper;
DSP1MemoryMapper dsp1_mapper;
unsigned rom_size, ram_size;
bool bsx_slot;
bool superfx;
bool sa1;
bool srtc;
bool sdd1;
bool spc7110, spc7110rtc;
bool cx4;
bool dsp1, dsp2, dsp3, dsp4;
bool obc1;
bool st010, st011, st018;
void reset();
cartinfo_t();
};
enum HeaderField {
CartName = 0x00,
Mapper = 0x15,
RomType = 0x16,
RomSize = 0x17,
RamSize = 0x18,
CartRegion = 0x19,
Company = 0x1a,
Version = 0x1b,
Complement = 0x1c, //inverse checksum
Checksum = 0x1e,
ResetVector = 0x3c,
};
void read_header(cartinfo_t &info, const uint8_t *data, unsigned size) const;
unsigned find_header(const uint8_t *data, unsigned size) const;
unsigned score_header(const uint8_t *data, unsigned size, unsigned addr) const;
void set_cartinfo(const cartinfo_t&);
bool load_image(const char *filename, uint8_t *&data, unsigned &size, bool &patched) const;
bool load_ram (const char *filename, uint8_t *&data, unsigned size, uint8_t init_value) const;
enum CompressionMode {
CompressionNone, //always load without compression
CompressionInspect, //use file header inspection
CompressionAuto, //use file extension or file header inspection (configured by user)
};
bool load_file(const char *fn, uint8 *&data, unsigned &size, CompressionMode compression = CompressionNone) const;
bool save_file(const char *fn, uint8 *data, unsigned size) const;
bool apply_patch(const uint8_t *pdata, unsigned psize, uint8_t *&data, unsigned &size) const;
string modify_extension(const char *filename, const char *extension) const;
string get_filename(const char *source, const char *extension, const char *path) const;
struct {
string filename;
uint8_t *rom, *ram, *rtc;
unsigned rom_size, ram_size, rtc_size;
} cart;
struct {
string filename;
uint8_t *ram;
unsigned ram_size;
} bs;
struct {
string filename;
uint8_t *rom, *ram;
unsigned rom_size, ram_size;
} stA, stB;
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bscram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
};
extern Cartridge cartridge;

View File

@ -1,109 +0,0 @@
#ifdef CART_CPP
#include "../reader/filereader.hpp"
#if defined(GZIP_SUPPORT)
#include "../reader/gzreader.hpp"
#include "../reader/zipreader.hpp"
#endif
#if defined(JMA_SUPPORT)
#include "../reader/jmareader.hpp"
#endif
string Cartridge::modify_extension(const char *filename_, const char *extension) const {
string filename = filename_;
int i;
for(i = strlen(filename); i >= 0; i--) {
if(filename[i] == '.') break;
if(filename[i] == '/') break;
if(filename[i] == '\\') break;
}
if(i > 0 && filename[i] == '.') filename[i] = 0;
return filename << "." << extension;
}
string Cartridge::get_filename(const char *source, const char *extension, const char *path) const {
return filepath(modify_extension(source, extension), path);
}
bool Cartridge::load_file(const char *fn, uint8 *&data, unsigned &size, CompressionMode compression) const {
if(file::exists(fn) == false) return false;
Reader::Type filetype = Reader::Normal;
if(compression == CompressionInspect) filetype = Reader::detect(fn, true);
if(compression == CompressionAuto) filetype = Reader::detect(fn, snes.config.file.autodetect_type);
switch(filetype) { default:
case Reader::Normal: {
FileReader ff(fn);
if(!ff.ready()) return false;
size = ff.size();
data = ff.read();
} break;
#ifdef GZIP_SUPPORT
case Reader::GZIP: {
GZReader gf(fn);
if(!gf.ready()) return false;
size = gf.size();
data = gf.read();
} break;
case Reader::ZIP: {
ZipReader zf(fn);
if(!zf.ready()) return false;
size = zf.size();
data = zf.read();
} break;
#endif
#ifdef JMA_SUPPORT
case Reader::JMA: {
try {
JMAReader jf(fn);
size = jf.size();
data = jf.read();
} catch(JMA::jma_errors jma_error) {
return false;
}
} break;
#endif
}
return true;
}
bool Cartridge::apply_patch(const uint8_t *pdata, const unsigned psize, uint8_t *&data, unsigned &size) const {
uint8_t *outdata = 0;
unsigned outsize;
ups patcher;
ups::result result = patcher.apply(pdata, psize, data, size, outdata, outsize);
bool apply = false;
if(result == ups::ok) apply = true;
if(snes.config.file.bypass_patch_crc32 == true) {
if(result == ups::input_crc32_invalid) apply = true;
if(result == ups::output_crc32_invalid) apply = true;
}
//if patch application was successful, replace old data, size with new data, size
if(apply == true) {
delete[] data;
data = new uint8_t[size = outsize];
memcpy(data, outdata, outsize);
}
if(outdata) delete[] outdata;
return apply;
}
bool Cartridge::save_file(const char *fn, uint8 *data, unsigned size) const {
file fp;
if(!fp.open(fn, file::mode_write)) return false;
fp.write(data, size);
fp.close();
return true;
}
#endif

View File

@ -1,245 +0,0 @@
#ifdef CART_CPP
//================
//Normal cartridge
//================
bool Cartridge::load_normal(const char *base) {
uint8_t *data;
unsigned size;
bool patch_applied;
cart.filename = base;
load_begin(ModeNormal);
if(load_image(base, data, size, patch_applied) == false) return false;
snes.config.path.current = basepath(cart.filename);
if(patch_applied) set(patched, true);
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = data, cart.rom_size = size);
set_cartinfo(cartinfo);
if(cartinfo.ram_size > 0) {
load_ram(get_filename(base, "srm", snes.config.path.save), cart.ram, cart.ram_size = cartinfo.ram_size, 0xff);
}
if(cartinfo.srtc || cartinfo.spc7110rtc) {
load_ram(get_filename(base, "rtc", snes.config.path.save), cart.rtc, cart.rtc_size = 20, 0x00);
}
load_end();
set(name, basename(base));
return true;
}
void Cartridge::unload_normal() {
if(cart.ram) save_file(get_filename(cart.filename, "srm", snes.config.path.save), cart.ram, cart.ram_size);
if(cart.rtc) save_file(get_filename(cart.filename, "rtc", snes.config.path.save), cart.rtc, cart.rtc_size);
}
//======================
//BS-X slotted cartridge
//======================
bool Cartridge::load_bsx_slotted(const char *base, const char *slot) {
uint8_t *data;
unsigned size;
bool patch_applied;
cart.filename = base;
bs.filename = slot;
load_begin(ModeBsxSlotted);
if(load_image(base, data, size, patch_applied) == false) return false;
snes.config.path.current = basepath(cart.filename);
if(patch_applied) set(patched, true);
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = data, cart.rom_size = size);
set_cartinfo(cartinfo);
if(load_image(slot, data, size, patch_applied) == true) {
set(bsx_flash_loaded, true);
if(patch_applied) set(patched, true);
bs.ram = data;
bs.ram_size = size;
}
if(cartinfo.ram_size > 0) {
load_ram(get_filename(base, "srm", snes.config.path.save), cart.ram, cart.ram_size = cartinfo.ram_size, 0xff);
}
load_end();
string filename = basename(base);
if(*slot) filename << " + " << basename(slot);
set(name, filename);
return true;
}
void Cartridge::unload_bsx_slotted() {
if(cart.ram) save_file(get_filename(cart.filename, "srm", snes.config.path.save), cart.ram, cart.ram_size);
}
//====================
//BS-X flash cartridge
//====================
bool Cartridge::load_bsx(const char *base, const char *slot) {
uint8_t *data;
unsigned size;
bool patch_applied;
cart.filename = base;
bs.filename = slot;
load_begin(ModeBsx);
if(load_image(base, data, size, patch_applied) == false) return false;
snes.config.path.current = basepath(cart.filename);
if(patch_applied) set(patched, true);
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = data, cart.rom_size = size);
set_cartinfo(cartinfo);
cart.ram = 0;
cart.ram_size = 0;
memset(bsxcart.sram.handle (), 0x00, bsxcart.sram.size ());
memset(bsxcart.psram.handle(), 0x00, bsxcart.psram.size());
if(load_file(get_filename(base, "srm", snes.config.path.save), data, size, CompressionNone) == true) {
memcpy(bsxcart.sram.handle (), data, min(bsxcart.sram.size (), size));
delete[] data;
}
if(load_file(get_filename(base, "psr", snes.config.path.save), data, size, CompressionNone) == true) {
memcpy(bsxcart.psram.handle(), data, min(bsxcart.psram.size(), size));
delete[] data;
}
if(load_image(slot, data, size, patch_applied) == true) {
set(bsx_flash_loaded, true);
if(patch_applied) set(patched, true);
bs.ram = data;
bs.ram_size = size;
}
load_end();
set(name, !*slot ? basename(base) : basename(slot));
return true;
}
void Cartridge::unload_bsx() {
save_file(get_filename(cart.filename, "srm", snes.config.path.save), bsxcart.sram.handle (), bsxcart.sram.size ());
save_file(get_filename(cart.filename, "psr", snes.config.path.save), bsxcart.psram.handle(), bsxcart.psram.size());
}
//============================
//Sufami Turbo flash cartridge
//============================
bool Cartridge::load_sufami_turbo(const char *base, const char *slotA, const char *slotB) {
uint8_t *data;
unsigned size;
bool patch_applied;
cart.filename = base;
stA.filename = slotA;
stB.filename = slotB;
load_begin(ModeSufamiTurbo);
if(load_image(base, data, size, patch_applied) == false) return false;
snes.config.path.current = basepath(cart.filename);
if(patch_applied) set(patched, true);
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = data, cart.rom_size = size);
set_cartinfo(cartinfo);
if(load_image(slotA, data, size, patch_applied) == true) {
if(patch_applied) set(patched, true);
stA.rom = new(zeromemory) uint8_t[stA.rom_size = 0x100000];
memcpy(stA.rom, data, min(size, stA.rom_size));
delete[] data;
load_ram(get_filename(slotA, "srm", snes.config.path.save), stA.ram, stA.ram_size = 0x020000, 0xff);
}
if(load_image(slotB, data, size, patch_applied) == true) {
if(patch_applied) set(patched, true);
stB.rom = new(zeromemory) uint8_t[stB.rom_size = 0x100000];
memcpy(stB.rom, data, min(size, stB.rom_size));
delete[] data;
load_ram(get_filename(slotB, "srm", snes.config.path.save), stB.ram, stB.ram_size = 0x020000, 0xff);
}
load_end();
string filename;
if(!*slotA && !*slotB) filename << basename(base);
else if( *slotA && !*slotB) filename << basename(slotA);
else if(!*slotA && *slotB) filename << basename(slotB);
else filename << basename(slotA) << " + " << basename(slotB);
set(name, filename);
return true;
}
void Cartridge::unload_sufami_turbo() {
if(stA.ram) save_file(get_filename(stA.filename, "srm", snes.config.path.save), stA.ram, stA.ram_size);
if(stB.ram) save_file(get_filename(stB.filename, "srm", snes.config.path.save), stB.ram, stB.ram_size);
}
//=================
//utility functions
//=================
Cartridge::Type Cartridge::detect_image_type(const char *filename) const {
uint8_t *data;
unsigned size;
bool patch_applied;
if(!load_image(filename, data, size, patch_applied)) return TypeUnknown;
cartinfo_t info;
read_header(info, data, size);
delete[] data;
return info.type;
}
bool Cartridge::load_image(const char *filename, uint8_t *&data, unsigned &size, bool &patched) const {
if(!filename || !*filename) return false;
if(!load_file(filename, data, size, CompressionAuto)) return false;
if((size & 0x7fff) == 512) {
//remove 512-byte header
memmove(data, data + 512, size -= 512);
}
uint8_t *pdata;
unsigned psize;
string path = (snes.config.path.patch == "" ? basepath(filename) : snes.config.path.patch);
if(load_file(get_filename(filename, "ups", path), pdata, psize, CompressionInspect) == true) {
bool result = apply_patch(pdata, psize, data, size);
delete[] pdata;
patched = result;
} else {
patched = false;
}
return true;
}
bool Cartridge::load_ram(const char *filename, uint8_t *&data, unsigned size, uint8_t init) const {
data = new uint8_t[size];
memset(data, init, size);
uint8_t *savedata;
unsigned savesize;
if(load_file(filename, savedata, savesize, CompressionNone) == false) return false;
memcpy(data, savedata, min(size, savesize));
delete[] savedata;
return true;
}
#endif

140
src/cartridge/cartridge.cpp Normal file
View File

@ -0,0 +1,140 @@
#include <../base.hpp>
#define CART_CPP
namespace SNES {
#include "cartridge_header.cpp"
#include "cartridge_loader.cpp"
namespace memory {
MappedRAM cartrom, cartram, cartrtc;
MappedRAM bscram;
MappedRAM stArom, stAram;
MappedRAM stBrom, stBram;
MappedRAM dmgrom, dmgram, dmgrtc;
};
Cartridge cartridge;
void Cartridge::load_begin(Mode cartridge_mode) {
memory::cartrom.map(0, 0);
memory::cartram.map(0, 0);
memory::cartrtc.map(0, 0);
memory::bscram.map (0, 0);
memory::stArom.map (0, 0);
memory::stAram.map (0, 0);
memory::stBrom.map (0, 0);
memory::stBram.map (0, 0);
memory::dmgrom.map (0, 0);
memory::dmgram.map (0, 0);
memory::dmgrtc.map (0, 0);
set(loaded, false);
set(bsx_flash_loaded, false);
set(patched, false);
set(mode, cartridge_mode);
}
void Cartridge::load_end() {
memory::cartrom.write_protect(true);
memory::cartram.write_protect(false);
memory::cartrtc.write_protect(false);
memory::bscram.write_protect (true);
memory::stArom.write_protect (true);
memory::stAram.write_protect (false);
memory::stBrom.write_protect (true);
memory::stBram.write_protect (false);
memory::dmgrom.write_protect (true);
memory::dmgram.write_protect (false);
memory::dmgrtc.write_protect (false);
bus.load_cart();
set(loaded, true);
}
void Cartridge::unload() {
if(loaded() == false) return;
bus.unload_cart();
memory::cartrom.reset();
memory::cartram.reset();
memory::cartrtc.reset();
memory::bscram.reset();
memory::stArom.reset();
memory::stAram.reset();
memory::stBrom.reset();
memory::stBram.reset();
memory::dmgrom.reset();
memory::dmgram.reset();
memory::dmgrtc.reset();
set(loaded, false);
}
Cartridge::Cartridge() {
set(loaded, false);
}
Cartridge::~Cartridge() {
if(loaded() == true) unload();
}
void Cartridge::set_cartinfo(const Cartridge::cartinfo_t &source) {
set(region, source.region);
set(mapper, source.mapper);
set(dsp1_mapper, source.dsp1_mapper);
set(has_bsx_slot, source.bsx_slot);
set(has_superfx, source.superfx);
set(has_sa1, source.sa1);
set(has_srtc, source.srtc);
set(has_sdd1, source.sdd1);
set(has_spc7110, source.spc7110);
set(has_spc7110rtc, source.spc7110rtc);
set(has_cx4, source.cx4);
set(has_dsp1, source.dsp1);
set(has_dsp2, source.dsp2);
set(has_dsp3, source.dsp3);
set(has_dsp4, source.dsp4);
set(has_obc1, source.obc1);
set(has_st010, source.st010);
set(has_st011, source.st011);
set(has_st018, source.st018);
}
//==========
//cartinfo_t
//==========
void Cartridge::cartinfo_t::reset() {
type = TypeUnknown;
mapper = LoROM;
dsp1_mapper = DSP1Unmapped;
region = NTSC;
rom_size = 0;
ram_size = 0;
bsx_slot = false;
superfx = false;
sa1 = false;
srtc = false;
sdd1 = false;
spc7110 = false;
spc7110rtc = false;
cx4 = false;
dsp1 = false;
dsp2 = false;
dsp3 = false;
dsp4 = false;
obc1 = false;
st010 = false;
st011 = false;
st018 = false;
}
Cartridge::cartinfo_t::cartinfo_t() {
reset();
}
};

137
src/cartridge/cartridge.hpp Normal file
View File

@ -0,0 +1,137 @@
class Cartridge : public property {
public:
enum Mode {
ModeNormal,
ModeBsxSlotted,
ModeBsx,
ModeSufamiTurbo,
ModeSuperGameboy,
};
enum Type {
TypeNormal,
TypeBsxSlotted,
TypeBsxBios,
TypeBsx,
TypeSufamiTurboBios,
TypeSufamiTurbo,
TypeSuperGameboyBios,
TypeGameboy,
TypeUnknown,
};
enum Region {
NTSC,
PAL,
};
enum MemoryMapper {
LoROM,
HiROM,
ExLoROM,
ExHiROM,
SA1ROM,
SPC7110ROM,
BSCLoROM,
BSCHiROM,
BSXROM,
STROM,
};
enum DSP1MemoryMapper {
DSP1Unmapped,
DSP1LoROM1MB,
DSP1LoROM2MB,
DSP1HiROM,
};
//properties can be read via operator(), eg "if(cartridge.loaded() == true)";
//warning: if loaded() == false, no other property is considered valid!
property_t<bool> loaded; //is a base cartridge inserted?
property_t<bool> bsx_flash_loaded; //is a BS-X flash cart connected?
property_t<bool> patched; //has a UPS patch been applied?
property_t<Mode> mode;
property_t<Region> region;
property_t<MemoryMapper> mapper;
property_t<DSP1MemoryMapper> dsp1_mapper;
property_t<bool> has_bsx_slot;
property_t<bool> has_superfx;
property_t<bool> has_sa1;
property_t<bool> has_srtc;
property_t<bool> has_sdd1;
property_t<bool> has_spc7110, has_spc7110rtc;
property_t<bool> has_cx4;
property_t<bool> has_dsp1, has_dsp2, has_dsp3, has_dsp4;
property_t<bool> has_obc1;
property_t<bool> has_st010, has_st011, has_st018;
//main interface
Type detect_image_type (uint8_t*, unsigned) const;
bool load_normal (uint8_t*, unsigned);
bool load_bsx_slotted (uint8_t*, unsigned, uint8_t*, unsigned);
bool load_bsx (uint8_t*, unsigned, uint8_t*, unsigned);
bool load_sufami_turbo (uint8_t*, unsigned, uint8_t*, unsigned, uint8_t*, unsigned);
bool load_super_gameboy(uint8_t*, unsigned, uint8_t*, unsigned);
void unload();
Cartridge();
~Cartridge();
private:
void load_begin(Mode);
void load_end();
struct cartinfo_t {
Type type;
Region region;
MemoryMapper mapper;
DSP1MemoryMapper dsp1_mapper;
unsigned rom_size, ram_size;
bool bsx_slot;
bool superfx;
bool sa1;
bool srtc;
bool sdd1;
bool spc7110, spc7110rtc;
bool cx4;
bool dsp1, dsp2, dsp3, dsp4;
bool obc1;
bool st010, st011, st018;
void reset();
cartinfo_t();
};
enum HeaderField {
CartName = 0x00,
Mapper = 0x15,
RomType = 0x16,
RomSize = 0x17,
RamSize = 0x18,
CartRegion = 0x19,
Company = 0x1a,
Version = 0x1b,
Complement = 0x1c, //inverse checksum
Checksum = 0x1e,
ResetVector = 0x3c,
};
void read_header(cartinfo_t &info, const uint8_t *data, unsigned size) const;
unsigned find_header(const uint8_t *data, unsigned size) const;
unsigned score_header(const uint8_t *data, unsigned size, unsigned addr) const;
void set_cartinfo(const cartinfo_t&);
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bscram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
extern MappedRAM dmgrom, dmgram, dmgrtc;
};
extern Cartridge cartridge;

View File

@ -2,7 +2,29 @@
void Cartridge::read_header(cartinfo_t &info, const uint8_t *data, unsigned size) const {
info.reset();
unsigned index = find_header(data, size);
//====================
//detect Gameboy carts
//====================
if(size >= 0x0150) {
if(data[0x0104] == 0xce && data[0x0105] == 0xed && data[0x0106] == 0x66 && data[0x0107] == 0x66) {
if(data[0x0108] == 0xcc && data[0x0109] == 0x0d && data[0x010a] == 0x00 && data[0x010b] == 0x0b) {
info.type = TypeGameboy;
return;
}
}
}
const unsigned index = find_header(data, size);
const uint8 mapper = data[index + Mapper];
const uint8 rom_type = data[index + RomType];
const uint8 rom_size = data[index + RomSize];
const uint8 company = data[index + Company];
const uint8 region = data[index + CartRegion] & 0x7f;
//0, 1, 13 = NTSC; 2 - 12 = PAL
info.region = (region <= 1 || region >= 13) ? NTSC : PAL;
//=======================
//detect BS-X flash carts
@ -15,7 +37,6 @@ void Cartridge::read_header(cartinfo_t &info, const uint8_t *data, unsigned size
if(data[index + 0x1a] == 0x33 || data[index + 0x1a] == 0xff) {
info.type = TypeBsx;
info.mapper = BSXROM;
info.region = NTSC; //BS-X only released in Japan
return;
}
}
@ -33,20 +54,23 @@ void Cartridge::read_header(cartinfo_t &info, const uint8_t *data, unsigned size
info.type = TypeSufamiTurbo;
}
info.mapper = STROM;
info.region = NTSC; //Sufami Turbo only released in Japan
return; //RAM size handled internally by load_cart_st();
return;
}
//=========================
//detect Super Gameboy cart
//=========================
if(!memcmp(data + index, "Super GAMEBOY", 13)) {
info.type = TypeSuperGameboyBios;
info.mapper = LoROM;
return;
}
//=====================
//detect standard carts
//=====================
const uint8 mapper = data[index + Mapper];
const uint8 rom_type = data[index + RomType];
const uint8 rom_size = data[index + RomSize];
const uint8 company = data[index + Company];
const uint8 region = data[index + CartRegion] & 0x7f;
//detect presence of BS-X flash cartridge connector (reads extended header information)
if(data[index - 14] == 'Z') {
if(data[index - 11] == 'J') {
@ -169,9 +193,6 @@ void Cartridge::read_header(cartinfo_t &info, const uint8_t *data, unsigned size
} else {
info.ram_size = 0;
}
//0, 1, 13 = NTSC; 2 - 12 = PAL
info.region = (region <= 1 || region >= 13) ? NTSC : PAL;
}
unsigned Cartridge::find_header(const uint8_t *data, unsigned size) const {

View File

@ -0,0 +1,148 @@
#ifdef CART_CPP
Cartridge::Type Cartridge::detect_image_type(uint8_t *data, unsigned size) const {
cartinfo_t info;
read_header(info, data, size);
return info.type;
}
//================
//Normal cartridge
//================
bool Cartridge::load_normal(uint8_t *basedata, unsigned basesize) {
load_begin(ModeNormal);
memory::cartrom.map(new uint8_t[basesize], basesize);
memcpy(memory::cartrom.handle(), basedata, basesize);
cartinfo_t cartinfo;
read_header(cartinfo, basedata, basesize);
set_cartinfo(cartinfo);
if(cartinfo.ram_size) {
memory::cartram.map(new(zeromemory) uint8_t[cartinfo.ram_size], cartinfo.ram_size);
}
if(cartinfo.srtc || cartinfo.spc7110rtc) {
memory::cartrtc.map(new(zeromemory) uint8_t[20], 20);
}
load_end();
return true;
}
//======================
//BS-X slotted cartridge
//======================
bool Cartridge::load_bsx_slotted(uint8_t *basedata, unsigned basesize, uint8_t *slotdata, unsigned slotsize) {
load_begin(ModeBsxSlotted);
memory::cartrom.map(new uint8_t[basesize], basesize);
memcpy(memory::cartrom.handle(), basedata, basesize);
cartinfo_t cartinfo;
read_header(cartinfo, basedata, basesize);
set_cartinfo(cartinfo);
if(slotdata) {
memory::bscram.map(new uint8_t[slotsize], slotsize);
memcpy(memory::bscram.handle(), slotdata, slotsize);
set(bsx_flash_loaded, true);
}
if(cartinfo.ram_size) {
memory::cartram.map(new(zeromemory) uint8_t[cartinfo.ram_size], cartinfo.ram_size);
}
load_end();
return true;
}
//====================
//BS-X flash cartridge
//====================
bool Cartridge::load_bsx(uint8_t *basedata, unsigned basesize, uint8_t *slotdata, unsigned slotsize) {
load_begin(ModeBsx);
memory::cartrom.map(new uint8_t[basesize], basesize);
memcpy(memory::cartrom.handle(), basedata, basesize);
cartinfo_t cartinfo;
read_header(cartinfo, basedata, basesize);
set_cartinfo(cartinfo);
if(slotdata) {
memory::bscram.map(new uint8_t[slotsize], slotsize);
memcpy(memory::bscram.handle(), slotdata, slotsize);
set(bsx_flash_loaded, true);
}
memset(bsxcart.sram.handle (), 0x00, bsxcart.sram.size ());
memset(bsxcart.psram.handle(), 0x00, bsxcart.psram.size());
load_end();
return true;
}
//============================
//Sufami Turbo flash cartridge
//============================
bool Cartridge::load_sufami_turbo(uint8_t *basedata, unsigned basesize, uint8_t *slotAdata, unsigned slotAsize, uint8_t *slotBdata, unsigned slotBsize) {
load_begin(ModeSufamiTurbo);
memory::cartrom.map(new uint8_t[basesize], basesize);
memcpy(memory::cartrom.handle(), basedata, basesize);
cartinfo_t cartinfo;
read_header(cartinfo, basedata, basesize);
set_cartinfo(cartinfo);
if(slotAdata) {
memory::stArom.map(new uint8_t[slotAsize], slotAsize);
memory::stAram.map(new uint8_t[0x020000], 0x020000);
memcpy(memory::stArom.handle(), slotAdata, slotAsize);
}
if(slotBdata) {
memory::stBrom.map(new uint8_t[slotBsize], slotBsize);
memory::stBram.map(new uint8_t[0x020000], 0x020000);
memcpy(memory::stBrom.handle(), slotBdata, slotBsize);
}
load_end();
return true;
}
//=======================
//Super Gameboy cartridge
//=======================
bool Cartridge::load_super_gameboy(uint8_t *basedata, unsigned basesize, uint8_t *slotdata, unsigned slotsize) {
load_begin(ModeSuperGameboy);
memory::cartrom.map(new uint8_t[basesize], basesize);
memcpy(memory::cartrom.handle(), basedata, basesize);
cartinfo_t cartinfo;
read_header(cartinfo, basedata, basesize);
set_cartinfo(cartinfo);
if(slotdata) {
uint8_t *data = new uint8_t[slotsize];
memcpy(data, slotdata, slotsize);
memory::dmgrom.map(data, slotsize);
//TODO: determine proper RAM size via GB ROM header
memory::dmgram.map(new uint8_t[524288], 524288);
memory::dmgrtc.map(new uint8_t[4], 4);
}
load_end();
return true;
}
#endif

View File

@ -1,3 +1,3 @@
@mingw32-make platform=win compiler=mingw32-gcc
@mingw32-make platform=win compiler=mingw32-gcc sgb=gambatte
::@mingw32-make platform=win compiler=mingw32-gcc enable_gzip=true enable_jma=true
@pause

View File

@ -1,2 +1,2 @@
make platform=x compiler=gcc
make platform=x compiler=gcc sgb=gambatte
#make platform=x compiler=gcc enable_gzip=true enable_jma=true

View File

@ -1,5 +1,8 @@
#include <../base.hpp>
#define CHEAT_CPP
namespace SNES {
Cheat cheat;
Cheat::cheat_t& Cheat::cheat_t::operator=(const Cheat::cheat_t& source) {
@ -390,3 +393,5 @@ string& Cheat::decode_description(string &desc) const {
desc.replace("\\n", "\n");
return desc;
}
};

View File

@ -1,8 +1,10 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#define BSX_CPP
#include "bsx.hpp"
#define BSX_CPP
namespace SNES {
#include "bsx_base.cpp"
#include "bsx_cart.cpp"
#include "bsx_flash.cpp"
};

View File

@ -1,3 +1,9 @@
struct Chip {
virtual void load() {}
virtual void unload() {}
};
#include "sgb/sgb.hpp"
#include "sa1/sa1.hpp"
#include "bsx/bsx.hpp"
#include "srtc/srtc.hpp"

View File

@ -6,9 +6,10 @@
*/
#include <../base.hpp>
#define CX4_CPP
#include "cx4.hpp"
#define CX4_CPP
namespace SNES {
#include "cx4data.cpp"
#include "cx4fn.cpp"
#include "cx4oam.cpp"
@ -195,3 +196,5 @@ void Cx4::reset() {
memset(ram, 0, 0x0c00);
memset(reg, 0, 0x0100);
}
};

View File

@ -1,8 +1,8 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#define DSP1_CPP
#include "dsp1.hpp"
#define DSP1_CPP
namespace SNES {
#include "dsp1emu.cpp"
void DSP1::init() {}
@ -57,3 +57,5 @@ void DSP1::write(unsigned addr, uint8 data) {
dsp1.setDr(data);
}
}
};

View File

@ -1,7 +1,8 @@
#include <../base.hpp>
#define DSP2_CPP
#include "dsp2.hpp"
#define DSP2_CPP
namespace SNES {
#include "dsp2_op.cpp"
void DSP2::init() {}
@ -134,3 +135,5 @@ void DSP2::write(unsigned addr, uint8 data) {
DSP2::DSP2() {}
DSP2::~DSP2() {}
};

View File

@ -1,7 +1,8 @@
#include <../base.hpp>
#define DSP3_CPP
#include "dsp3.hpp"
#define DSP3_CPP
namespace SNES {
namespace DSP3i {
#define bool8 uint8
#include "dsp3emu.c"
@ -33,3 +34,5 @@ void DSP3::write(unsigned addr, uint8 data) {
DSP3i::dsp3_byte = data;
DSP3i::DSP3SetByte();
}
};

View File

@ -1,7 +1,8 @@
#include <../base.hpp>
#define DSP4_CPP
#include "dsp4.hpp"
#define DSP4_CPP
namespace SNES {
namespace DSP4i {
inline uint16 READ_WORD(uint8 *addr) {
return (addr[0]) + (addr[1] << 8);
@ -53,3 +54,5 @@ void DSP4::write(unsigned addr, uint8 data) {
DSP4i::DSP4SetByte();
}
}
};

View File

@ -1,6 +1,7 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#include "obc1.hpp"
#define OBC1_CPP
namespace SNES {
void OBC1::init() {}
void OBC1::enable() {}
@ -70,3 +71,5 @@ void OBC1::ram_write(unsigned addr, uint8 data) {
OBC1::OBC1() {}
OBC1::~OBC1() {}
};

View File

@ -1,9 +1,8 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#include <../chip/bsx/bsx.hpp>
#define SA1_CPP
#include "sa1.hpp"
#define SA1_CPP
namespace SNES {
#include "bus/bus.cpp"
#include "dma/dma.cpp"
#include "memory/memory.cpp"
@ -141,7 +140,7 @@ void SA1::reset() {
status.interrupt_pending = false;
status.interrupt_vector = 0x0000;
status.scanlines = (snes.region() == SNES::NTSC ? 262 : 312);
status.scanlines = (system.region() == System::NTSC ? 262 : 312);
status.vcounter = 0;
status.hcounter = 0;
@ -312,3 +311,5 @@ void SA1::reset() {
SA1::SA1() {
}
};

View File

@ -1,8 +1,8 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#define SDD1_CPP
#include "sdd1.hpp"
#define SDD1_CPP
namespace SNES {
#include "sdd1emu.cpp"
void SDD1::init() {}
@ -156,3 +156,5 @@ SDD1::SDD1() {
SDD1::~SDD1() {
delete[] buffer.data;
}
};

View File

@ -0,0 +1,174 @@
#include <libgambatte/include/gambatte.h>
namespace SNES {
class GambatteVideo : public Gambatte::VideoBlitter {
public:
unsigned bufferWidth, bufferHeight;
uint32_t *buffer;
void setBufferDimensions(unsigned width, unsigned height) {
if(buffer) delete[] buffer;
buffer = new uint32_t[width * height];
bufferWidth = width;
bufferHeight = height;
}
const Gambatte::PixelBuffer inBuffer() {
Gambatte::PixelBuffer pb;
pb.pixels = (void*)buffer;
pb.format = Gambatte::PixelBuffer::RGB32;
pb.pitch = bufferWidth;
return pb;
}
void blit() {
}
void update(unsigned row) {
uint32_t *source = buffer + row * 160 * 8;
uint8_t *buffer = new(zeromemory) uint8_t[5760];
for(unsigned y = row * 8; y < row * 8 + 8; y++) {
for(unsigned x = 0; x < 160; x++) {
unsigned pixel = *source++ / 0x555555;
pixel ^= 3;
unsigned tile = ((y / 8) * 20) + (x / 8);
unsigned addr = (tile * 16) + ((y & 7) * 2);
buffer[addr + 0] |= ((pixel & 1) >> 0) << (7 - (x & 7));
buffer[addr + 1] |= ((pixel & 2) >> 1) << (7 - (x & 7));
}
}
memcpy(sgb.gameboy->vram, buffer, 5760);
delete[] buffer;
}
~GambatteVideo() {
if(buffer) delete[] buffer;
}
};
class GambatteInput : public Gambatte::InputStateGetter {
public:
Gambatte::InputState is;
const Gambatte::InputState& operator()() {
unsigned joypad = sgb.gameboy->joypadid();
unsigned data = sgb.mmio.joypad[joypad];
//TODO: fix SGB detection
joypad = 1;
data = sgb.mmio.joypad[0];
is.joypadId = 0x0f - joypad;
is.startButton = !(data & 0x80);
is.selectButton = !(data & 0x40);
is.bButton = !(data & 0x20);
is.aButton = !(data & 0x10);
is.dpadDown = !(data & 0x08);
is.dpadUp = !(data & 0x04);
is.dpadLeft = !(data & 0x02);
is.dpadRight = !(data & 0x01);
return is;
}
};
class GambatteMemory : public Gambatte::MemoryInterface {
public:
Gambatte::MemoryBuffer loadRomData() {
Gambatte::MemoryBuffer mb;
mb.data = (void*)memory::dmgrom.handle();
mb.size = memory::dmgrom.size();
return mb;
}
Gambatte::MemoryBuffer loadRamData() {
Gambatte::MemoryBuffer mb;
mb.data = (void*)memory::dmgram.handle();
mb.size = memory::dmgram.size();
return mb;
}
Gambatte::MemoryBuffer loadRtcData() {
Gambatte::MemoryBuffer mb;
mb.data = (void*)memory::dmgrtc.handle();
mb.size = memory::dmgram.size();
return mb;
}
Gambatte::MemoryBuffer saveRamData(unsigned size) {
memory::dmgram.reset();
memory::dmgram.map(new uint8_t[size], size);
Gambatte::MemoryBuffer mb;
mb.data = (void*)memory::dmgram.handle();
mb.size = memory::dmgram.size();
return mb;
}
Gambatte::MemoryBuffer saveRtcData() {
memory::dmgrtc.reset();
memory::dmgrtc.map(new uint8_t[4], 4);
Gambatte::MemoryBuffer mb;
mb.data = (void*)memory::dmgrtc.handle();
mb.size = memory::dmgrtc.size();
return mb;
}
void joypWrite(bool p15, bool p14) {
sgb.gameboy->write(p15, p14);
}
};
class GameboyGambatte : public Gameboy {
public:
Gambatte::GB gambatte;
GambatteInput gambatte_input;
GambatteVideo gambatte_video;
GambatteMemory gambatte_memory;
uint32_t audio_buffer[65536];
unsigned run() {
unsigned samples = gambatte.runFor(audio_buffer, 16);
for(unsigned i = 0; i < samples; i++) {
system.audio.cop_sample(audio_buffer[i] >> 0, audio_buffer[i] >> 16);
}
return (samples << 3) + (samples << 1); //1 sample = 10 S-CPU clock cycles
}
unsigned lyCounter() {
return gambatte.lyCounter();
}
void updateVideo(unsigned row) {
gambatte.updateVideo();
gambatte_video.update(row);
}
void unload() {
gambatte.save();
}
void power() {
Gameboy::power();
gambatte.load(true);
system.audio.set_cop_frequency(60 * 35112);
}
void reset() {
Gameboy::reset();
gambatte.reset();
system.audio.set_cop_frequency(60 * 35112);
}
GameboyGambatte() {
gambatte.setVideoBlitter(&gambatte_video);
gambatte.setInputStateGetter(&gambatte_input);
gambatte.setMemoryInterface(&gambatte_memory);
}
};
};

View File

@ -0,0 +1,98 @@
namespace SNES {
static const char command_name[32][64] = {
"PAL01", "PAL23", "PAL03", "PAL12",
"ATTR_BLK", "ATTR_LIN", "ATTR_DIV", "ATTR_CHR",
"SOUND", "SOU_TRN", "PAL_SET", "PAL_TRN",
"ATRC_EN", "TEST_EN", "ICON_EN", "DATA_SND",
"DATA_TRN", "MLT_REG", "JUMP", "CHR_TRN",
"PCT_TRN", "ATTR_TRN", "ATTR_SET", "MASK_EN",
"OBJ_TRN", "19_???", "1A_???", "1B_???",
"1C_???", "1D_???", "1E_ROM", "1F_???",
};
class Gameboy {
public:
uint8_t vram[(160 / 8) * (144 / 8) * (64 / 4)];
bool pulselock;
bool strobelock;
bool packetlock;
SuperGameboy::Packet packet;
uint8_t packetoffset;
uint8_t bitdata, bitoffset;
unsigned joypadid() {
return sgb.mmio.joypadid;
}
void write(bool p15, bool p14) {
if(p15 == 1 && p14 == 1) {
sgb.mmio.joypadid++;
if(sgb.mmio.r6003 & 0x20) sgb.mmio.joypadid &= 3;
else if(sgb.mmio.r6003 & 0x10) sgb.mmio.joypadid &= 1;
else sgb.mmio.joypadid &= 0;
}
if(p15 == 0 && p14 == 0) {
//pulse
pulselock = false;
packetoffset = 0;
bitoffset = 0;
strobelock = true;
packetlock = false;
return;
}
if(pulselock) return;
if(p15 == 1 && p14 == 1) {
strobelock = false;
return;
}
if(strobelock) return;
//p15(1), p14(0) = 0
//p15(0), p14(1) = 1
bool bit = (p15 == 0);
strobelock = true;
if(packetlock) {
if(p15 == 1 && p14 == 0) {
//packet stop bit
printf("%s\n", command_name[packet[0] >> 3]);
sgb.packet.add(packet);
packetlock = false;
pulselock = true;
}
return;
}
bitdata = (bit << 7) | (bitdata >> 1);
if(++bitoffset < 8) return;
bitoffset = 0;
packet[packetoffset] = bitdata;
if(++packetoffset < 16) return;
packetlock = true;
}
virtual unsigned run() { return 64; }
virtual unsigned lyCounter() { return 0; }
virtual void updateVideo(unsigned) {}
virtual void unload() {}
virtual void power() {
pulselock = true;
memset(&vram, 0, sizeof vram);
}
virtual void reset() {
pulselock = true;
memset(&vram, 0, sizeof vram);
}
};
};

View File

@ -0,0 +1,24 @@
namespace SNES {
class Gameboy {
public:
unsigned run() {
for(unsigned i = 0; i < memory::sgbvram.size(); i++) {
memory::sgbvram.write(i, rand());
}
sgb.refresh();
return 0;
}
void unload() {
}
void power() {
}
void reset() {
}
};
};

147
src/chip/sgb/sgb.cpp Normal file
View File

@ -0,0 +1,147 @@
#include <../base.hpp>
#include "interface/interface.hpp"
#if defined(SGB_GAMBATTE)
#include "interface/gambatte.cpp"
#else
#include "interface/reference.cpp"
#endif
#define SGB_CPP
namespace SNES {
void SuperGameboy::enter() {
while(true) {
unsigned clocks;
if((mmio.r6003 & 0x80) == 0) {
clocks = 10;
system.audio.cop_sample(0, 0);
} else {
clocks = gameboy->run();
}
scheduler.addclocks_cop(clocks);
scheduler.sync_copcpu();
}
}
uint8_t SuperGameboy::read(unsigned addr) {
addr &= 0xffff;
//DMG lyCounter
if(addr == 0x6000) {
return gameboy->lyCounter();
}
//command ready port
if(addr == 0x6002) {
bool data = packet.size() > 0;
if(data) {
mmio.r7000 = packet[0];
unsigned size = packet.size() - 1;
for(unsigned i = 0; i < size; i++) packet[i] = packet[i + 1];
packet.resize(size);
}
return data;
}
//command port
if((addr & 0xfff0) == 0x7000) {
return mmio.r7000[addr & 15];
}
//screen data port
if(addr == 0x7800) {
uint8_t data = gameboy->vram[mmio.r7800++];
if(mmio.r7800 >= (160 / 8) * (144 / 8) * (64 / 4)) mmio.r7800 = 0;
return data;
}
return 0x00;
}
void SuperGameboy::write(unsigned addr, uint8_t data) {
addr &= 0xffff;
if(addr == 0x6001) {
gameboy->updateVideo(mmio.r7800 / 320);
}
//control port
//d7 = Gameboy enable
//d5 = four-player enable (1=4-player, 0=see d4)
//d4 = two-player enable (if: d5=0; 1=2-player, 0=1-player)
//d0 = ??? (always 1)
if(addr == 0x6003) {
if(((mmio.r6003 & 0x80) == 0x00) && ((data & 0x80) == 0x80)) {
gameboy->reset();
command_1e();
mmio.r7800 = 320 * 16;
}
mmio.r6003 = data;
return;
}
//joypad ports 1-4
if((addr & 0x600c) == 0x6004) {
mmio.joypad[addr & 3] = data;
return;
}
}
void SuperGameboy::init() {}
void SuperGameboy::enable() {}
void SuperGameboy::power() {
multiplier = (system.region() == System::NTSC ? config.cpu.ntsc_clock_rate : config.cpu.pal_clock_rate);
gameboy->power();
reset();
}
void SuperGameboy::reset() {
gameboy->reset();
packet.reset();
counter = 0;
bus.map(Bus::MapDirect, 0x00, 0x3f, 0x6000, 0x7fff, *this);
bus.map(Bus::MapDirect, 0x80, 0xbf, 0x6000, 0x7fff, *this);
mmio.r6000 = 0;
mmio.r6003 = 0;
//$6004-$6007
mmio.joypadid = 0;
for(unsigned i = 0; i < 4; i++) mmio.joypad[i] = 0xff;
for(unsigned i = 0; i < 16; i++) mmio.r7000[i] = 0;
mmio.r7800 = 0;
}
void SuperGameboy::unload() {
gameboy->unload();
}
//
void SuperGameboy::command_1e() {
for(unsigned i = 0; i < 6; i++) {
Packet p;
p[0] = (0x1e << 3) + 1;
p[1] = 0;
for(unsigned n = 2; n < 16; n++) {
p[n] = memory::dmgrom.read(0x0104 + (i * 14) + (n - 2));
}
packet.add(p);
}
}
//
SuperGameboy::SuperGameboy() {
gameboy = new GameboyGambatte;
}
SuperGameboy::~SuperGameboy() {
delete gameboy;
}
};

44
src/chip/sgb/sgb.hpp Normal file
View File

@ -0,0 +1,44 @@
class Gameboy;
class SuperGameboy : public Memory {
public:
Gameboy *gameboy;
void enter();
struct Packet {
uint8_t data[16];
uint8_t& operator[](unsigned addr) { return data[addr & 15]; }
};
vector<Packet> packet;
struct MMIO {
unsigned r6000;
uint8_t r6003;
//$6004-$6007
uint8_t joypadid;
uint8_t joypad[4];
Packet r7000;
unsigned r7800;
} mmio;
uint8_t read(unsigned addr);
void write(unsigned addr, uint8_t data);
void init();
void enable();
void power();
void reset();
void unload();
SuperGameboy();
~SuperGameboy();
protected:
uint64_t multiplier;
uint64_t counter;
void command_1e();
};
extern SuperGameboy sgb;

View File

@ -1,8 +1,8 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#define SPC7110_CPP
#include "spc7110.hpp"
#define SPC7110_CPP
namespace SNES {
#include "decomp.cpp"
const unsigned SPC7110::months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
@ -670,3 +670,5 @@ void SPC7110::write(unsigned addr, uint8 data) {
SPC7110::SPC7110() {
}
};

View File

@ -1,6 +1,7 @@
#include <../base.hpp>
#include <../cart/cart.hpp>
#include "srtc.hpp"
#define SRTC_CPP
namespace SNES {
const unsigned SRTC::months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
@ -224,3 +225,5 @@ void SRTC::mmio_write(unsigned addr, uint8 data) {
SRTC::SRTC() {
}
};

View File

@ -1,7 +1,8 @@
#include <../base.hpp>
#define ST010_CPP
#include "st010.hpp"
#define ST010_CPP
namespace SNES {
#include "st010_data.hpp"
#include "st010_op.cpp"
@ -85,3 +86,5 @@ void ST010::write(unsigned addr, uint8 data) {
ram[0x0021] &= ~0x80;
}
}
};

View File

@ -1,5 +1,8 @@
#include <../base.hpp>
#define CPUCORE_CPP
namespace SNES {
#include "opcode_algorithms.cpp"
#include "opcode_functions.cpp"
#include "opcode_tables.cpp"
@ -43,3 +46,5 @@ alwaysinline void CPUcore::op_io_cond6(uint16 addr) {
CPUcore::CPUcore() {
initialize_opcode_table();
}
};

View File

@ -383,4 +383,6 @@ void op_per_e();
void op_per_n();
@endmacro
//
@include "opcode_list.bpp"

View File

@ -1,8 +1,10 @@
#include <../base.hpp>
#define CPU_CPP
#define CPU_CPP
namespace SNES {
void CPU::power() {
cpu_version = snes.config.cpu.version;
cpu_version = config.cpu.version;
}
void CPU::reset() {
@ -13,3 +15,5 @@ CPU::CPU() {
CPU::~CPU() {
}
};

View File

@ -42,7 +42,7 @@ void sCPU::mmio_w4016(uint8 data) {
status.joypad_strobe_latch = !!(data & 1);
if(status.joypad_strobe_latch == 1) {
snes.input.poll();
system.input.poll();
}
}
@ -54,7 +54,7 @@ void sCPU::mmio_w4016(uint8 data) {
//realtime or buffered status of joypadN.b
uint8 sCPU::mmio_r4016() {
uint8 r = regs.mdr & 0xfc;
r |= snes.input.port_read(0) & 3;
r |= system.input.port_read(0) & 3;
return r;
}
@ -64,7 +64,7 @@ uint8 sCPU::mmio_r4016() {
//1-0 = Joypad serial data
uint8 sCPU::mmio_r4017() {
uint8 r = (regs.mdr & 0xe0) | 0x1c;
r |= snes.input.port_read(1) & 3;
r |= system.input.port_read(1) & 3;
return r;
}
@ -93,7 +93,7 @@ void sCPU::mmio_w4203(uint8 data) {
status.r4216 = status.mul_a * status.mul_b;
status.alu_lock = true;
event.enqueue(snes.config.cpu.alu_mul_delay, EventAluLockRelease);
event.enqueue(config.cpu.alu_mul_delay, EventAluLockRelease);
}
//WRDIVL
@ -113,7 +113,7 @@ void sCPU::mmio_w4206(uint8 data) {
status.r4216 = (status.div_b) ? status.div_a % status.div_b : status.div_a;
status.alu_lock = true;
event.enqueue(snes.config.cpu.alu_div_delay, EventAluLockRelease);
event.enqueue(config.cpu.alu_div_delay, EventAluLockRelease);
}
//HTIMEL

View File

@ -1,7 +1,9 @@
#include <../base.hpp>
#define SCPU_CPP
#include <nall/priorityqueue.hpp>
#define SCPU_CPP
namespace SNES {
priority_queue<unsigned> event(512, bind(&sCPU::queue_event, &cpu));
#include "dma/dma.cpp"
@ -94,3 +96,5 @@ sCPU::sCPU() {
sCPU::~sCPU() {
}
};

View File

@ -3,8 +3,8 @@
void sCPU::run_auto_joypad_poll() {
uint16 joy1 = 0, joy2 = 0, joy3 = 0, joy4 = 0;
for(unsigned i = 0; i < 16; i++) {
uint8 port0 = snes.input.port_read(0);
uint8 port1 = snes.input.port_read(1);
uint8 port0 = system.input.port_read(0);
uint8 port1 = system.input.port_read(1);
joy1 |= (port0 & 1) ? (0x8000 >> i) : 0;
joy2 |= (port1 & 1) ? (0x8000 >> i) : 0;

View File

@ -14,7 +14,7 @@ void sCPU::add_clocks(unsigned clocks) {
while(ticks--) {
ppu.tick();
if((ppu.hcounter() & 2) == 0) {
snes.input.tick();
system.input.tick();
} else {
poll_interrupts();
}
@ -44,7 +44,7 @@ void sCPU::scanline() {
}
if(status.auto_joypad_poll == true && ppu.vcounter() == (ppu.overscan() == false ? 227 : 242)) {
snes.input.poll();
system.input.poll();
run_auto_joypad_poll();
}
}

View File

@ -66,6 +66,8 @@ software which is ordinarily not compatible with this license, such as the GPL.
<table border="1" cellpadding="3">
<tr><td><b>Name</b></td><td><b>License</b></td><td><b>Author(s)</b></td></tr>
<tr><td>gambatte Gameboy emulator</td><td>GPL 2</td><td>Sindre Aamas</td></tr>
<tr><td>Cx4 emulator</td><td></td><td>anomie, Kris Bleakley, Nach, zsKnight</td></tr>
<tr><td>DSP-1 emulator</td><td></td><td>Andreas Naive, John Weidman, Kris Bleakley, neviksti</td></tr>
<tr><td>DSP-2 emulator</td><td></td><td>Kris Bleakley</td></tr>

View File

@ -1,5 +1,7 @@
#include <../base.hpp>
#define ADSP_CPP
#define ADSP_CPP
namespace SNES {
#include "adsp_tables.cpp"
@ -580,10 +582,12 @@ int32 fir_samplel, fir_sampler;
msampler = sclamp<16>(msampler);
}
snes.audio.update(msamplel, msampler);
system.audio.dsp_sample(msamplel, msampler);
scheduler.addclocks_dsp(32 * 3 * 8);
scheduler.sync_dspsmp();
}
aDSP::aDSP() {}
aDSP::~aDSP() {}
};

View File

@ -106,7 +106,7 @@ void sDSP::echo_27() {
}
//output sample to DAC
snes.audio.update(outl, outr);
system.audio.dsp_sample(outl, outr);
}
void sDSP::echo_28() {

View File

@ -8,6 +8,7 @@
#include <../base.hpp>
#define SDSP_CPP
namespace SNES {
#define REG(n) state.regs[r_##n]
#define VREG(n) state.regs[v.vidx + v_##n]
@ -324,3 +325,5 @@ sDSP::sDSP() {
sDSP::~sDSP() {
}
};

View File

@ -1,25 +1,31 @@
#include "cheat/cheat.hpp"
namespace SNES {
#include "cheat/cheat.hpp"
#include "memory/memory.hpp"
#include "memory/smemory/smemory.hpp"
#include "memory/memory.hpp"
#include "memory/smemory/smemory.hpp"
#include "cpu/cpu.hpp"
#include "cpu/core/core.hpp"
#include "cpu/scpu/scpu.hpp"
#include "cpu/cpu.hpp"
#include "cpu/core/core.hpp"
#include "cpu/scpu/scpu.hpp"
#include "ppu/ppu.hpp"
#include "ppu/bppu/bppu.hpp"
#include "smp/smp.hpp"
#include "smp/core/core.hpp"
#include "smp/ssmp/ssmp.hpp"
#include "smp/smp.hpp"
#include "smp/ssmp/ssmp.hpp"
#include "ppu/ppu.hpp"
#include "ppu/bppu/bppu.hpp"
#include "dsp/dsp.hpp"
#include "dsp/sdsp/sdsp.hpp"
#include "dsp/dsp.hpp"
#include "dsp/sdsp/sdsp.hpp"
extern BUSCORE bus;
extern CPUCORE cpu;
extern SMPCORE smp;
extern DSPCORE dsp;
extern PPUCORE ppu;
extern BUSCORE bus;
extern CPUCORE cpu;
extern SMPCORE smp;
extern DSPCORE dsp;
extern PPUCORE ppu;
#include "snes/snes.hpp"
#include "system/system.hpp"
#include "chip/chip.hpp"
#include "cartridge/cartridge.hpp"
}

339
src/lib/libgambatte/COPYING Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -0,0 +1,69 @@
cc = g++
cflags = -O2 -fomit-frame-pointer -Wall -Wextra
cflags += -fno-exceptions -fno-rtti
cflags += -DHAVE_STDINT_H -DCHAR_WIDTH_8
cflags += -Isrc -Iinclude -Icommon
headers = src/*.h src/file/*.h src/sound/*.h src/video/*.h src/video/filters/*.h
headers += include/*.h
headers += common/*.h common/resample/*.h
source = \
src/bitmap_font.cpp \
src/colorconversion.cpp \
src/cpu.cpp \
src/gambatte.cpp \
src/initstate.cpp \
src/interrupter.cpp \
src/memory.cpp \
src/rtc.cpp \
src/sound.cpp \
src/state_osd_elements.cpp \
src/statesaver.cpp \
src/video.cpp \
src/sound/channel1.cpp \
src/sound/channel2.cpp \
src/sound/channel3.cpp \
src/sound/channel4.cpp \
src/sound/duty_unit.cpp \
src/sound/envelope_unit.cpp \
src/sound/length_counter.cpp \
src/video/basic_add_event.cpp \
src/video/break_event.cpp \
src/video/irq_event.cpp \
src/video/ly_counter.cpp \
src/video/lyc_irq.cpp \
src/video/m3_extra_cycles.cpp \
src/video/mode3_event.cpp \
src/video/mode0_irq.cpp \
src/video/mode1_irq.cpp \
src/video/mode2_irq.cpp \
src/video/sc_reader.cpp \
src/video/scx_reader.cpp \
src/video/sprite_mapper.cpp \
src/video/we_master_checker.cpp \
src/video/we.cpp \
src/video/wx_reader.cpp \
src/video/wy.cpp \
src/video/filters/catrom2x.cpp \
src/video/filters/catrom3x.cpp \
src/video/filters/kreed2xsai.cpp \
src/video/filters/maxsthq2x.cpp \
src/video/filters/maxsthq3x.cpp \
src/file/file.cpp \
all: build;
clean:
-@rm obj/*.o
-@rm libgambatte.a
$(foreach item,$(source),$(eval obj/$(notdir $(basename $(item))).o: $(item) $(headers)))
objects := $(foreach item,$(source),obj/$(notdir $(basename $(item))).o)
%.o: $<
$(cc) -o $@ -c $< $(cflags)
build: $(objects)
ar rcs libgambatte.a $(objects)

130
src/lib/libgambatte/README Normal file
View File

@ -0,0 +1,130 @@
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Copyright (C) 2007 by Sindre Aamås
aamas@stud.ntnu.no
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
About
--------------------------------------------------------------------------------
Gambatte is an accuracy-focused, open-source, cross-platform
Game Boy Color emulator written in C++. It is based on hundreds of
corner case hardware tests, as well as previous documentation and reverse
engineering efforts.
The core emulation code is contained in a separate library back-end
(libgambatte) written in platform-independent C++. There is currently a GUI
front-end (gambatte_qt) using Trolltech's Qt4 toolkit, and a simple command-line
SDL front-end (gambatte_sdl).
The GUI front-end contains platform-specific extensions for video, sound and
timers. It should work on MS Windows, Linux/BSD/UNIX-like OSes, and Mac OS X.
The SDL front-end should be usable on all platforms with a working SDL port. It
should also be quite trivial to create new (simple) front-ends (note that the
library API should in no way be considered stable).
Usage
--------------------------------------------------------------------------------
You will have to supply Gambatte with a ROM image file of the GB/GBC
program/game you'd like to run/play, either as a command-line argument to
gambatte_sdl, or through the File->Open... menu in gambatte_qt.
gambatte_sdl keyboard commands:
TAB - fast-forward
Ctrl-f - toggle full screen
Ctrl-r - reset
F5 - save state
F6 - previous state slot
F7 - next state slot
F8 - load state
0 to 9 - select state slot 0 to 9
Default key mapping:
Up: Up
Down: Down
Left: Left
Right: Right
A: D
B: C
Start: Return
Select: Shift
Compiling
--------------------------------------------------------------------------------
Building Gambatte from source code can be done by executing the
build_<qt/sdl>.sh scripts for the qt/sdl front-ends respectively, or by issueing
the correct build command (either 'scons' or 'qmake && make') in the top-level
subdirectories (libgambatte will have to be built first). The clean.sh script
can be executed to remove all generated files after a compile (including
binaries).
Requirements for building libgambatte:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- SCons.
- optionally zlib
Requirements for building gambatte_sdl:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- SDL headers and library.
- SCons.
(- libgambatte.)
Requirements for building gambatte_qt:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- Qt4 (Core, GUI, OpenGL) headers and library.
- Qmake and make (GNU Make should work).
- Platform-specific requirements:
* MS Windows:
- Win32 API headers and libraries.
- DirectSound and DirectDraw7 headers and libraries.
- Direct3D9 headers
* Linux/BSD/UNIX-like OSes:
- POSIX/UNIX headers (unistd.h, fcntl.h, sys/ioctl.h, sys/time.h, sys/shm.h).
- Open Sound System header (sys/soundcard.h).
- X11 Xlib, XVideo, XRandR and XShm headers and libraries.
- Alsa headers and library (Linux only).
* Max OS X:
- Recent Mac OS X SDK (Panther Xcode/SDK should work)
(- libgambatte.)
Installing after a compile simply amounts to copying the generated binary
(either gambatte_qt/bin/gambatte_qt<.exe> or gambatte_sdl/gambatte_sdl<.exe>)
to wherever you'd like to keep it.
Thanks
--------------------------------------------------------------------------------
Derek Liauw Kie Fa (Kreed)
Gilles Vollant
Jeff Frohwein
Jonathan Gevaryahu (Lord Nightmare)
kOOPa
Marat Fayzullin
Martin Korth (nocash)
Maxim Stepin (MaxSt)
Nach
Pan of Anthrox
Pascal Felber
Paul Robson
SDL
Shay Green (blargg)
The OpenGL Extension Wrangler Library
--------------------------------------------------------------------------------
Game Boy and Game Boy Color are registered trademarks of
Nintendo of America Inc.
Gambatte is not affiliated with or endorsed by any of the companies mentioned.

View File

@ -0,0 +1,56 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "adaptivesleep.h"
usec_t AdaptiveSleep::sleepUntil(usec_t base, usec_t inc) {
usec_t now = getusecs();
usec_t diff = now - base;
if (diff >= inc)
return diff - inc;
diff = inc - diff;
if (diff > oversleep + oversleepVar) {
diff -= oversleep + oversleepVar;
usecsleep(diff);
const usec_t ideal = now + diff;
now = getusecs();
{
usec_t curOversleep = now - ideal;
if (negate(curOversleep) < curOversleep)
curOversleep = 0;
oversleepVar = (oversleepVar * 15 + (curOversleep < oversleep ? oversleep - curOversleep : curOversleep - oversleep)) >> 4;
oversleep = (oversleep * 15 + curOversleep) >> 4;
}
noSleep = 60;
} else if (--noSleep == 0) {
noSleep = 60;
oversleep = oversleepVar = 0;
}
while (now - base < inc)
now = getusecs();
return 0;
}

View File

@ -0,0 +1,34 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef ADAPTIVE_SLEEP_H
#define ADAPTIVE_SLEEP_H
#include "usec.h"
class AdaptiveSleep {
usec_t oversleep;
usec_t oversleepVar;
unsigned noSleep;
public:
AdaptiveSleep() : oversleep(0), oversleepVar(0), noSleep(60) {}
usec_t sleepUntil(usec_t base, usec_t inc);
};
#endif

View File

@ -0,0 +1,40 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef ARRAY_H
#define ARRAY_H
#include <cstddef>
template<typename T>
class Array {
T *a;
std::size_t sz;
Array(const Array &ar);
public:
Array(const std::size_t size = 0) : a(size ? new T[size] : 0), sz(size) {}
~Array() { delete []a; }
void reset(const std::size_t size) { delete []a; a = size ? new T[size] : 0; sz = size; }
std::size_t size() const { return sz; }
operator T*() { return a; }
operator const T*() const { return a; }
};
#endif

View File

@ -0,0 +1,96 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "rateest.h"
#include <cstdlib>
void RateEst::SumQueue::reset() {
q.clear();
samples_ = usecs_ = 0;
}
void RateEst::SumQueue::push(const long samples, const usec_t usecs) {
q.push_back(pair_t(samples, usecs));
samples_ += samples;
usecs_ += usecs;
}
void RateEst::SumQueue::pop() {
const pair_t &f = q.front();
samples_ -= f.first;
usecs_ -= f.second;
q.pop_front();
}
static usec_t sampleUsecs(long samples, long rate) {
return static_cast<usec_t>((samples * 1000000.0f) / (rate ? rate : 1) + 0.5f);
}
static long limit(long est, const long reference) {
if (est > reference + (reference >> 6))
est = reference + (reference >> 6);
else if (est < reference - (reference >> 6))
est = reference - (reference >> 6);
return est;
}
void RateEst::init(long srate, long reference, const long maxSamplePeriod) {
maxPeriod = sampleUsecs(maxSamplePeriod, reference);
srate <<= UPSHIFT;
reference <<= UPSHIFT;
this->srate.est = limit(srate, reference);
this->srate.var = srate >> 12;
last = 0;
this->reference = reference;
samples = ((this->srate.est >> UPSHIFT) * 12) << 5;
usecs = 12000000 << 5;
sumq.reset();
}
void RateEst::feed(long samplesIn, const usec_t now) {
usec_t usecsIn = now - last;
if (last && usecsIn < maxPeriod) {
sumq.push(samplesIn, usecsIn);
while ((usecsIn = sumq.usecs()) > 100000) {
samplesIn = sumq.samples();
sumq.pop();
if (std::abs(static_cast<long>(samplesIn * (1000000.0f * UP) / usecsIn) - reference) < reference >> 1) {
samples += (samplesIn - sumq.samples()) << 5;
usecs += (usecsIn - sumq.usecs()) << 5;
long est = static_cast<long>(samples * (1000000.0f * UP) / usecs + 0.5f);
est = limit((srate.est * 31 + est + 16) >> 5, reference);
srate.var = (srate.var * 15 + std::abs(est - srate.est) + 8) >> 4;
srate.est = est;
if (usecs > 16000000 << 5) {
samples = (samples * 3 + 2) >> 2;
usecs = (usecs * 3 + 2) >> 2;
}
}
}
}
last = now;
}

View File

@ -0,0 +1,73 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RATEEST_H
#define RATEEST_H
#include "usec.h"
#include <deque>
#include <utility>
class RateEst {
public:
struct Result {
long est;
long var;
};
private:
class SumQueue {
typedef std::pair<long, usec_t> pair_t;
typedef std::deque<pair_t> q_t;
q_t q;
long samples_;
usec_t usecs_;
public:
SumQueue() : samples_(0), usecs_(0) {}
void reset();
long samples() const { return samples_; }
usec_t usecs() const { return usecs_; }
void push(long samples, usec_t usecs);
void pop();
};
enum { UPSHIFT = 5 };
enum { UP = 1 << UPSHIFT };
Result srate;
SumQueue sumq;
usec_t last;
usec_t usecs;
usec_t maxPeriod;
long reference;
long samples;
public:
RateEst(long srate = 0) { init(srate); }
RateEst(long srate, long reference) { init(srate, reference); }
void init(long srate) { init(srate, srate); }
void init(long srate, long reference) { init(srate, reference, reference); }
void init(long srate, long reference, long maxSamplePeriod);
void reset() { last = 0; }
void feed(long samples, usec_t usecs = getusecs());
const Result result() const { const Result res = { (srate.est + UP / 2) >> UPSHIFT, (srate.var + UP / 2) >> UPSHIFT }; return res; }
};
#endif

View File

@ -0,0 +1,100 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef BLACKMANSINC_H
#define BLACKMANSINC_H
#include "convoluter.h"
#include "subresampler.h"
#include "makesinckernel.h"
#include "cic4.h"
#include <cmath>
#include <cstdlib>
template<unsigned channels, unsigned phases>
class BlackmanSinc : public SubResampler {
PolyPhaseConvoluter<channels, phases> convoluters[channels];
short *kernel;
static double blackmanWin(const long i, const long M) {
static const double PI = 3.14159265358979323846;
return 0.42 - 0.5 * std::cos(2 * PI * i / M) + 0.08 * std::cos(4 * PI * i / M);
}
void init(unsigned div, unsigned phaseLen, double fc);
public:
enum { MUL = phases };
typedef Cic4<channels> Cic;
static float cicLimit() { return 4.7f; }
class RollOff {
static unsigned toTaps(const float rollOffWidth) {
static const float widthTimesTaps = 4.5f;
return std::ceil(widthTimesTaps / rollOffWidth);
}
static float toFc(const float rollOffStart, const int taps) {
static const float startToFcDeltaTimesTaps = 1.69f;
return startToFcDeltaTimesTaps / taps + rollOffStart;
}
public:
const unsigned taps;
const float fc;
RollOff(float rollOffStart, float rollOffWidth) : taps(toTaps(rollOffWidth)), fc(toFc(rollOffStart, taps)) {}
};
BlackmanSinc(unsigned div, unsigned phaseLen, double fc) { init(div, phaseLen, fc); }
BlackmanSinc(unsigned div, RollOff ro) { init(div, ro.taps, ro.fc); }
~BlackmanSinc() { delete[] kernel; }
std::size_t resample(short *out, const short *in, std::size_t inlen);
void adjustDiv(unsigned div);
unsigned mul() const { return MUL; }
unsigned div() const { return convoluters[0].div(); }
};
template<const unsigned channels, const unsigned phases>
void BlackmanSinc<channels, phases>::init(const unsigned div, const unsigned phaseLen, const double fc) {
kernel = new short[phaseLen * phases];
makeSincKernel(kernel, phases, phaseLen, fc, blackmanWin);
for (unsigned i = 0; i < channels; ++i)
convoluters[i].reset(kernel, phaseLen, div);
}
template<const unsigned channels, const unsigned phases>
std::size_t BlackmanSinc<channels, phases>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i)
samplesOut = convoluters[i].filter(out + i, in + i, inlen);
return samplesOut;
}
template<const unsigned channels, const unsigned phases>
void BlackmanSinc<channels, phases>::adjustDiv(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
convoluters[i].adjustDiv(div);
}
#endif

View File

@ -0,0 +1,118 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "chainresampler.h"
float ChainResampler::get2ChainMidRatio(const float ratio, const float rollOff) {
return std::sqrt(0.5f * rollOff * ratio) + 1;
}
float ChainResampler::get2ChainCost(const float ratio, const float rollOff, const float midRatio) {
return midRatio * ratio / ((midRatio - 1) * 2) + midRatio / rollOff;
}
float ChainResampler::get3ChainRatio1(float ratio1, const float rollOff, const float ratio) {
for (unsigned n = 8; n--;) {
ratio1 = std::sqrt(ratio - ratio / get3ChainRatio2(ratio1, rollOff)) + 1;
}
return ratio1;
}
float ChainResampler::get3ChainCost(const float ratio, const float rollOff, const float ratio1, const float ratio2) {
return ratio1 * ratio / ((ratio1 - 1) * 2) + ratio2 * ratio1 / ((ratio2 - 1) * 2) + ratio2 / rollOff;
}
std::size_t ChainResampler::reallocateBuffer() {
std::size_t bufSz[2] = { 0, 0 };
std::size_t inSz = periodSize;
int i = -1;
for (list_t::iterator it = list.begin(); it != list.end(); ++it) {
inSz = (inSz * (*it)->mul() - 1) / (*it)->div() + 1;
++i;
if (inSz > bufSz[i&1])
bufSz[i&1] = inSz;
}
if (inSz >= bufSz[i&1])
bufSz[i&1] = 0;
if (bufferSize < bufSz[0] + bufSz[1]) {
delete[] buffer;
buffer = (bufferSize = bufSz[0] + bufSz[1]) ? new short[bufferSize * channels] : NULL;
}
buffer2 = bufSz[1] ? buffer + bufSz[0] * channels : NULL;
return (maxOut_ = inSz);
}
void ChainResampler::adjustRate(const long inRate, const long outRate) {
unsigned long mul, div;
exactRatio(mul, div);
bigSinc->adjustDiv(static_cast<double>(inRate) * mul / (static_cast<double>(div / bigSinc->div()) * outRate) + 0.5);
reallocateBuffer();
setRate(inRate, outRate);
}
void ChainResampler::exactRatio(unsigned long &mul, unsigned long &div) const {
mul = 1;
div = 1;
for (list_t::const_iterator it = list.begin(); it != list.end(); ++it) {
mul *= (*it)->mul();
div *= (*it)->div();
}
}
std::size_t ChainResampler::resample(short *const out, const short *const in, std::size_t inlen) {
assert(inlen <= periodSize);
short *const buf = buffer != buffer2 ? buffer : out;
short *const buf2 = buffer2 ? buffer2 : out;
const short *inbuf = in;
short *outbuf = NULL;
for (list_t::iterator it = list.begin(); it != list.end(); ++it) {
outbuf = ++list_t::iterator(it) == list.end() ? out : (inbuf == buf ? buf2 : buf);
inlen = (*it)->resample(outbuf, inbuf, inlen);
inbuf = outbuf;
}
return inlen;
}
void ChainResampler::uninit() {
delete[] buffer;
buffer2 = buffer = NULL;
bufferSize = 0;
periodSize = 0;
bigSinc = NULL;
for (list_t::iterator it = list.begin(); it != list.end(); ++it)
delete *it;
list.clear();
}

View File

@ -0,0 +1,189 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CHAINRESAMPLER_H
#define CHAINRESAMPLER_H
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cstddef>
#include <list>
#include "subresampler.h"
#include "resampler.h"
#include "upsampler.h"
class ChainResampler : public Resampler {
enum { channels = 2 };
typedef std::list<SubResampler*> list_t;
list_t list;
SubResampler *bigSinc;
short *buffer;
short *buffer2;
std::size_t bufferSize;
std::size_t periodSize;
std::size_t maxOut_;
static float get1ChainCost(const float ratio, const float rollOff) {
return ratio / rollOff;
}
static float get2ChainMidRatio(float ratio, float rollOff);
static float get2ChainCost(float ratio, float rollOff, float midRatio);
static float get3ChainRatio2(const float ratio1, const float rollOff) {
return get2ChainMidRatio(ratio1, rollOff);
}
static float get3ChainRatio1(float ratio1, float rollOff, float ratio);
static float get3ChainCost(float ratio, float rollOff, float ratio1, float ratio2);
template<template<unsigned,unsigned> class Sinc>
std::size_t downinit(long inRate, long outRate, std::size_t periodSize);
std::size_t reallocateBuffer();
template<template<unsigned,unsigned> class Sinc>
std::size_t upinit(long inRate, long outRate, std::size_t periodSize);
public:
ChainResampler() : bigSinc(NULL), buffer(NULL), buffer2(NULL), bufferSize(0), periodSize(0) {}
~ChainResampler() { uninit(); }
void adjustRate(long inRate, long outRate);
void exactRatio(unsigned long &mul, unsigned long &div) const;
template<template<unsigned,unsigned> class Sinc>
std::size_t init(long inRate, long outRate, std::size_t periodSize);
std::size_t maxOut(std::size_t /*inlen*/) const { return maxOut_; }
std::size_t resample(short *out, const short *in, std::size_t inlen);
void uninit();
};
template<template<unsigned,unsigned> class Sinc>
std::size_t ChainResampler::init(const long inRate, const long outRate, const std::size_t periodSize) {
setRate(inRate, outRate);
if (outRate > inRate)
return upinit<Sinc>(inRate, outRate, periodSize);
else
return downinit<Sinc>(inRate, outRate, periodSize);
}
template<template<unsigned,unsigned> class Sinc>
std::size_t ChainResampler::downinit(const long inRate, const long outRate, const std::size_t periodSize) {
typedef Sinc<channels,2048> BigSinc;
typedef Sinc<channels,32> SmallSinc;
uninit();
this->periodSize = periodSize;
const float rollOff = std::max((outRate - 36000.0f + outRate - 40000.0f) / outRate, 0.2f);
double ratio = static_cast<double>(inRate) / outRate;
while (ratio >= BigSinc::cicLimit() * 2) {
const int div = std::min<int>(static_cast<int>(ratio / BigSinc::cicLimit()), BigSinc::Cic::MAX_DIV);
list.push_back(new typename BigSinc::Cic(div));
ratio /= div;
}
{
int div_2c = ratio * SmallSinc::MUL / get2ChainMidRatio(ratio, rollOff) + 0.5f;
double ratio_2c = ratio * SmallSinc::MUL / div_2c;
float cost_2c = get2ChainCost(ratio, rollOff, ratio_2c);
if (cost_2c < get1ChainCost(ratio, rollOff)) {
const int div1_3c = ratio * SmallSinc::MUL / get3ChainRatio1(ratio_2c, rollOff, ratio) + 0.5f;
const double ratio1_3c = ratio * SmallSinc::MUL / div1_3c;
const int div2_3c = ratio1_3c * SmallSinc::MUL / get3ChainRatio2(ratio1_3c, rollOff) + 0.5f;
const double ratio2_3c = ratio1_3c * SmallSinc::MUL / div2_3c;
if (get3ChainCost(ratio, rollOff, ratio1_3c, ratio2_3c) < cost_2c) {
list.push_back(new SmallSinc(div1_3c, typename SmallSinc::RollOff(0.5f / ratio, (ratio1_3c - 1) / ratio)));
ratio = ratio1_3c;
div_2c = div2_3c;
ratio_2c = ratio2_3c;
}
list.push_back(new SmallSinc(div_2c, typename SmallSinc::RollOff(0.5f / ratio, (ratio_2c - 1) / ratio)));
ratio = ratio_2c;
}
}
list.push_back(bigSinc = new BigSinc(BigSinc::MUL * ratio + 0.5,
typename BigSinc::RollOff(0.5f * (1 + std::max((outRate - 40000.0f) / outRate, 0.0f) - rollOff) / ratio, 0.5f * rollOff / ratio)));
return reallocateBuffer();
}
template<template<unsigned,unsigned> class Sinc>
std::size_t ChainResampler::upinit(const long inRate, const long outRate, const std::size_t periodSize) {
typedef Sinc<channels,2048> BigSinc;
typedef Sinc<channels,32> SmallSinc;
uninit();
this->periodSize = periodSize;
const float rollOff = std::max((inRate - 36000.0f) / inRate, 0.2f);
double ratio = static_cast<double>(outRate) / inRate;
// Spectral images above 20 kHz assumed inaudible
{
const int div = outRate / std::max(inRate, 40000l);
if (div >= 2) {
list.push_front(new Upsampler<channels>(div));
ratio /= div;
}
}
{
int div_2c = get2ChainMidRatio(ratio, rollOff) * SmallSinc::MUL / ratio + 0.5f;
double ratio_2c = ratio * div_2c / SmallSinc::MUL;
float cost_2c = get2ChainCost(ratio, rollOff, ratio_2c);
if (cost_2c < get1ChainCost(ratio, rollOff)) {
const int div1_3c = get3ChainRatio1(ratio_2c, rollOff, ratio) * SmallSinc::MUL / ratio + 0.5f;
const double ratio1_3c = ratio * div1_3c / SmallSinc::MUL;
const int div2_3c = get3ChainRatio2(ratio1_3c, rollOff) * SmallSinc::MUL / ratio1_3c + 0.5f;
const double ratio2_3c = ratio1_3c * div2_3c / SmallSinc::MUL;
if (get3ChainCost(ratio, rollOff, ratio1_3c, ratio2_3c) < cost_2c) {
list.push_front(new SmallSinc(div1_3c, typename SmallSinc::RollOff(0.5f / ratio1_3c, (ratio1_3c - 1) / ratio1_3c)));
ratio = ratio1_3c;
div_2c = div2_3c;
ratio_2c = ratio2_3c;
}
list.push_front(new SmallSinc(div_2c, typename SmallSinc::RollOff(0.5f / ratio_2c, (ratio_2c - 1) / ratio_2c)));
ratio = ratio_2c;
}
}
list.push_front(bigSinc = new BigSinc(BigSinc::MUL / ratio + 0.5, typename BigSinc::RollOff(0.5f * (1 - rollOff), 0.5f * rollOff)));
return reallocateBuffer();
}
#endif

View File

@ -0,0 +1,198 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CIC2_H
#define CIC2_H
#include "subresampler.h"
template<unsigned channels>
class Cic2Core {
// enum { BUFLEN = 64 };
// unsigned long buf[BUFLEN];
unsigned long sum1;
unsigned long sum2;
unsigned long prev1;
unsigned long prev2;
unsigned div_;
unsigned nextdivn;
// unsigned bufpos;
public:
Cic2Core(const unsigned div = 2) {
reset(div);
}
unsigned div() const { return div_; }
std::size_t filter(short *out, const short *in, std::size_t inlen);
void reset(unsigned div);
};
template<const unsigned channels>
void Cic2Core<channels>::reset(const unsigned div) {
sum2 = sum1 = 0;
prev2 = prev1 = 0;
this->div_ = div;
nextdivn = div;
// bufpos = div - 1;
}
template<const unsigned channels>
std::size_t Cic2Core<channels>::filter(short *out, const short *const in, std::size_t inlen) {
// const std::size_t produced = (inlen + div_ - (bufpos + 1)) / div_;
const std::size_t produced = (inlen + div_ - nextdivn) / div_;
const long mul = 0x10000 / (div_ * div_); // trouble if div is too large, may be better to only support power of 2 div
const short *s = in;
/*unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
while (inlen >> 2) {
unsigned n = (inlen < BUFLEN ? inlen >> 2 : BUFLEN >> 2);
const unsigned end = n * 4;
unsigned i = 0;
do {
unsigned long s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
buf[i++] = sm2 += s1;
buf[i++] = sm2 += sm1;
s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
buf[i++] = sm2 += s1;
buf[i++] = sm2 += sm1;
} while (--n);
while (bufpos < end) {
const unsigned long out2 = buf[bufpos] - prev2;
prev2 = buf[bufpos];
bufpos += div_;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= end;
inlen -= end;
}
if (inlen) {
unsigned n = inlen;
unsigned i = 0;
do {
sm1 += static_cast<long>(*s);
s += channels;
buf[i++] = sm2 += sm1;
} while (--n);
while (bufpos < inlen) {
const unsigned long out2 = buf[bufpos] - prev2;
prev2 = buf[bufpos];
bufpos += div_;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= inlen;
}
sum1 = sm1;
sum2 = sm2;*/
unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
if (inlen >= nextdivn) {
unsigned divn = nextdivn;
std::size_t n = produced;
do {
do {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
} while (--divn);
const unsigned long out2 = sm2 - prev2;
prev2 = sm2;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
divn = div_;
} while (--n);
nextdivn = div_;
}
{
unsigned divn = (in + inlen * channels - s) / channels;
nextdivn -= divn;
while (divn--) {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
}
}
sum1 = sm1;
sum2 = sm2;
return produced;
}
template<unsigned channels>
class Cic2 : public SubResampler {
Cic2Core<channels> cics[channels];
public:
enum { MAX_DIV = 64 };
Cic2(unsigned div);
std::size_t resample(short *out, const short *in, std::size_t inlen);
unsigned mul() const { return 1; }
unsigned div() const { return cics[0].div(); }
};
template<const unsigned channels>
Cic2<channels>::Cic2(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
cics[i].reset(div);
}
template<const unsigned channels>
std::size_t Cic2<channels>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i) {
samplesOut = cics[i].filter(out + i, in + i, inlen);
}
return samplesOut;
}
#endif

View File

@ -0,0 +1,382 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CIC3_H
#define CIC3_H
#include "subresampler.h"
template<unsigned channels>
class Cic3Core {
// enum { BUFLEN = 64 };
// unsigned long buf[BUFLEN];
unsigned long sum1;
unsigned long sum2;
unsigned long sum3;
unsigned long prev1;
unsigned long prev2;
unsigned long prev3;
unsigned div_;
unsigned nextdivn;
// unsigned bufpos;
public:
Cic3Core(const unsigned div = 1) {
reset(div);
}
unsigned div() const { return div_; }
std::size_t filter(short *out, const short *in, std::size_t inlen);
void reset(unsigned div);
};
template<const unsigned channels>
void Cic3Core<channels>::reset(const unsigned div) {
sum3 = sum2 = sum1 = 0;
prev3 = prev2 = prev1 = 0;
this->div_ = div;
nextdivn = div;
// bufpos = div - 1;
}
template<const unsigned channels>
std::size_t Cic3Core<channels>::filter(short *out, const short *const in, std::size_t inlen) {
// const std::size_t produced = (inlen + div_ - (bufpos + 1)) / div_;
const std::size_t produced = (inlen + div_ - nextdivn) / div_;
const long mul = 0x10000 / (div_ * div_ * div_); // trouble if div is too large, may be better to only support power of 2 div
const short *s = in;
/*unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
while (inlen >> 1) {
unsigned n = (inlen < BUFLEN ? inlen >> 1 : BUFLEN >> 1);
const unsigned end = n * 2;
unsigned i = 0;
do {
unsigned long s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
unsigned long s2 = sm2 += s1;
sm2 += sm1;
buf[i++] = sm3 += s2;
buf[i++] = sm3 += sm2;
} while (--n);
while (bufpos < end) {
const unsigned long out3 = buf[bufpos] - prev3;
prev3 = buf[bufpos];
bufpos += div_;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= end;
inlen -= end;
}
if (inlen) {
unsigned n = inlen;
unsigned i = 0;
do {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
buf[i++] = sm3 += sm2;
} while (--n);
while (bufpos < inlen) {
const unsigned long out3 = buf[bufpos] - prev3;
prev3 = buf[bufpos];
bufpos += div_;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= inlen;
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;*/
unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
if (inlen >= nextdivn) {
unsigned divn = nextdivn;
std::size_t n = produced;
do {
do {
sm1 += static_cast<long>(*s);
sm2 += sm1;
sm3 += sm2;
s += channels;
} while (--divn);
const unsigned long out3 = sm3 - prev3;
prev3 = sm3;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
divn = div_;
} while (--n);
nextdivn = div_;
}
{
unsigned divn = (in + inlen * channels - s) / channels;
nextdivn -= divn;
while (divn--) {
sm1 += static_cast<long>(*s);
sm2 += sm1;
sm3 += sm2;
s += channels;
}
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;
return produced;
}
/*template<unsigned channels>
class Cic3EvenOddCore {
unsigned long sum1;
unsigned long sum2;
unsigned long sum3;
unsigned long prev1;
unsigned long prev2;
unsigned long prev3;
unsigned div_;
unsigned nextdivn;
static int getMul(unsigned div) {
return 0x10000 / (div * div * div); // trouble if div is too large, may be better to only support power of 2 div
}
void filterEven(short *out, const short *s, std::size_t n);
void filterOdd(short *out, const short *s, std::size_t n);
public:
Cic3EvenOddCore(const unsigned div = 2) {
reset(div);
}
unsigned div() const { return div_; }
std::size_t filter(short *out, const short *in, std::size_t inlen);
void reset(unsigned div);
};
template<const unsigned channels>
void Cic3EvenOddCore<channels>::reset(const unsigned div) {
sum3 = sum2 = sum1 = 0;
prev3 = prev2 = prev1 = 0;
this->div_ = div;
nextdivn = div;
}
template<const unsigned channels>
void Cic3EvenOddCore<channels>::filterEven(short *out, const short *s, std::size_t n) {
const int mul = getMul(div_);
unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
while (n--) {
{
unsigned sn = div_ >> 1;
do {
unsigned long s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
unsigned long s2 = sm2 += s1;
sm2 += sm1;
sm3 += s2;
sm3 += sm2;
} while (--sn);
}
const unsigned long out3 = sm3 - prev3;
prev3 = sm3;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;
}
template<const unsigned channels>
void Cic3EvenOddCore<channels>::filterOdd(short *out, const short *s, std::size_t n) {
const int mul = getMul(div_);
unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
while (n--) {
{
unsigned sn = div_ >> 1;
do {
unsigned long s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
unsigned long s2 = sm2 += s1;
sm2 += sm1;
sm3 += s2;
sm3 += sm2;
} while (--sn);
}
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
sm3 += sm2;
const unsigned long out3 = sm3 - prev3;
prev3 = sm3;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;
}
template<const unsigned channels>
std::size_t Cic3EvenOddCore<channels>::filter(short *out, const short *const in, std::size_t inlen) {
short *const outStart = out;
const short *s = in;
if (inlen >= nextdivn) {
{
{
unsigned divn = nextdivn;
do {
sum1 += static_cast<long>(*s);
s += channels;
sum2 += sum1;
sum3 += sum2;
} while (--divn);
}
const unsigned long out3 = sum3 - prev3;
prev3 = sum3;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * getMul(div_) / 0x10000;
prev1 = out2;
out += channels;
}
std::size_t n = (inlen - nextdivn) / div_;
if (div_ & 1)
filterOdd(out, s, n);
else
filterEven(out, s, n);
s += n * div_ * channels;
out += n * channels;
nextdivn = div_;
}
{
unsigned divn = inlen - (s - in) / channels;
nextdivn -= divn;
while (divn--) {
sum1 += static_cast<long>(*s);
s += channels;
sum2 += sum1;
sum3 += sum2;
}
}
return (out - outStart) / channels;
}*/
template<unsigned channels>
class Cic3 : public SubResampler {
Cic3Core<channels> cics[channels];
public:
enum { MAX_DIV = 23 };
Cic3(unsigned div);
std::size_t resample(short *out, const short *in, std::size_t inlen);
unsigned mul() const { return 1; }
unsigned div() const { return cics[0].div(); }
};
template<const unsigned channels>
Cic3<channels>::Cic3(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
cics[i].reset(div);
}
template<const unsigned channels>
std::size_t Cic3<channels>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i) {
samplesOut = cics[i].filter(out + i, in + i, inlen);
}
return samplesOut;
}
#endif

View File

@ -0,0 +1,237 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CIC4_H
#define CIC4_H
#include "subresampler.h"
template<unsigned channels>
class Cic4Core {
enum { BUFLEN = 64 };
unsigned long buf[BUFLEN];
unsigned long sum1;
unsigned long sum2;
unsigned long sum3;
unsigned long sum4;
unsigned long prev1;
unsigned long prev2;
unsigned long prev3;
unsigned long prev4;
unsigned div_;
// unsigned nextdivn;
unsigned bufpos;
public:
Cic4Core(const unsigned div = 1) {
reset(div);
}
unsigned div() const { return div_; }
std::size_t filter(short *out, const short *in, std::size_t inlen);
void reset(unsigned div);
};
template<const unsigned channels>
void Cic4Core<channels>::reset(const unsigned div) {
sum4 = sum3 = sum2 = sum1 = 0;
prev4 = prev3 = prev2 = prev1 = 0;
this->div_ = div;
// nextdivn = div;
bufpos = div - 1;
}
template<const unsigned channels>
std::size_t Cic4Core<channels>::filter(short *out, const short *const in, std::size_t inlen) {
const std::size_t produced = (inlen + div_ - (bufpos + 1)) / div_;
// const std::size_t produced = (inlen + div_ - nextdivn) / div_;
const long mul = 0x10000 / (div_ * div_ * div_ * div_); // trouble if div is too large, may be better to only support power of 2 div
const short *s = in;
unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
unsigned long sm4 = sum4;
while (inlen >> 2) {
unsigned n = (inlen < BUFLEN ? inlen >> 2 : BUFLEN >> 2);
const unsigned end = n * 4;
unsigned i = 0;
do {
unsigned long s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
unsigned long s2 = sm2 += s1;
sm2 += sm1;
unsigned long s3 = sm3 += s2;
sm3 += sm2;
buf[i++] = sm4 += s3;
buf[i++] = sm4 += sm3;
s1 = sm1 += static_cast<long>(*s);
s += channels;
sm1 += static_cast<long>(*s);
s += channels;
s2 = sm2 += s1;
sm2 += sm1;
s3 = sm3 += s2;
sm3 += sm2;
buf[i++] = sm4 += s3;
buf[i++] = sm4 += sm3;
} while (--n);
while (bufpos < end) {
const unsigned long out4 = buf[bufpos] - prev4;
prev4 = buf[bufpos];
bufpos += div_;
const unsigned long out3 = out4 - prev3;
prev3 = out4;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= end;
inlen -= end;
}
if (inlen) {
unsigned n = inlen;
unsigned i = 0;
do {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
sm3 += sm2;
buf[i++] = sm4 += sm3;
} while (--n);
while (bufpos < inlen) {
const unsigned long out4 = buf[bufpos] - prev4;
prev4 = buf[bufpos];
bufpos += div_;
const unsigned long out3 = out4 - prev3;
prev3 = out4;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
}
bufpos -= inlen;
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;
sum4 = sm4;
/*unsigned long sm1 = sum1;
unsigned long sm2 = sum2;
unsigned long sm3 = sum3;
unsigned long sm4 = sum4;
if (produced) {
unsigned divn = nextdivn;
std::size_t n = produced;
do {
do {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
sm3 += sm2;
sm4 += sm3;
} while (--divn);
const unsigned long out4 = sm4 - prev4;
prev4 = sm4;
const unsigned long out3 = out4 - prev3;
prev3 = out4;
const unsigned long out2 = out3 - prev2;
prev2 = out3;
*out = static_cast<long>(out2 - prev1) * mul / 0x10000;
prev1 = out2;
out += channels;
divn = div_;
} while (--n);
nextdivn = div_;
}
{
unsigned divn = (in + inlen * channels - s) / channels;
nextdivn -= divn;
while (divn--) {
sm1 += static_cast<long>(*s);
s += channels;
sm2 += sm1;
sm3 += sm2;
sm4 += sm3;
}
}
sum1 = sm1;
sum2 = sm2;
sum3 = sm3;
sum4 = sm4;*/
return produced;
}
template<unsigned channels>
class Cic4 : public SubResampler {
Cic4Core<channels> cics[channels];
public:
enum { MAX_DIV = 13 };
Cic4(unsigned div);
std::size_t resample(short *out, const short *in, std::size_t inlen);
unsigned mul() const { return 1; }
unsigned div() const { return cics[0].div(); }
};
template<const unsigned channels>
Cic4<channels>::Cic4(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
cics[i].reset(div);
}
template<const unsigned channels>
std::size_t Cic4<channels>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i) {
samplesOut = cics[i].filter(out + i, in + i, inlen);
}
return samplesOut;
}
#endif

View File

@ -0,0 +1,156 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CONVOLUTER_H
#define CONVOLUTER_H
#include <algorithm>
#include <cstring>
template<unsigned channels, unsigned phases>
class PolyPhaseConvoluter {
const short *kernel;
short *prevbuf;
unsigned phaseLen;
unsigned div_;
unsigned x_;
public:
PolyPhaseConvoluter() : kernel(NULL), prevbuf(NULL), phaseLen(0), div_(0), x_(0) {}
PolyPhaseConvoluter(const short *kernel, unsigned phaseLen, unsigned div) { reset(kernel, phaseLen, div); }
~PolyPhaseConvoluter() { delete[] prevbuf; }
void reset(const short *kernel, unsigned phaseLen, unsigned div);
std::size_t filter(short *out, const short *in, std::size_t inlen);
void adjustDiv(const unsigned div) { this->div_ = div; }
unsigned div() const { return div_; }
};
template<const unsigned channels, const unsigned phases>
void PolyPhaseConvoluter<channels, phases>::reset(const short *const kernel, const unsigned phaseLen, const unsigned div) {
this->kernel = kernel;
this->phaseLen = phaseLen;
this->div_ = div;
x_ = 0;
delete[] prevbuf;
prevbuf = new short[phaseLen];
std::fill(prevbuf, prevbuf + phaseLen, 0);
}
template<const unsigned channels, const unsigned phases>
std::size_t PolyPhaseConvoluter<channels, phases>::filter(short *out, const short *const in, std::size_t inlen) {
if (!kernel || !inlen)
return 0;
/*for (std::size_t x = 0; x < inlen + M; ++x) {
const int end = x < inlen ? M + 1 : inlen + M - x;
int j = x < M ? M - x : 0;
j += (phases - (x - M + j) % phases) % phases; // adjust j so we don't start on a virtual 0 sample
for (; j < end; j += phases) {
buffer[x] += kernel[j] * start[(x - M + j) / phases];
}
}*/
/*for (std::size_t x = 0; x < inlen + M; ++x) {
const int end = x < inlen ? M + 1 : inlen + M - x;
int j = x < M ? M - x : 0;
j += (phases - (x - M + j) % phases) % phases; // adjust j so we don't start on a virtual 0 sample
const short *k = kernel + (j % phases) * phaseLen + j / phases;
const short *s = start + (x - M + j) / phases;
int n = ((end - j) + phases - 1) / phases;
do {
buffer[x] += *k++ * *s++;
} while (--n);
}*/
const std::size_t M = phaseLen * phases - 1;
inlen *= phases;
std::size_t x = x_;
for (; x < (M < inlen ? M : inlen); x += div_) {
long acc = 0;
const unsigned phase = (phases - (x + 1) % phases) % phases; // adjust phase so we don't start on a virtual 0 sample
const short *s = prevbuf + (x + 1 + phase) / phases;
const short *k = kernel + phase * phaseLen;
unsigned n = prevbuf + phaseLen - s;
while (n--) {
acc += *k++ * *s++;
}
s = in;
n = x / phases + 1;
do {
acc += *k++ * *s;
s += channels;
} while (--n);
*out = acc / 0x10000;
out += channels;
}
for (; x < inlen; x += div_) {
long acc = 0;
const unsigned phase = (phases - (x - M) % phases) % phases; // adjust phase so we don't start on a virtual 0 sample
const short *s = in + ((x - M + phase) / phases) * channels;
const short *k = kernel + phase * phaseLen;
// unsigned n = (M + 1/* - phase + phases - 1*/) / phases;
unsigned n = phaseLen;
do {
acc += *k++ * *s;
s += channels;
} while (--n);
*out = acc / 0x10000;
out += channels;
}
const std::size_t produced = (x - x_) / div_;
x_ = x - inlen;
inlen /= phases;
{
short *p = prevbuf;
const short *s = in + (inlen - phaseLen) * channels;
unsigned n = phaseLen;
if (inlen < phaseLen) {
const unsigned i = phaseLen - inlen;
std::memmove(p, p + inlen, i * sizeof(short));
p += i;
n -= i;
s = in;
}
do {
*p++ = *s;
s += channels;
} while (--n);
}
return produced;
}
#endif

View File

@ -0,0 +1,100 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef HAMMINGSINC_H
#define HAMMINGSINC_H
#include "convoluter.h"
#include "subresampler.h"
#include "makesinckernel.h"
#include "cic3.h"
#include <cmath>
#include <cstdlib>
template<unsigned channels, unsigned phases>
class HammingSinc : public SubResampler {
PolyPhaseConvoluter<channels, phases> convoluters[channels];
short *kernel;
static double hammingWin(const long i, const long M) {
static const double PI = 3.14159265358979323846;
return 0.53836 - 0.46164 * std::cos(2 * PI * i / M);
}
void init(unsigned div, unsigned phaseLen, double fc);
public:
enum { MUL = phases };
typedef Cic3<channels> Cic;
static float cicLimit() { return 4.2f; }
class RollOff {
static unsigned toTaps(const float rollOffWidth) {
static const float widthTimesTaps = 3.0f;
return std::ceil(widthTimesTaps / rollOffWidth);
}
static float toFc(const float rollOffStart, const int taps) {
static const float startToFcDeltaTimesTaps = 1.27f;
return startToFcDeltaTimesTaps / taps + rollOffStart;
}
public:
const unsigned taps;
const float fc;
RollOff(float rollOffStart, float rollOffWidth) : taps(toTaps(rollOffWidth)), fc(toFc(rollOffStart, taps)) {}
};
HammingSinc(unsigned div, unsigned phaseLen, double fc) { init(div, phaseLen, fc); }
HammingSinc(unsigned div, RollOff ro) { init(div, ro.taps, ro.fc); }
~HammingSinc() { delete[] kernel; }
std::size_t resample(short *out, const short *in, std::size_t inlen);
void adjustDiv(unsigned div);
unsigned mul() const { return MUL; }
unsigned div() const { return convoluters[0].div(); }
};
template<const unsigned channels, const unsigned phases>
void HammingSinc<channels, phases>::init(const unsigned div, const unsigned phaseLen, const double fc) {
kernel = new short[phaseLen * phases];
makeSincKernel(kernel, phases, phaseLen, fc, hammingWin);
for (unsigned i = 0; i < channels; ++i)
convoluters[i].reset(kernel, phaseLen, div);
}
template<const unsigned channels, const unsigned phases>
std::size_t HammingSinc<channels, phases>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i)
samplesOut = convoluters[i].filter(out + i, in + i, inlen);
return samplesOut;
}
template<const unsigned channels, const unsigned phases>
void HammingSinc<channels, phases>::adjustDiv(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
convoluters[i].adjustDiv(div);
}
#endif

View File

@ -0,0 +1,129 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef LININT_H
#define LININT_H
#include <cstddef>
#include "resampler.h"
#include "u48div.h"
template<unsigned channels>
class LinintCore {
unsigned long ratio;
std::size_t pos_;
unsigned fracPos_;
int prevSample_;
public:
LinintCore(long inRate = 1, long outRate = 1) { init(inRate, outRate); }
void adjustRate(long inRate, long outRate) { ratio = (static_cast<double>(inRate) / outRate) * 0x10000 + 0.5; }
void exactRatio(unsigned long &mul, unsigned long &div) const { mul = 0x10000; div = ratio; }
void init(long inRate, long outRate);
std::size_t maxOut(std::size_t inlen) const { return inlen ? u48div(inlen - 1, 0xFFFF, ratio) + 1 : 0; }
std::size_t resample(short *out, const short *in, std::size_t inlen);
};
template<const unsigned channels>
void LinintCore<channels>::init(const long inRate, const long outRate) {
adjustRate(inRate, outRate);
pos_ = (ratio >> 16) + 1;
fracPos_ = ratio & 0xFFFF;
prevSample_ = 0;
}
template<const unsigned channels>
std::size_t LinintCore<channels>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t opos = 0;
std::size_t pos = pos_;
unsigned fracPos = fracPos_;
int prevSample = prevSample_;
if (pos < inlen) {
if (pos != 0)
prevSample = in[(pos-1) * channels];
for (;;) {
out[opos] = prevSample + (in[pos * channels] - prevSample) * static_cast<long>(fracPos) / 0x10000;
opos += channels;
{
const unsigned long next = ratio + fracPos;
pos += next >> 16;
fracPos = next & 0xFFFF;
}
if (pos < inlen) {
prevSample = in[(pos-1) * channels];
} else
break;
}
if (pos == inlen)
prevSample = in[(pos-1) * channels];
}
// const std::size_t produced = ((pos - pos_) * 0x10000 + fracPos - fracPos_) / ratio;
pos_ = pos - inlen;
fracPos_ = fracPos;
prevSample_ = prevSample;
return opos / channels;
}
template<unsigned channels>
class Linint : public Resampler {
LinintCore<channels> cores[channels];
public:
Linint(long inRate, long outRate);
void adjustRate(long inRate, long outRate);
void exactRatio(unsigned long &mul, unsigned long &div) const { cores[0].exactRatio(mul, div); }
std::size_t maxOut(std::size_t inlen) const { return cores[0].maxOut(inlen); }
std::size_t resample(short *out, const short *in, std::size_t inlen);
};
template<const unsigned channels>
Linint<channels>::Linint(const long inRate, const long outRate) {
setRate(inRate, outRate);
for (unsigned i = 0; i < channels; ++i)
cores[i].init(inRate, outRate);
}
template<const unsigned channels>
void Linint<channels>::adjustRate(const long inRate, const long outRate) {
setRate(inRate, outRate);
for (unsigned i = 0; i < channels; ++i)
cores[i].adjustRate(inRate, outRate);
}
template<const unsigned channels>
std::size_t Linint<channels>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t outlen = 0;
for (unsigned i = 0; i < channels; ++i)
outlen = cores[i].resample(out + i, in + i, inlen);
return outlen;
}
#endif

View File

@ -0,0 +1,152 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MAKE_SINC_KERNEL_H
#define MAKE_SINC_KERNEL_H
#include <cmath>
#include <cstdlib>
template<class Window>
void makeSincKernel(short *const kernel, const unsigned phases, const unsigned phaseLen, double fc, Window win) {
static const double PI = 3.14159265358979323846;
fc /= phases;
/*{
double *const dkernel = new double[phaseLen * phases];
const long M = static_cast<long>(phaseLen) * phases - 1;
for (long i = 0; i < M + 1; ++i) {
const double sinc = i * 2 == M ?
PI * fc :
std::sin(PI * fc * (i * 2 - M)) / (i * 2 - M);
dkernel[(i % phases) * phaseLen + i / phases] = win(i, M) * sinc;
}
double maxabsgain = 0;
for (unsigned ph = 0; ph < phases; ++ph) {
double gain = 0;
double absgain = 0;
for (unsigned i = 0; i < phaseLen; ++i) {
gain += dkernel[ph * phaseLen + i];
absgain += std::abs(dkernel[ph * phaseLen + i]);
}
gain = 1.0 / gain;
// Per phase normalization to avoid DC fluctuations.
for (unsigned i = 0; i < phaseLen; ++i)
dkernel[ph * phaseLen + i] *= gain;
absgain *= gain;
if (absgain > maxabsgain)
maxabsgain = absgain;
}
const double gain = 0x10000 / maxabsgain;
for (long i = 0; i < M + 1; ++i)
kernel[i] = std::floor(dkernel[i] * gain + 0.5);
delete[] dkernel;
}*/
// The following is equivalent to the more readable version above
const long M = static_cast<long>(phaseLen) * phases - 1;
double *const dkernel = new double[M / 2 + 1];
{
double *dk = dkernel;
for (unsigned ph = 0; ph < phases; ++ph) {
for (long i = ph; i < M / 2 + 1; i += phases) {
const double sinc = i * 2 == M ?
PI * fc :
std::sin(PI * fc * (i * 2 - M)) / (i * 2 - M);
*dk++ = win(i, M) * sinc;
}
}
}
double maxabsgain = 0.0;
{
double *dkp1 = dkernel;
double *dkp2 = dkernel + M / 2;
for (unsigned ph = 0; ph < (phases + 1) / 2; ++ph) {
double gain = 0.0;
double absgain = 0.0;
{
const double *kp1 = dkp1;
const double *kp2 = dkp2;
long i = ph;
for (; i < M / 2 + 1; i += phases) {
gain += *kp1;
absgain += std::abs(*kp1++);
}
for (; i < M + 1; i += phases) {
gain += *kp2;
absgain += std::abs(*kp2--);
}
}
gain = 1.0 / gain;
long i = ph;
for (; i < M / 2 + 1; i += phases)
*dkp1++ *= gain;
if (dkp1 < dkp2) {
for (; i < M + 1; i += phases)
*dkp2-- *= gain;
}
absgain *= gain;
if (absgain > maxabsgain)
maxabsgain = absgain;
}
}
const double gain = 0x10000 / maxabsgain;
const double *dk = dkernel;
for (unsigned ph = 0; ph < phases; ++ph) {
short *k = kernel + ph * phaseLen;
short *km = kernel + M - ph * phaseLen;
for (long i = ph; i < M / 2 + 1; i += phases)
*km-- = *k++ = std::floor(*dk++ * gain + 0.5);
}
delete[] dkernel;
}
#endif

View File

@ -0,0 +1,99 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RECTSINC_H
#define RECTSINC_H
#include "convoluter.h"
#include "subresampler.h"
#include "makesinckernel.h"
#include "cic2.h"
#include <cmath>
#include <cstdlib>
template<unsigned channels, unsigned phases>
class RectSinc : public SubResampler {
PolyPhaseConvoluter<channels, phases> convoluters[channels];
short *kernel;
static double rectWin(const long /*i*/, const long /*M*/) {
return 1;
}
void init(unsigned div, unsigned phaseLen, double fc);
public:
enum { MUL = phases };
typedef Cic2<channels> Cic;
static float cicLimit() { return 2.0f; }
class RollOff {
static unsigned toTaps(const float rollOffWidth) {
static const float widthTimesTaps = 0.9f;
return std::ceil(widthTimesTaps / rollOffWidth);
}
static float toFc(const float rollOffStart, const int taps) {
static const float startToFcDeltaTimesTaps = 0.43f;
return startToFcDeltaTimesTaps / taps + rollOffStart;
}
public:
const unsigned taps;
const float fc;
RollOff(float rollOffStart, float rollOffWidth) : taps(toTaps(rollOffWidth)), fc(toFc(rollOffStart, taps)) {}
};
RectSinc(unsigned div, unsigned phaseLen, double fc) { init(div, phaseLen, fc); }
RectSinc(unsigned div, RollOff ro) { init(div, ro.taps, ro.fc); }
~RectSinc() { delete[] kernel; }
std::size_t resample(short *out, const short *in, std::size_t inlen);
void adjustDiv(unsigned div);
unsigned mul() const { return MUL; }
unsigned div() const { return convoluters[0].div(); }
};
template<const unsigned channels, const unsigned phases>
void RectSinc<channels, phases>::init(const unsigned div, const unsigned phaseLen, const double fc) {
kernel = new short[phaseLen * phases];
makeSincKernel(kernel, phases, phaseLen, fc, rectWin);
for (unsigned i = 0; i < channels; ++i)
convoluters[i].reset(kernel, phaseLen, div);
}
template<const unsigned channels, const unsigned phases>
std::size_t RectSinc<channels, phases>::resample(short *const out, const short *const in, const std::size_t inlen) {
std::size_t samplesOut;
for (unsigned i = 0; i < channels; ++i)
samplesOut = convoluters[i].filter(out + i, in + i, inlen);
return samplesOut;
}
template<const unsigned channels, const unsigned phases>
void RectSinc<channels, phases>::adjustDiv(const unsigned div) {
for (unsigned i = 0; i < channels; ++i)
convoluters[i].adjustDiv(div);
}
#endif

View File

@ -0,0 +1,43 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RESAMPLER_H
#define RESAMPLER_H
#include <cstddef>
class Resampler {
long inRate_;
long outRate_;
protected:
void setRate(const long inRate, const long outRate) { inRate_ = inRate; outRate_ = outRate; }
public:
Resampler() : inRate_(0), outRate_(0) {}
long inRate() const { return inRate_; }
long outRate() const { return outRate_; }
virtual void adjustRate(long inRate, long outRate) = 0;
virtual void exactRatio(unsigned long &mul, unsigned long &div) const = 0;
virtual std::size_t maxOut(std::size_t inlen) const = 0;
virtual std::size_t resample(short *out, const short *in, std::size_t inlen) = 0;
virtual ~Resampler() {}
};
#endif

View File

@ -0,0 +1,61 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "resamplerinfo.h"
#include "chainresampler.h"
#include "hammingsinc.h"
#include "blackmansinc.h"
#include "rectsinc.h"
#include "linint.h"
struct LinintInfo {
static Resampler* create(long inRate, long outRate, std::size_t) { return new Linint<2>(inRate, outRate); }
};
struct RectsincInfo {
static Resampler* create(long inRate, long outRate, std::size_t periodSz) {
ChainResampler *r = new ChainResampler;
r->init<RectSinc>(inRate, outRate, periodSz);
return r;
}
};
struct HammingsincInfo {
static Resampler* create(long inRate, long outRate, std::size_t periodSz) {
ChainResampler *r = new ChainResampler;
r->init<HammingSinc>(inRate, outRate, periodSz);
return r;
}
};
struct BlackmansincInfo {
static Resampler* create(long inRate, long outRate, std::size_t periodSz) {
ChainResampler *r = new ChainResampler;
r->init<BlackmanSinc>(inRate, outRate, periodSz);
return r;
}
};
const ResamplerInfo ResamplerInfo::resamplers[] = {
{ "2-tap linear interpolation", LinintInfo::create },
{ "Rectangular windowed sinc (~20 dB SNR)", RectsincInfo::create },
{ "Hamming windowed sinc (~50 dB SNR)", HammingsincInfo::create },
{ "Blackman windowed sinc (~70 dB SNR)", BlackmansincInfo::create }
};
const unsigned ResamplerInfo::num_ = sizeof(ResamplerInfo::resamplers) / sizeof(ResamplerInfo);

View File

@ -0,0 +1,36 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RESAMPLER_INFO_H
#define RESAMPLER_INFO_H
#include "resampler.h"
struct ResamplerInfo {
const char *desc;
Resampler* (*create)(long inRate, long outRate, std::size_t periodSz);
static unsigned num() { return num_; }
static const ResamplerInfo& get(unsigned n) { return resamplers[n]; }
private:
static const ResamplerInfo resamplers[];
static const unsigned num_;
};
#endif

View File

@ -0,0 +1,33 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef SUBRESAMPLER_H
#define SUBRESAMPLER_H
#include <cstddef>
class SubResampler {
public:
virtual std::size_t resample(short *out, const short *in, std::size_t inlen) = 0;
virtual unsigned mul() const = 0;
virtual unsigned div() const = 0;
virtual void adjustDiv(unsigned /*div*/) {}
virtual ~SubResampler() {}
};
#endif

View File

@ -0,0 +1,54 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "u48div.h"
unsigned long u48div(unsigned long num1, unsigned num2, const unsigned long den) {
unsigned long res = 0;
unsigned s = 16;
do {
if (num1 < 0x10000) {
num1 <<= s;
num1 |= num2 & ((1 << s) - 1);
s = 0;
} else {
if (num1 < 0x1000000) {
const unsigned maxs = s < 8 ? s : 8;
num1 <<= maxs;
num1 |= (num2 >> (s -= maxs)) & ((1 << maxs) - 1);
}
if (num1 < 0x10000000) {
const unsigned maxs = s < 4 ? s : 4;
num1 <<= maxs;
num1 |= (num2 >> (s -= maxs)) & ((1 << maxs) - 1);
}
while (num1 < den && s) {
num1 <<= 1; // if this overflows we're screwed
num1 |= num2 >> --s & 1;
}
}
res += (num1 / den) << s;
num1 = (num1 % den);
} while (s);
return res;
}

View File

@ -0,0 +1,24 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef U48DIV_H
#define U48DIV_H
unsigned long u48div(unsigned long num1, unsigned num2, unsigned long den);
#endif

View File

@ -0,0 +1,51 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef UPSAMPLER_H
#define UPSAMPLER_H
#include "subresampler.h"
#include <cstring>
template<unsigned channels>
class Upsampler : public SubResampler {
unsigned mul_;
public:
Upsampler(const unsigned mul) : mul_(mul) {}
std::size_t resample(short *out, const short *in, std::size_t inlen);
unsigned mul() const { return mul_; }
unsigned div() const { return 1; }
};
template<const unsigned channels>
std::size_t Upsampler<channels>::resample(short *out, const short *in, std::size_t inlen) {
if (inlen) {
std::memset(out, 0, inlen * mul_ * sizeof(short) * channels);
do {
std::memcpy(out, in, sizeof(short) * channels);
in += channels;
out += mul_ * channels;
} while (--inlen);
}
return inlen * mul_;
}
#endif

View File

@ -0,0 +1,112 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include "array.h"
#include <cstddef>
#include <algorithm>
#include <cstring>
template<typename T>
class RingBuffer {
Array<T> buf;
std::size_t sz;
std::size_t rpos;
std::size_t wpos;
public:
RingBuffer(const std::size_t sz_in = 0) : sz(0), rpos(0), wpos(0) { reset(sz_in); }
std::size_t avail() const {
return (wpos < rpos ? 0 : sz) + rpos - wpos - 1;
}
void clear() {
wpos = rpos = 0;
}
void fill(T value);
void read(T *out, std::size_t num);
void reset(std::size_t sz_in);
std::size_t size() const {
return sz - 1;
}
std::size_t used() const {
return (wpos < rpos ? sz : 0) + wpos - rpos;
}
void write(const T *in, std::size_t num);
};
template<typename T>
void RingBuffer<T>::fill(const T value) {
std::fill(buf + 0, buf + sz, value);
rpos = 0;
wpos = sz - 1;
}
template<typename T>
void RingBuffer<T>::read(T *out, std::size_t num) {
if (rpos + num > sz) {
const std::size_t n = sz - rpos;
std::memcpy(out, buf + rpos, n * sizeof(T));
rpos = 0;
num -= n;
out += n;
}
std::memcpy(out, buf + rpos, num * sizeof(T));
if ((rpos += num) == sz)
rpos = 0;
}
template<typename T>
void RingBuffer<T>::reset(const std::size_t sz_in) {
sz = sz_in + 1;
rpos = wpos = 0;
buf.reset(sz_in ? sz : 0);
}
template<typename T>
void RingBuffer<T>::write(const T *in, std::size_t num) {
if (wpos + num > sz) {
const std::size_t n = sz - wpos;
std::memcpy(buf + wpos, in, n * sizeof(T));
wpos = 0;
num -= n;
in += n;
}
std::memcpy(buf + wpos, in, num * sizeof(T));
if ((wpos += num) == sz)
wpos = 0;
}
#endif

View File

@ -0,0 +1,31 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef USEC_H
#define USEC_H
typedef unsigned long usec_t;
static inline usec_t negate(usec_t t) {
return usec_t(0) - t;
}
usec_t getusecs();
void usecsleep(usec_t usecs);
#endif

View File

@ -0,0 +1,32 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_FILTERINFO_H
#define GAMBATTE_FILTERINFO_H
#include <string>
namespace Gambatte {
struct FilterInfo {
std::string handle;
unsigned int outWidth;
unsigned int outHeight;
};
}
#endif

View File

@ -0,0 +1,84 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_H
#define GAMBATTE_H
class CPU;
#include "videoblitter.h"
#include "inputstate.h"
#include "inputstategetter.h"
#include "memoryinterface.h"
#include "filterinfo.h"
#include "int.h"
#include <vector>
namespace Gambatte {
class GB {
CPU *const z80;
int stateNo;
void loadState(const char *filepath, bool osdMessage);
public:
GB();
~GB();
bool load(bool forceDmg = false);
void save();
/** Emulates until at least 'samples' stereo sound samples are produced in the supplied buffer.
* There are 35112 stereo sound samples in a video frame.
* May run for uptil 2064 stereo samples too long.
* A stereo sample consists of two native endian 2s complement 16-bit PCM samples,
* with the left sample preceding the right one. Usually casting soundBuf to/from
* short* is OK and recommended. The reason for not using a short* in the interface
* is to avoid implementation defined behaviour without compromising performance.
*
* @param soundBuf buffer with space >= samples + 2064
* @param samples number of stereo samples to produce
* @return actual number of samples produced
*/
unsigned runFor(uint32_t *soundBuf, unsigned samples);
void updateVideo();
unsigned lyCounter();
void reset();
void setVideoBlitter(VideoBlitter *vb);
void videoBufferChange();
unsigned videoWidth() const;
unsigned videoHeight() const;
void setDmgPaletteColor(unsigned palNum, unsigned colorNum, unsigned rgb32);
void setVideoFilter(unsigned n);
std::vector<const FilterInfo*> filterInfo() const;
void setInputStateGetter(InputStateGetter *getInput);
void setMemoryInterface(MemoryInterface *memoryInterface);
void set_savedir(const char *sdir);
bool isCgb() const;
void saveState();
void loadState();
void saveState(const char *filepath);
void loadState(const char *filepath);
void selectState(int n);
int currentState() const { return stateNo; }
};
}
#endif

View File

@ -0,0 +1,30 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_INPUTSTATE_H
#define GAMBATTE_INPUTSTATE_H
namespace Gambatte {
struct InputState {
unsigned joypadId;
bool startButton, selectButton, bButton, aButton;
bool dpadDown, dpadUp, dpadLeft, dpadRight;
};
}
#endif

View File

@ -0,0 +1,30 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_INPUTSTATEGETTER_H
#define GAMBATTE_INPUTSTATEGETTER_H
namespace Gambatte {
class InputStateGetter {
public:
virtual ~InputStateGetter() {};
virtual const InputState& operator()() = 0;
};
}
#endif

View File

@ -0,0 +1,62 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_INT_H
#define GAMBATTE_INT_H
#ifdef HAVE_CSTDINT
#include <cstdint>
namespace Gambatte {
using std::uint_least32_t;
using std::uint_least16_t;
}
#elif defined(HAVE_STDINT_H)
#include <stdint.h>
namespace Gambatte {
using ::uint_least32_t;
using ::uint_least16_t;
}
#else
namespace Gambatte {
#ifdef CHAR_LEAST_32
typedef unsigned char uint_least32_t;
#elif defined(SHORT_LEAST_32)
typedef unsigned short uint_least32_t;
#elif defined(INT_LEAST_32)
typedef unsigned uint_least32_t;
#else
typedef unsigned long uint_least32_t;
#endif
#ifdef CHAR_LEAST_16
typedef unsigned char uint_least16_t;
#else
typedef unsigned short uint_least16_t;
#endif
}
#endif
#endif

View File

@ -0,0 +1,25 @@
#ifndef GAMBATTE_MEMORYINTERFACE_H
#define GAMBATTE_MEMORYINTERFACE_H
namespace Gambatte {
struct MemoryBuffer {
void *data;
unsigned size;
};
class MemoryInterface {
public:
virtual MemoryBuffer loadRomData() = 0;
virtual MemoryBuffer loadRamData() = 0;
virtual MemoryBuffer loadRtcData() = 0;
virtual MemoryBuffer saveRamData(unsigned size) = 0;
virtual MemoryBuffer saveRtcData() = 0;
virtual void joypWrite(bool /*p15*/, bool /*p14*/) {}
};
}
#endif

View File

@ -0,0 +1,44 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_VIDEOBLITTER_H
#define GAMBATTE_VIDEOBLITTER_H
namespace Gambatte {
struct PixelBuffer {
enum Format { RGB32, RGB16, UYVY };
void *pixels;
Format format;
unsigned pitch;
PixelBuffer() : pixels(0), format(RGB32), pitch(0) {}
};
class VideoBlitter {
public:
virtual void setBufferDimensions(unsigned width, unsigned height) = 0;
virtual const PixelBuffer inBuffer() = 0;
virtual void blit() = 0;
virtual ~VideoBlitter() {}
};
}
#endif

View File

@ -0,0 +1,328 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
/*
The following font bitmaps (static const unsigned char *_bits[]), only used
as data and included in this source file for convenience, are derived from
the Bitstream Vera Sans font, which is distributed under the following
copyright:
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream Vera"
names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM
OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or
Bitstream Inc., respectively. For further information, contact: fonts at
gnome dot org.
*/
#include "bitmap_font.h"
static const unsigned char n0_bits[] = { 0x68,
0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c };
static const unsigned char n1_bits[] = { 0x68,
0x00, 0x0e, 0x08, 0x08, 0x08, 0x08, 0x08, 0x3e };
static const unsigned char n2_bits[] = { 0x68,
0x00, 0x1c, 0x22, 0x20, 0x10, 0x08, 0x04, 0x3e };
static const unsigned char n3_bits[] = { 0x68,
0x00, 0x1c, 0x22, 0x20, 0x1c, 0x20, 0x22, 0x1c };
static const unsigned char n4_bits[] = { 0x68,
0x00, 0x18, 0x18, 0x14, 0x12, 0x3e, 0x10, 0x10 };
static const unsigned char n5_bits[] = { 0x68,
0x00, 0x1e, 0x02, 0x1e, 0x20, 0x20, 0x20, 0x1e };
static const unsigned char n6_bits[] = { 0x68,
0x00, 0x3c, 0x06, 0x02, 0x1e, 0x22, 0x22, 0x1c };
static const unsigned char n7_bits[] = { 0x68,
0x00, 0x3e, 0x20, 0x10, 0x10, 0x08, 0x08, 0x04 };
static const unsigned char n8_bits[] = { 0x68,
0x00, 0x1c, 0x22, 0x22, 0x1c, 0x22, 0x22, 0x1c };
static const unsigned char n9_bits[] = { 0x68,
0x00, 0x1c, 0x22, 0x22, 0x3c, 0x20, 0x30, 0x1e };
static const unsigned char A_bits[] = { 0x78,
0x00, 0x08, 0x14, 0x14, 0x22, 0x3e, 0x22, 0x41 };
static const unsigned char a_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x1c, 0x20, 0x3c, 0x22, 0x3e };
static const unsigned char B_bits[] = { 0x78,
0x00, 0x1e, 0x22, 0x22, 0x1e, 0x22, 0x22, 0x1e };
static const unsigned char b_bits[] = { 0x68,
0x02, 0x02, 0x02, 0x1e, 0x22, 0x22, 0x22, 0x1e };
static const unsigned char C_bits[] = { 0x88,
0x00, 0x38, 0x44, 0x02, 0x02, 0x02, 0x44, 0x38 };
static const unsigned char c_bits[] = { 0x58,
0x00, 0x00, 0x00, 0x1c, 0x02, 0x02, 0x02, 0x1c };
static const unsigned char D_bits[] = { 0x88,
0x00, 0x3e, 0x62, 0x42, 0x42, 0x42, 0x62, 0x3e };
static const unsigned char d_bits[] = { 0x68,
0x20, 0x20, 0x20, 0x3c, 0x22, 0x22, 0x22, 0x3c };
static const unsigned char E_bits[] = { 0x78,
0x00, 0x3e, 0x02, 0x02, 0x3e, 0x02, 0x02, 0x3e };
static const unsigned char e_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x1c, 0x22, 0x3e, 0x02, 0x3c };
static const unsigned char F_bits[] = { 0x68,
0x00, 0x1e, 0x02, 0x02, 0x1e, 0x02, 0x02, 0x02 };
static const unsigned char f_bits[] = { 0x48,
0x0e, 0x02, 0x02, 0x07, 0x02, 0x02, 0x02, 0x02 };
static const unsigned char G_bits[] = { 0x88,
0x00, 0x3c, 0x46, 0x02, 0x72, 0x42, 0x46, 0x3c };
static const unsigned char g_bits[] = { 0x6a,
0x00, 0x00, 0x00, 0x3c, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x1c };
static const unsigned char H_bits[] = { 0x88,
0x00, 0x42, 0x42, 0x42, 0x7e, 0x42, 0x42, 0x42 };
static const unsigned char h_bits[] = { 0x68,
0x02, 0x02, 0x02, 0x1e, 0x22, 0x22, 0x22, 0x22 };
static const unsigned char I_bits[] = { 0x38,
0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
static const unsigned char i_bits[] = { 0x28,
0x02, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02 };
static const unsigned char J_bits[] = { 0x4a,
0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03 };
static const unsigned char j_bits[] = { 0x2a,
0x02, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03 };
static const unsigned char K_bits[] = { 0x78,
0x00, 0x22, 0x12, 0x0a, 0x06, 0x0a, 0x12, 0x22 };
static const unsigned char k_bits[] = { 0x58,
0x02, 0x02, 0x02, 0x12, 0x0a, 0x06, 0x0a, 0x12 };
static const unsigned char L_bits[] = { 0x68,
0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x3e };
static const unsigned char l_bits[] = { 0x28,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
static const unsigned char M_bits[] = { 0x98,
0x00, 0x00, 0x82, 0x00, 0xc6, 0x00, 0xc6, 0x00, 0xaa, 0x00, 0xaa, 0x00,
0x92, 0x00, 0x82, 0x00 };
static const unsigned char m_bits[] = { 0xa8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0x01, 0x22, 0x02, 0x22, 0x02,
0x22, 0x02, 0x22, 0x02 };
static const unsigned char N_bits[] = { 0x88,
0x00, 0x42, 0x46, 0x4a, 0x4a, 0x52, 0x62, 0x42 };
static const unsigned char n_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x1e, 0x22, 0x22, 0x22, 0x22 };
static const unsigned char O_bits[] = { 0x88,
0x00, 0x3c, 0x66, 0x42, 0x42, 0x42, 0x66, 0x3c };
static const unsigned char o_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x1c, 0x22, 0x22, 0x22, 0x1c };
static const unsigned char P_bits[] = { 0x78,
0x00, 0x1e, 0x22, 0x22, 0x1e, 0x02, 0x02, 0x02 };
static const unsigned char p_bits[] = { 0x6a,
0x00, 0x00, 0x00, 0x1e, 0x22, 0x22, 0x22, 0x1e, 0x02, 0x02 };
static const unsigned char Q_bits[] = { 0x89,
0x00, 0x3c, 0x66, 0x42, 0x42, 0x42, 0x26, 0x1c, 0x20 };
static const unsigned char q_bits[] = { 0x6a,
0x00, 0x00, 0x00, 0x3c, 0x22, 0x22, 0x22, 0x3c, 0x20, 0x20 };
static const unsigned char R_bits[] = { 0x78,
0x00, 0x1e, 0x22, 0x22, 0x1e, 0x12, 0x22, 0x42 };
static const unsigned char r_bits[] = { 0x48,
0x00, 0x00, 0x00, 0x0e, 0x02, 0x02, 0x02, 0x02 };
static const unsigned char S_bits[] = { 0x78,
0x00, 0x1c, 0x22, 0x02, 0x1c, 0x20, 0x22, 0x1c };
static const unsigned char s_bits[] = { 0x58,
0x00, 0x00, 0x00, 0x1e, 0x02, 0x1c, 0x10, 0x1e };
static const unsigned char T_bits[] = { 0x58,
0x00, 0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 };
static const unsigned char t_bits[] = { 0x48,
0x00, 0x02, 0x02, 0x0f, 0x02, 0x02, 0x02, 0x0e };
static const unsigned char U_bits[] = { 0x88,
0x00, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x3c };
static const unsigned char u_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, 0x3c };
static const unsigned char V_bits[] = { 0x78,
0x00, 0x41, 0x41, 0x22, 0x22, 0x14, 0x14, 0x08 };
static const unsigned char v_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x22, 0x22, 0x14, 0x14, 0x08 };
static const unsigned char W_bits[] = { 0x98,
0x00, 0x00, 0x11, 0x01, 0x11, 0x01, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00,
0x44, 0x00, 0x44, 0x00 };
static const unsigned char w_bits[] = { 0x88,
0x00, 0x00, 0x00, 0x92, 0xaa, 0xaa, 0x44, 0x44 };
static const unsigned char X_bits[] = { 0x68,
0x00, 0x21, 0x12, 0x0c, 0x0c, 0x0c, 0x12, 0x21 };
static const unsigned char x_bits[] = { 0x68,
0x00, 0x00, 0x00, 0x22, 0x14, 0x08, 0x14, 0x22 };
static const unsigned char Y_bits[] = { 0x78,
0x00, 0x41, 0x22, 0x14, 0x08, 0x08, 0x08, 0x08 };
static const unsigned char y_bits[] = { 0x6a,
0x00, 0x00, 0x00, 0x22, 0x22, 0x14, 0x14, 0x08, 0x08, 0x06 };
static const unsigned char Z_bits[] = { 0x68,
0x00, 0x3f, 0x10, 0x08, 0x0c, 0x04, 0x02, 0x3f };
static const unsigned char z_bits[] = { 0x58,
0x00, 0x00, 0x00, 0x1e, 0x10, 0x08, 0x04, 0x1e };
static const unsigned char SPC_bits[] = { 0x38,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
namespace BitmapFont {
const unsigned char *const font[] = {
0,
n0_bits, n1_bits, n2_bits, n3_bits, n4_bits, n5_bits, n6_bits, n7_bits, n8_bits, n9_bits,
A_bits, B_bits, C_bits, D_bits, E_bits, F_bits, G_bits, H_bits, I_bits, J_bits, K_bits, L_bits, M_bits,
N_bits, O_bits, P_bits, Q_bits, R_bits, S_bits, T_bits, U_bits, V_bits, W_bits, X_bits, Y_bits, Z_bits,
a_bits, b_bits, c_bits, d_bits, e_bits, f_bits, g_bits, h_bits, i_bits, j_bits, k_bits, l_bits, m_bits,
n_bits, o_bits, p_bits, q_bits, r_bits, s_bits, t_bits, u_bits, v_bits, w_bits, x_bits, y_bits, z_bits,
SPC_bits
};
unsigned getWidth(const char *chars) {
unsigned w = 0;
while (const int character = *chars++) {
w += *font[character] >> 4;
}
return w;
}
class Rgb32Fill {
const unsigned long color;
public:
Rgb32Fill(unsigned long color) : color(color) {}
void operator()(Gambatte::uint_least32_t *dest, unsigned /*pitch*/) {
*dest = color;
}
};
void print(Gambatte::uint_least32_t *dest, const unsigned pitch, const unsigned long color, const char *chars) {
print(dest, pitch, Rgb32Fill(color), chars);
}
static void reverse(char *first, char *last) {
while (first < last) {
const int tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
}
}
void utoa(unsigned u, char *a) {
char *aa = a;
while (u > 9) {
const unsigned div = u / 10;
const unsigned rem = u % 10;
u = div;
*aa++ = rem + N0;
}
*aa = u + N0;
reverse(a, aa);
}
}

View File

@ -0,0 +1,87 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef BITMAP_FONT_H
#define BITMAP_FONT_H
#include "int.h"
namespace BitmapFont {
enum Char {
NUL,
N0, N1, N2, N3, N4, N5, N6, N7, N8, N9,
A, B, C, D, E, F, G, H, I, J, K, L, M,
N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
a, b, c, d, e, f, g, h, i, j, k, l, m,
n, o, p, q, r, s, t, u, v, w, x, y, z,
SPC
};
enum { HEIGHT = 10 };
enum { MAX_WIDTH = 9 };
enum { NUMBER_WIDTH = 6 };
unsigned getWidth(const char *chars);
// struct Fill { void operator()(RandomAccessIterator dest, unsigned pitch) { fill pixels at dest } }
template<class RandomAccessIterator, class Fill>
void print(RandomAccessIterator dest, unsigned pitch, Fill fill, const char *chars);
void print(Gambatte::uint_least32_t *dest, unsigned pitch, unsigned long color, const char *chars);
void utoa(unsigned u, char *a);
// --- INTERFACE END ---
extern const unsigned char *const font[];
template<class RandomAccessIterator, class Fill>
void print(RandomAccessIterator dest, const unsigned pitch, Fill fill, const char *chars) {
while (const int character = *chars++) {
RandomAccessIterator dst = dest;
const unsigned char *s = font[character];
const unsigned width = *s >> 4;
unsigned h = *s++ & 0xF;
while (h--) {
RandomAccessIterator d = dst;
unsigned line = *s++;
if (width > 8)
line |= *s++ << 8;
while (line) {
if (line & 1)
fill(d, pitch);
line >>= 1;
++d;
}
dst += pitch;
}
dest += width;
}
}
}
#endif

View File

@ -0,0 +1,96 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "colorconversion.h"
#include <algorithm>
Rgb32ToUyvy::Rgb32ToUyvy() {
#ifdef WORDS_BIGENDIAN
const CacheUnit c = { 0, 128ul << 24 | 16ul << 16 | 128 << 8 | 16 };
#else
const CacheUnit c = { 0, 16ul << 24 | 128ul << 16 | 16 << 8 | 128 };
#endif
std::fill(cache, cache + cache_size, c);
}
void Rgb32ToUyvy::operator()(const Gambatte::uint_least32_t *s, Gambatte::uint_least32_t *d, const unsigned w, unsigned h, const unsigned d_pitch) {
while (h--) {
for (const Gambatte::uint_least32_t *const ends = s + w; s != ends;) {
if ((cache[*s & cache_mask].rgb32 - *s) | (cache[*(s+1) & cache_mask].rgb32 - *(s+1))) {
cache[*s & cache_mask].rgb32 = *s;
cache[*(s+1) & cache_mask].rgb32 = *(s+1);
const unsigned long r = (*s >> 16 & 0x000000FF) | (*(s+1) & 0x00FF0000);
const unsigned long g = (*s >> 8 & 0x000000FF) | (*(s+1) << 8 & 0x00FF0000);
const unsigned long b = (*s & 0x000000FF) | (*(s+1) << 16 & 0x00FF0000);
const unsigned long y = r * 66 + g * 129 + b * 25 + (16 * 256 + 128) * 0x00010001ul;
const unsigned long u = b * 112 - r * 38 - g * 74 + (128 * 256 + 128) * 0x00010001ul;
const unsigned long v = r * 112 - g * 94 - b * 18 + (128 * 256 + 128) * 0x00010001ul;
#ifdef WORDS_BIGENDIAN
*d++ = cache[*s & cache_mask].uyvy = (u << 16 & 0xFF000000) | (y << 8 & 0x00FF0000) | (v & 0x0000FF00) | (y >> 8 & 0x000000FF);
*d++ = cache[*(s+1) & cache_mask].uyvy = (u & 0xFF000000) | (y >> 8 & 0x00FF0000) | (v >> 16 & 0x0000FF00) | y >> 24;
#else
*d++ = cache[*s & cache_mask].uyvy = (y << 16 & 0xFF000000) | (v << 8 & 0x00FF0000) | (y & 0x0000FF00) | (u >> 8 & 0x000000FF);
*d++ = cache[*(s+1) & cache_mask].uyvy = (y & 0xFF000000) | (v >> 8 & 0x00FF0000) | (y >> 16 & 0x0000FF00) | u >> 24;
#endif
} else {
*d++ = cache[*s & cache_mask].uyvy;
*d++ = cache[*(s+1) & cache_mask].uyvy;
}
s += 2;
}
d += d_pitch - w;
}
}
unsigned long rgb32ToUyvy(unsigned long rgb32) {
const unsigned r = rgb32 >> 16 & 0xFF;
const unsigned g = rgb32 >> 8 & 0xFF;
const unsigned b = rgb32 & 0xFF;
const unsigned long y = (r * 66 + g * 129 + b * 25 + 16 * 256 + 128) >> 8;
const unsigned long u = (b * 112 - r * 38 - g * 74 + 128 * 256 + 128) >> 8;
const unsigned long v = (r * 112 - g * 94 - b * 18 + 128 * 256 + 128) >> 8;
#ifdef WORDS_BIGENDIAN
return u << 24 | y << 16 | v << 8 | y;
#else
return y << 24 | v << 16 | y << 8 | u;
#endif
}
void rgb32ToRgb16(const Gambatte::uint_least32_t *s, Gambatte::uint_least16_t *d, const unsigned w, unsigned h, const unsigned dstPitch) {
do {
unsigned n = w;
do {
*d++ = (*s >> 8 & 0xF800) | (*s >> 5 & 0x07E0) | (*s >> 3 & 0x001F);
++s;
} while (--n);
d += dstPitch - w;
} while (--h);
}
unsigned rgb32ToRgb16(const unsigned long rgb32) {
return (rgb32 >> 8 & 0xF800) | (rgb32 >> 5 & 0x07E0) | (rgb32 >> 3 & 0x001F);
}

View File

@ -0,0 +1,46 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef COLORCONVERSION_H
#define COLORCONVERSION_H
#include "int.h"
#include <algorithm>
class Rgb32ToUyvy {
struct CacheUnit {
Gambatte::uint_least32_t rgb32;
Gambatte::uint_least32_t uyvy;
};
enum { cache_size = 0x100 };
enum { cache_mask = cache_size - 1 };
CacheUnit cache[cache_size];
public:
Rgb32ToUyvy();
void operator()(const Gambatte::uint_least32_t *s, Gambatte::uint_least32_t *d, unsigned w, unsigned h, unsigned dstPitch);
};
unsigned long rgb32ToUyvy(unsigned long rgb32);
void rgb32ToRgb16(const Gambatte::uint_least32_t *s, Gambatte::uint_least16_t *d, unsigned w, unsigned h, unsigned dstPitch);
unsigned rgb32ToRgb16(unsigned long rgb32);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,117 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef CPU_H
#define CPU_H
class SaveState;
#include "int.h"
#include "memory.h"
class CPU {
Memory memory;
unsigned long cycleCounter_;
unsigned short PC_;
unsigned short SP;
unsigned HF1, HF2, ZF, CF;
unsigned char A_, B, C, D, E, /*F,*/ H, L;
bool skip;
bool halted;
void process(unsigned long cycles);
public:
CPU();
// void halt();
// unsigned interrupt(unsigned address, unsigned cycleCounter);
void runFor(unsigned long cycles);
void updateVideo();
unsigned lyCounter();
void setStatePtrs(SaveState &state);
void saveState(SaveState &state);
void loadState(const SaveState &state);
void loadSavedata() { memory.loadSavedata(); }
void saveSavedata() { memory.saveSavedata(); }
void setVideoBlitter(Gambatte::VideoBlitter *vb) {
memory.setVideoBlitter(vb);
}
void videoBufferChange() {
memory.videoBufferChange();
}
unsigned int videoWidth() const {
return memory.videoWidth();
}
unsigned int videoHeight() const {
return memory.videoHeight();
}
void setVideoFilter(const unsigned int n) {
memory.setVideoFilter(n);
}
std::vector<const Gambatte::FilterInfo*> filterInfo() const {
return memory.filterInfo();
}
void setInputStateGetter(Gambatte::InputStateGetter *getInput) {
memory.setInputStateGetter(getInput);
}
void setMemoryInterface(Gambatte::MemoryInterface *memoryInterface) {
memory.setMemoryInterface(memoryInterface);
}
void set_savedir(const char *sdir) {
memory.set_savedir(sdir);
}
const std::string saveBasePath() const {
return memory.saveBasePath();
}
void setOsdElement(std::auto_ptr<OsdElement> osdElement) {
memory.setOsdElement(osdElement);
}
bool load(bool forceDmg);
void setSoundBuffer(Gambatte::uint_least32_t *const buf) { memory.setSoundBuffer(buf); }
unsigned fillSoundBuffer() { return memory.fillSoundBuffer(cycleCounter_); }
bool isCgb() const { return memory.isCgb(); }
void setDmgPaletteColor(unsigned palNum, unsigned colorNum, unsigned rgb32) {
memory.setDmgPaletteColor(palNum, colorNum, rgb32);
}
};
#endif

View File

@ -0,0 +1,160 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef EVENT_QUEUE_H
#define EVENT_QUEUE_H
#include <cstddef>
template<typename T, class Comparer>
class event_queue {
Comparer comparer;
T *const a;
const std::size_t capacity_;
std::size_t size_;
std::size_t indexOf(T e);
void internalDec(std::size_t i, T e);
template<bool child2BoundsCheck> void internalInc(std::size_t i, T e);
public:
event_queue(std::size_t capacity, const Comparer &comparer);
~event_queue();
std::size_t capacity() const {
return capacity_;
}
void clear() {
size_ = 0;
}
void dec(const T oldE, const T newE) {
internalDec(indexOf(oldE), newE);
}
bool empty() const {
return size_ == 0;
}
void inc(const T oldE, const T newE) {
internalInc<true>(indexOf(oldE), newE);
}
void modify_root(const T newRoot) {
internalInc<true>(0, newRoot);
}
void pop() {
internalInc<false>(0, a[--size_]);
}
void push(const T e) {
internalDec(size_++, e);
}
void remove(T e);
std::size_t size() const {
return size_;
}
T top() const {
return a[0];
}
};
template<typename T, class Comparer>
event_queue<T,Comparer>::event_queue(const std::size_t capacity, const Comparer &comparer_in) :
comparer(comparer_in),
a(new T[capacity]),
capacity_(capacity),
size_(0)
{}
template<typename T, class Comparer>
event_queue<T,Comparer>::~event_queue() {
delete[] a;
}
template<typename T, class Comparer>
std::size_t event_queue<T,Comparer>::indexOf(const T e) {
std::size_t i = 0;
while (a[i] != e)
++i;
return i;
}
template<typename T, class Comparer>
void event_queue<T,Comparer>::internalDec(std::size_t i, const T e) {
a[i] = e;
while (i != 0) {
const std::size_t parentI = (i - 1) >> 1;
if (!comparer.less(e, a[parentI]))
break;
a[i] = a[parentI];
a[parentI] = e;
i = parentI;
}
}
template<typename T, class Comparer>
template<const bool child2BoundsCheck>
void event_queue<T,Comparer>::internalInc(std::size_t i, const T e) {
a[i] = e;
for (;;) {
std::size_t childI = i * 2 + 1;
if (childI >= size_)
break;
if ((!child2BoundsCheck || childI + 1 < size_) && comparer.less(a[childI + 1], a[childI]))
++childI;
if (!comparer.less(a[childI], e))
break;
a[i] = a[childI];
a[childI] = e;
i = childI;
}
}
template<typename T, class Comparer>
void event_queue<T,Comparer>::remove(const T e) {
std::size_t i = indexOf(e);
while (i != 0) {
const std::size_t parentI = (i - 1) >> 1;
a[i] = a[parentI];
a[parentI] = e;
i = parentI;
}
pop();
}
#endif

View File

@ -0,0 +1,73 @@
/***************************************************************************
Copyright (C) 2007 by Nach
http://nsrt.edgeemu.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************/
#include "file.h"
using namespace std;
static const unsigned int MAX_FILE_NAME = 512;
File::File(const char *filename) : stream(filename, ios::in | ios::binary), is_zip(false), fsize(0), count(0)
{
if (stream)
{
stream.seekg(0, ios::end);
fsize = stream.tellg();
stream.seekg(0, ios::beg);
}
}
File::~File()
{
close();
}
void File::rewind()
{
if (is_open())
{
stream.seekg(0, ios::beg);
}
}
bool File::is_open()
{
return(stream.is_open());
}
void File::close()
{
if (is_open())
{
stream.close();
}
}
void File::read(char *buffer, size_t amount)
{
if (is_open())
{
stream.read(buffer, amount);
count = stream.gcount();
}
else
{
count = 0;
}
}

View File

@ -0,0 +1,42 @@
/***************************************************************************
Copyright (C) 2007 by Nach
http://nsrt.edgeemu.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************/
#include <fstream>
class File {
private:
std::ifstream stream;
bool is_zip; //Change this to an enum later
std::size_t fsize, count;
void *zipfile;
bool zip_sub_open;
void zip(const char *filename);
public:
File(const char *filename);
~File();
void rewind();
bool is_open();
void close();
std::size_t size() const { return fsize; };
void read(char *buffer, std::size_t amount);
std::size_t gcount() const { return count; }
bool fail() const { return stream.fail(); }
};

View File

@ -0,0 +1,167 @@
/***************************************************************************
Copyright (C) 2007 by Nach
http://nsrt.edgeemu.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************/
#include "file.h"
#include <cstring>
namespace zlib {
#include "unzip/unzip.h"
}
using namespace std;
using namespace zlib;
static const unsigned int MAX_FILE_NAME = 512;
File::File(const char *filename) : stream(filename, ios::in | ios::binary), is_zip(false), fsize(0), count(0)
{
if (stream)
{
char temp[4];
stream.read(temp, sizeof(temp));
//check for standard zip 'magic number'
if ((temp[0] == 'P') && (temp[1] == 'K') && (temp[2] == 3) && (temp[3] == 4))
{
stream.close();
is_zip = true;
zip(filename);
}
else
{
stream.seekg(0, ios::end);
fsize = stream.tellg();
stream.seekg(0, ios::beg);
}
}
}
void File::zip(const char *filename)
{
zipfile = unzOpen(filename);
if (zipfile)
{
zip_sub_open = false;
unz_file_info cFileInfo;
char ourFile[MAX_FILE_NAME] = { '\n' };
for (int cFile = unzGoToFirstFile((unzFile)zipfile); cFile == UNZ_OK; cFile = unzGoToNextFile((unzFile)zipfile))
{
//Temporary char array for file name
char cFileName[MAX_FILE_NAME];
//Gets info on current file, and places it in cFileInfo
unzGetCurrentFileInfo((unzFile)zipfile, &cFileInfo, cFileName, MAX_FILE_NAME, 0, 0, 0, 0);
//Check for largest file which should be the ROM
if ((size_t)cFileInfo.uncompressed_size > fsize)
{
strcpy(ourFile, cFileName);
fsize = (size_t)cFileInfo.uncompressed_size;
}
}
if (ourFile[0] != '\n')
{
//Sets current file to the file we liked before
unzLocateFile((unzFile)zipfile, ourFile, 1);
if (unzOpenCurrentFile((unzFile)zipfile) == UNZ_OK)
{
zip_sub_open = true;
}
}
if (!zip_sub_open)
{
unzClose((unzFile)zipfile);
zipfile = 0;
}
}
}
File::~File()
{
close();
}
void File::rewind()
{
if (is_open())
{
if (!is_zip)
{
stream.seekg(0, ios::beg);
}
else
{
unzCloseCurrentFile((unzFile)zipfile);
unzOpenCurrentFile((unzFile)zipfile);
}
}
}
bool File::is_open()
{
if (!is_zip)
{
return(stream.is_open());
}
return(zipfile && zip_sub_open);
}
void File::close()
{
if (is_open())
{
if (!is_zip)
{
stream.close();
}
else
{
unzOpenCurrentFile((unzFile)zipfile);
unzClose((unzFile)zipfile);
zipfile = 0;
zip_sub_open = false;
}
}
}
void File::read(char *buffer, size_t amount)
{
if (is_open())
{
if (!is_zip)
{
stream.read(buffer, amount);
count = stream.gcount();
}
else
{
count = (size_t)unzReadCurrentFile((unzFile)zipfile, buffer, amount);
}
}
else
{
count = 0;
}
}

View File

@ -0,0 +1,177 @@
/* ioapi.c -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include "ioapi.h"
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
voidpf ZCALLBACK fopen_file_func OF((
voidpf opaque,
const char* filename,
int mode));
uLong ZCALLBACK fread_file_func OF((
voidpf opaque,
voidpf stream,
void* buf,
uLong size));
uLong ZCALLBACK fwrite_file_func OF((
voidpf opaque,
voidpf stream,
const void* buf,
uLong size));
long ZCALLBACK ftell_file_func OF((
voidpf opaque,
voidpf stream));
long ZCALLBACK fseek_file_func OF((
voidpf opaque,
voidpf stream,
uLong offset,
int origin));
int ZCALLBACK fclose_file_func OF((
voidpf opaque,
voidpf stream));
int ZCALLBACK ferror_file_func OF((
voidpf opaque,
voidpf stream));
voidpf ZCALLBACK fopen_file_func (opaque, filename, mode)
voidpf opaque;
const char* filename;
int mode;
{
FILE* file = NULL;
const char* mode_fopen = NULL;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
mode_fopen = "rb";
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
mode_fopen = "r+b";
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
mode_fopen = "wb";
if ((filename!=NULL) && (mode_fopen != NULL))
file = fopen(filename, mode_fopen);
return file;
}
uLong ZCALLBACK fread_file_func (opaque, stream, buf, size)
voidpf opaque;
voidpf stream;
void* buf;
uLong size;
{
uLong ret;
ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size)
voidpf opaque;
voidpf stream;
const void* buf;
uLong size;
{
uLong ret;
ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
long ZCALLBACK ftell_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
long ret;
ret = ftell((FILE *)stream);
return ret;
}
long ZCALLBACK fseek_file_func (opaque, stream, offset, origin)
voidpf opaque;
voidpf stream;
uLong offset;
int origin;
{
int fseek_origin=0;
long ret;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
fseek_origin = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END :
fseek_origin = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
fseek_origin = SEEK_SET;
break;
default: return -1;
}
ret = 0;
fseek((FILE *)stream, offset, fseek_origin);
return ret;
}
int ZCALLBACK fclose_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
int ret;
ret = fclose((FILE *)stream);
return ret;
}
int ZCALLBACK ferror_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
int ret;
ret = ferror((FILE *)stream);
return ret;
}
void fill_fopen_filefunc (pzlib_filefunc_def)
zlib_filefunc_def* pzlib_filefunc_def;
{
pzlib_filefunc_def->zopen_file = fopen_file_func;
pzlib_filefunc_def->zread_file = fread_file_func;
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
pzlib_filefunc_def->ztell_file = ftell_file_func;
pzlib_filefunc_def->zseek_file = fseek_file_func;
pzlib_filefunc_def->zclose_file = fclose_file_func;
pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,354 @@
/* unzip.h -- IO for uncompress .zip files using zlib
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
WinZip, InfoZip tools and compatible.
Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported
I WAIT FEEDBACK at mail info@winimage.com
Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* for more info about .ZIP format, see
http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip
http://www.info-zip.org/pub/infozip/doc/
PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip
*/
#ifndef _unz_H
#define _unz_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include <zlib.h>
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */
typedef struct TagunzFile__ { int unused; } unzFile__;
typedef unzFile__ *unzFile;
#else
typedef voidp unzFile;
#endif
#define UNZ_OK (0)
#define UNZ_END_OF_LIST_OF_FILE (-100)
#define UNZ_ERRNO (Z_ERRNO)
#define UNZ_EOF (0)
#define UNZ_PARAMERROR (-102)
#define UNZ_BADZIPFILE (-103)
#define UNZ_INTERNALERROR (-104)
#define UNZ_CRCERROR (-105)
/* tm_unz contain date/time info */
typedef struct tm_unz_s
{
uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */
} tm_unz;
/* unz_global_info structure contain global data about the ZIPfile
These data comes from the end of central dir */
typedef struct unz_global_info_s
{
uLong number_entry; /* total number of entries in
the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info;
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info_s
{
uLong version; /* version made by 2 bytes */
uLong version_needed; /* version needed to extract 2 bytes */
uLong flag; /* general purpose bit flag 2 bytes */
uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */
uLong compressed_size; /* compressed size 4 bytes */
uLong uncompressed_size; /* uncompressed size 4 bytes */
uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */
uLong disk_num_start; /* disk number start 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info;
extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
const char* fileName2,
int iCaseSensitivity));
/*
Compare two filename (fileName1,fileName2).
If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
or strcasecmp)
If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
(like 1 on Unix, 2 on Windows)
*/
extern unzFile ZEXPORT unzOpen OF((const char *path));
/*
Open a Zip file. path contain the full pathname (by example,
on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
"zlib/zlib113.zip".
If the zipfile cannot be opened (file don't exist or in not valid), the
return value is NULL.
Else, the return value is a unzFile Handle, usable with other function
of this unzip package.
*/
extern unzFile ZEXPORT unzOpen2 OF((const char *path,
zlib_filefunc_def* pzlib_filefunc_def));
/*
Open a Zip file, like unzOpen, but provide a set of file low level API
for read/write the zip file (see ioapi.h)
*/
extern int ZEXPORT unzClose OF((unzFile file));
/*
Close a ZipFile opened with unzipOpen.
If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
unz_global_info *pglobal_info));
/*
Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
char *szComment,
uLong uSizeBuf));
/*
Get the global comment string of the ZipFile, in the szComment buffer.
uSizeBuf is the size of the szComment buffer.
return the number of byte copied or an error code <0
*/
/***************************************************************************/
/* Unzip package allow you browse the directory of the zipfile */
extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
/*
Set the current file of the zipfile to the first file.
return UNZ_OK if there is no problem
*/
extern int ZEXPORT unzGoToNextFile OF((unzFile file));
/*
Set the current file of the zipfile to the next file.
return UNZ_OK if there is no problem
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
*/
extern int ZEXPORT unzLocateFile OF((unzFile file,
const char *szFileName,
int iCaseSensitivity));
/*
Try locate the file szFileName in the zipfile.
For the iCaseSensitivity signification, see unzStringFileNameCompare
return value :
UNZ_OK if the file is found. It becomes the current file.
UNZ_END_OF_LIST_OF_FILE if the file is not found
*/
/* ****************************************** */
/* Ryan supplied functions */
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_pos_s
{
uLong pos_in_zip_directory; /* offset in zip file directory */
uLong num_of_file; /* # of file */
} unz_file_pos;
extern int ZEXPORT unzGetFilePos(
unzFile file,
unz_file_pos* file_pos);
extern int ZEXPORT unzGoToFilePos(
unzFile file,
unz_file_pos* file_pos);
/* ****************************************** */
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
unz_file_info *pfile_info,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
/*
Get Info about the current file
if pfile_info!=NULL, the *pfile_info structure will contain somes info about
the current file
if szFileName!=NULL, the filemane string will be copied in szFileName
(fileNameBufferSize is the size of the buffer)
if extraField!=NULL, the extra field information will be copied in extraField
(extraFieldBufferSize is the size of the buffer).
This is the Central-header version of the extra field
if szComment!=NULL, the comment string of the file will be copied in szComment
(commentBufferSize is the size of the buffer)
*/
/***************************************************************************/
/* for reading the content of the current zipfile, you can open it, read data
from it, and close it (you can close it before reading all the file)
*/
extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
/*
Open for reading data the current file in the zipfile.
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
const char* password));
/*
Open for reading data the current file in the zipfile.
password is a crypting password
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file,
int* method,
int* level,
int raw));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file,
int* method,
int* level,
int raw,
const char* password));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
/*
Close the file in zip opened with unzOpenCurrentFile
Return UNZ_CRCERROR if all the file was read but the CRC is not good
*/
extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
voidp buf,
unsigned len));
/*
Read bytes from the current file (opened by unzOpenCurrentFile)
buf contain buffer where data must be copied
len the size of buf.
return the number of byte copied if somes bytes are copied
return 0 if the end of file was reached
return <0 with error code if there is an error
(UNZ_ERRNO for IO error, or zLib error for uncompress error)
*/
extern z_off_t ZEXPORT unztell OF((unzFile file));
/*
Give the current position in uncompressed data
*/
extern int ZEXPORT unzeof OF((unzFile file));
/*
return 1 if the end of file was reached, 0 elsewhere
*/
extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
voidp buf,
unsigned len));
/*
Read extra field from the current file (opened by unzOpenCurrentFile)
This is the local-header version of the extra field (sometimes, there is
more info in the local-header version than in the central-header)
if buf==NULL, it return the size of the local extra field
if buf!=NULL, len is the size of the buffer, the extra header is copied in
buf.
the return value is the number of bytes copied in buf, or (if <0)
the error code
*/
/***************************************************************************/
/* Get the current file offset */
extern uLong ZEXPORT unzGetOffset (unzFile file);
/* Set the current file offset */
extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
#ifdef __cplusplus
}
#endif
#endif /* _unz_H */

View File

@ -0,0 +1,184 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "gambatte.h"
#include "cpu.h"
#include "savestate.h"
#include "statesaver.h"
#include "initstate.h"
#include "state_osd_elements.h"
#include <string>
#include <sstream>
static const std::string itos(int i) {
std::stringstream ss;
ss << i;
std::string out;
ss >> out;
return out;
}
static const std::string statePath(const std::string &basePath, int stateNo) {
return basePath + "_" + itos(stateNo) + ".gqs";
}
namespace Gambatte {
GB::GB() : z80(new CPU), stateNo(1) {}
GB::~GB() {
delete z80;
}
unsigned GB::runFor(Gambatte::uint_least32_t *const soundBuf, const unsigned samples) {
z80->setSoundBuffer(soundBuf);
z80->runFor(samples * 2);
return z80->fillSoundBuffer();
}
void GB::updateVideo() {
return z80->updateVideo();
}
unsigned GB::lyCounter() {
return z80->lyCounter();
}
void GB::reset() {
z80->saveSavedata();
SaveState state;
z80->setStatePtrs(state);
setInitState(state, z80->isCgb());
z80->loadState(state);
z80->loadSavedata();
// z80->reset();
}
void GB::setVideoBlitter(VideoBlitter *vb) {
z80->setVideoBlitter(vb);
}
void GB::videoBufferChange() {
z80->videoBufferChange();
}
unsigned GB::videoWidth() const {
return z80->videoWidth();
}
unsigned GB::videoHeight() const {
return z80->videoHeight();
}
void GB::setVideoFilter(const unsigned n) {
z80->setVideoFilter(n);
}
std::vector<const FilterInfo*> GB::filterInfo() const {
return z80->filterInfo();
}
void GB::setInputStateGetter(InputStateGetter *getInput) {
z80->setInputStateGetter(getInput);
}
void GB::setMemoryInterface(MemoryInterface *memoryInterface) {
z80->setMemoryInterface(memoryInterface);
}
void GB::set_savedir(const char *sdir) {
z80->set_savedir(sdir);
}
bool GB::load(const bool forceDmg) {
z80->saveSavedata();
const bool failed = z80->load(forceDmg);
if (!failed) {
SaveState state;
z80->setStatePtrs(state);
setInitState(state, z80->isCgb());
z80->loadState(state);
z80->loadSavedata();
stateNo = 1;
z80->setOsdElement(std::auto_ptr<OsdElement>());
}
return failed;
}
void GB::save() {
z80->saveSavedata();
}
bool GB::isCgb() const {
return z80->isCgb();
}
void GB::setDmgPaletteColor(unsigned palNum, unsigned colorNum, unsigned rgb32) {
z80->setDmgPaletteColor(palNum, colorNum, rgb32);
}
void GB::loadState(const char *const filepath, const bool osdMessage) {
z80->saveSavedata();
SaveState state;
z80->setStatePtrs(state);
if (StateSaver::loadState(state, filepath)) {
z80->loadState(state);
if (osdMessage)
z80->setOsdElement(newStateLoadedOsdElement(stateNo));
}
}
void GB::saveState() {
saveState(statePath(z80->saveBasePath(), stateNo).c_str());
z80->setOsdElement(newStateSavedOsdElement(stateNo));
}
void GB::loadState() {
loadState(statePath(z80->saveBasePath(), stateNo).c_str(), true);
}
void GB::saveState(const char *filepath) {
SaveState state;
z80->setStatePtrs(state);
z80->saveState(state);
StateSaver::saveState(state, filepath);
}
void GB::loadState(const char *const filepath) {
loadState(filepath, false);
}
void GB::selectState(int n) {
n -= (n / 10) * 10;
stateNo = n < 0 ? n + 10 : n;
z80->setOsdElement(newSaveStateOsdElement(statePath(z80->saveBasePath(), stateNo).c_str(), stateNo));
}
}

View File

@ -0,0 +1,281 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "initstate.h"
#include "savestate.h"
#include <cstring>
#include <algorithm>
#include "sound/sound_unit.h"
#include "memory.h"
void setInitState(SaveState &state, const bool cgb) {
static const unsigned char feaxDump[0x60] = {
0x18, 0x01, 0xEF, 0xDE, 0x06, 0x4A, 0xCD, 0xBD,
0x18, 0x01, 0xEF, 0xDE, 0x06, 0x4A, 0xCD, 0xBD,
0x18, 0x01, 0xEF, 0xDE, 0x06, 0x4A, 0xCD, 0xBD,
0x18, 0x01, 0xEF, 0xDE, 0x06, 0x4A, 0xCD, 0xBD,
0x00, 0x90, 0xF7, 0x7F, 0xC0, 0xB1, 0xB4, 0xFB,
0x00, 0x90, 0xF7, 0x7F, 0xC0, 0xB1, 0xB4, 0xFB,
0x00, 0x90, 0xF7, 0x7F, 0xC0, 0xB1, 0xB4, 0xFB,
0x00, 0x90, 0xF7, 0x7F, 0xC0, 0xB1, 0xB4, 0xFB,
0x24, 0x1B, 0xFD, 0x3A, 0x10, 0x12, 0xAD, 0x45,
0x24, 0x1B, 0xFD, 0x3A, 0x10, 0x12, 0xAD, 0x45,
0x24, 0x1B, 0xFD, 0x3A, 0x10, 0x12, 0xAD, 0x45,
0x24, 0x1B, 0xFD, 0x3A, 0x10, 0x12, 0xAD, 0x45
};
static const unsigned char ffxxDump[0x100] = {
0xCF, 0x00, 0x7C, 0xFF, 0x43, 0x00, 0x00, 0xF8,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE1,
0x80, 0xBF, 0xF3, 0xFF, 0xBF, 0xFF, 0x3F, 0x00,
0xFF, 0xBF, 0x7F, 0xFF, 0x9F, 0xFF, 0xBF, 0xFF,
0xFF, 0x00, 0x00, 0xBF, 0x77, 0xF3, 0xF1, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x7E, 0xFF, 0xFE,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC0, 0xFF, 0xC1, 0x00, 0xFE, 0xFF, 0xFF, 0xFF,
0xF8, 0xFF, 0x00, 0x00, 0x00, 0x8F, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D,
0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99,
0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E,
0x45, 0xEC, 0x52, 0xFA, 0x08, 0xB7, 0x07, 0x5D,
0x01, 0xFD, 0xC0, 0xFF, 0x08, 0xFC, 0x00, 0xE5,
0x0B, 0xF8, 0xC2, 0xCE, 0xF4, 0xF9, 0x0F, 0x7F,
0x45, 0x6D, 0x3D, 0xFE, 0x46, 0x97, 0x33, 0x5E,
0x08, 0xEF, 0xF1, 0xFF, 0x86, 0x83, 0x24, 0x74,
0x12, 0xFC, 0x00, 0x9F, 0xB4, 0xB7, 0x06, 0xD5,
0xD0, 0x7A, 0x00, 0x9E, 0x04, 0x5F, 0x41, 0x2F,
0x1D, 0x77, 0x36, 0x75, 0x81, 0xAA, 0x70, 0x3A,
0x98, 0xD1, 0x71, 0x02, 0x4D, 0x01, 0xC1, 0xFF,
0x0D, 0x00, 0xD3, 0x05, 0xF9, 0x00, 0x0B, 0x00
};
static const unsigned char cgbObjpDump[0x40] = {
0x00, 0x00, 0xF2, 0xAB,
0x61, 0xC2, 0xD9, 0xBA,
0x88, 0x6E, 0xDD, 0x63,
0x28, 0x27, 0xFB, 0x9F,
0x35, 0x42, 0xD6, 0xD4,
0x50, 0x48, 0x57, 0x5E,
0x23, 0x3E, 0x3D, 0xCA,
0x71, 0x21, 0x37, 0xC0,
0xC6, 0xB3, 0xFB, 0xF9,
0x08, 0x00, 0x8D, 0x29,
0xA3, 0x20, 0xDB, 0x87,
0x62, 0x05, 0x5D, 0xD4,
0x0E, 0x08, 0xFE, 0xAF,
0x20, 0x02, 0xD7, 0xFF,
0x07, 0x6A, 0x55, 0xEC,
0x83, 0x40, 0x0B, 0x77
};
state.cpu.cycleCounter = 0x102A0;
state.cpu.PC = 0x100;
state.cpu.SP = 0xFFFE;
state.cpu.A = (cgb * 0x10) | 0x01;
state.cpu.B = 0x00;
state.cpu.C = 0x13;
state.cpu.D = 0x00;
state.cpu.E = 0xD8;
state.cpu.F = 0xB0;
state.cpu.H = 0x01;
state.cpu.L = 0x4D;
state.cpu.skip = false;
state.cpu.halted = false;
std::memset(state.mem.vram.ptr, 0, state.mem.vram.getSz());
std::memset(state.mem.sram.ptr, 0xFF, state.mem.sram.getSz());
for (unsigned addr = 0x0000; addr < 0x0800; addr += 0x10) {
std::memset(state.mem.wram.ptr + addr + 0x00, 0xFF, 0x08);
std::memset(state.mem.wram.ptr + addr + 0x08, 0x00, 0x08);
}
for (unsigned addr = 0x0800; addr < 0x1000; addr += 0x10) {
std::memset(state.mem.wram.ptr + addr + 0x00, 0x00, 0x08);
std::memset(state.mem.wram.ptr + addr + 0x08, 0xFF, 0x08);
}
for (unsigned addr = 0x0E00; addr < 0x1000; addr += 0x10) {
state.mem.wram.ptr[addr + 0x02] = 0xFF;
state.mem.wram.ptr[addr + 0x0A] = 0x00;
}
for (unsigned addr = 0x1000; addr < state.mem.wram.getSz(); addr += 0x1000)
std::memcpy(state.mem.wram.ptr + addr, state.mem.wram.ptr, 0x1000);
std::memset(state.mem.ioamhram.ptr, 0x00, state.mem.ioamhram.getSz());
std::memcpy(state.mem.ioamhram.ptr + 0xA0, feaxDump, sizeof(feaxDump));
std::memcpy(state.mem.ioamhram.ptr + 0x100, ffxxDump, sizeof(ffxxDump));
state.mem.ioamhram.ptr[0x104] = 0x1C;
state.mem.ioamhram.ptr[0x140] = 0x91;
state.mem.ioamhram.ptr[0x144] = 0x00;
if (!cgb) {
state.mem.ioamhram.ptr[0x130] = 0xAC;
state.mem.ioamhram.ptr[0x131] = 0xDD;
state.mem.ioamhram.ptr[0x132] = 0xDA;
state.mem.ioamhram.ptr[0x133] = 0x48;
state.mem.ioamhram.ptr[0x134] = 0x36;
state.mem.ioamhram.ptr[0x135] = 0x02;
state.mem.ioamhram.ptr[0x136] = 0xCF;
state.mem.ioamhram.ptr[0x137] = 0x16;
state.mem.ioamhram.ptr[0x138] = 0x2C;
state.mem.ioamhram.ptr[0x139] = 0x04;
state.mem.ioamhram.ptr[0x13A] = 0xE5;
state.mem.ioamhram.ptr[0x13B] = 0x2C;
state.mem.ioamhram.ptr[0x13C] = 0xAC;
state.mem.ioamhram.ptr[0x13D] = 0xDD;
state.mem.ioamhram.ptr[0x13E] = 0xDA;
state.mem.ioamhram.ptr[0x13F] = 0x48;
state.mem.ioamhram.ptr[0x14D] = 0xFF;
state.mem.ioamhram.ptr[0x14F] = 0xFF;
state.mem.ioamhram.ptr[0x156] = 0xFF;
state.mem.ioamhram.ptr[0x168] = 0xFF;
state.mem.ioamhram.ptr[0x16A] = 0xFF;
state.mem.ioamhram.ptr[0x16B] = 0xFF;
state.mem.ioamhram.ptr[0x16C] = 0xFF;
state.mem.ioamhram.ptr[0x170] = 0xFF;
state.mem.ioamhram.ptr[0x172] = 0xFF;
state.mem.ioamhram.ptr[0x173] = 0xFF;
state.mem.ioamhram.ptr[0x174] = 0xFF;
state.mem.ioamhram.ptr[0x175] = 0xFF;
state.mem.ioamhram.ptr[0x176] = 0xFF;
state.mem.ioamhram.ptr[0x177] = 0xFF;
}
state.mem.div_lastUpdate = 0;
state.mem.tima_lastUpdate = 0;
state.mem.tmatime = Memory::COUNTER_DISABLED;
state.mem.next_serialtime = Memory::COUNTER_DISABLED;
state.mem.lastOamDmaUpdate = Memory::COUNTER_DISABLED;
state.mem.minIntTime = 0;
state.mem.rombank = 1;
state.mem.dmaSource = 0;
state.mem.dmaDestination = 0;
state.mem.rambank = 0;
state.mem.oamDmaPos = 0xFE;
state.mem.IME = false;
state.mem.enable_ram = false;
state.mem.rambank_mode = false;
state.mem.hdma_transfer = false;
for (unsigned i = 0x00; i < 0x40; i += 0x02) {
state.ppu.bgpData.ptr[i] = 0xFF;
state.ppu.bgpData.ptr[i + 1] = 0x7F;
}
std::memcpy(state.ppu.objpData.ptr, cgbObjpDump, sizeof(cgbObjpDump));
if (!cgb) {
state.ppu.bgpData.ptr[0] = state.mem.ioamhram.get()[0x147];
state.ppu.objpData.ptr[0] = state.mem.ioamhram.get()[0x148];
state.ppu.objpData.ptr[1] = state.mem.ioamhram.get()[0x149];
}
for (unsigned pos = 0; pos < 80; ++pos)
state.ppu.oamReaderBuf.ptr[pos] = state.mem.ioamhram.ptr[((pos * 2) & ~3) | (pos & 1)];
std::fill_n(state.ppu.oamReaderSzbuf.ptr, 40, false);
state.ppu.videoCycles = 144*456ul + 164;
state.ppu.enableDisplayM0Time = state.cpu.cycleCounter - state.ppu.videoCycles + 159;
state.ppu.winYPos = 0xFF;
state.ppu.drawStartCycle = 90;
state.ppu.scReadOffset = 90;
state.ppu.lcdc = state.mem.ioamhram.get()[0x140];
state.ppu.scx[1] = state.ppu.scx[0] = 0;
state.ppu.scy[1] = state.ppu.scy[0] = 0;
state.ppu.scxAnd7 = 0;
state.ppu.weMaster = false;
state.ppu.wx = 0;
state.ppu.wy = 0;
state.ppu.lycIrqSkip = false;
state.spu.cycleCounter = 0x1000 | ((state.cpu.cycleCounter >> 1) & 0xFFF); // spu.cycleCounter >> 12 & 7 represents the frame sequencer position.
state.spu.ch1.sweep.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch1.sweep.shadow = 0;
state.spu.ch1.sweep.nr0 = 0;
state.spu.ch1.sweep.negging = false;
state.spu.ch1.duty.nextPosUpdate = (state.spu.cycleCounter & ~1) + 2048 * 2;
state.spu.ch1.duty.nr3 = 0;
state.spu.ch1.duty.pos = 0;
state.spu.ch1.env.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch1.env.volume = 0;
state.spu.ch1.lcounter.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch1.lcounter.lengthCounter = 0x40;
state.spu.ch1.nr4 = 0;
state.spu.ch1.master = true;
state.spu.ch2.duty.nextPosUpdate = (state.spu.cycleCounter & ~1) + 2048 * 2;
state.spu.ch2.duty.nr3 = 0;
state.spu.ch2.duty.pos = 0;
state.spu.ch2.env.counter = state.spu.cycleCounter - ((state.spu.cycleCounter - 0x1000) & 0x7FFF) + 8ul * 0x8000;
state.spu.ch2.env.volume = 0;
state.spu.ch2.lcounter.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch2.lcounter.lengthCounter = 0x40;
state.spu.ch2.nr4 = 0;
state.spu.ch2.master = false;
for (unsigned i = 0; i < 0x10; ++i)
state.spu.ch3.waveRam.ptr[i] = state.mem.ioamhram.get()[0x130 + i];
state.spu.ch3.lcounter.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch3.lcounter.lengthCounter = 0x100;
state.spu.ch3.waveCounter = SoundUnit::COUNTER_DISABLED;
state.spu.ch3.lastReadTime = SoundUnit::COUNTER_DISABLED;
state.spu.ch3.nr3 = 0;
state.spu.ch3.nr4 = 0;
state.spu.ch3.wavePos = 0;
state.spu.ch3.sampleBuf = 0;
state.spu.ch3.master = false;
state.spu.ch4.lfsr.counter = state.spu.cycleCounter + 4;
state.spu.ch4.lfsr.reg = 0xFF;
state.spu.ch4.env.counter = state.spu.cycleCounter - ((state.spu.cycleCounter - 0x1000) & 0x7FFF) + 8ul * 0x8000;
state.spu.ch4.env.volume = 0;
state.spu.ch4.lcounter.counter = SoundUnit::COUNTER_DISABLED;
state.spu.ch4.lcounter.lengthCounter = 0x40;
state.spu.ch4.nr4 = 0;
state.spu.ch4.master = false;
state.rtc.baseTime = std::time(0);
state.rtc.haltTime = state.rtc.baseTime;
state.rtc.index = 5;
state.rtc.dataDh = 0;
state.rtc.dataDl = 0;
state.rtc.dataH = 0;
state.rtc.dataM = 0;
state.rtc.dataS = 0;
state.rtc.lastLatchData = false;
}

View File

@ -0,0 +1,26 @@
/***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INITSTATE_H
#define INITSTATE_H
class SaveState;
void setInitState(SaveState &state, bool cgb);
#endif

View File

@ -0,0 +1,51 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INSERTION_SORT_H
#define INSERTION_SORT_H
#include <functional>
template<typename T, class Less>
void insertionSort(T *const start, T *const end, Less less) {
if (start >= end)
return;
T *a = start;
while (++a < end) {
const T e = *a;
T *b = a;
while (b != start && less(e, *(b - 1))) {
*b = *(b - 1);
b = b - 1;
}
*b = e;
}
}
template<typename T>
inline void insertionSort(T *const start, T *const end) {
insertionSort(start, end, std::less<T>());
}
#endif /*INSERTION_SORT_H*/

View File

@ -0,0 +1,44 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "interrupter.h"
#include "memory.h"
Interrupter::Interrupter(unsigned short &SP_in, unsigned short &PC_in, bool &halted_in) :
SP(SP_in),
PC(PC_in),
halted(halted_in)
{}
unsigned long Interrupter::interrupt(const unsigned address, unsigned long cycleCounter, Memory &memory) {
if (halted && memory.isCgb())
cycleCounter += 4;
halted = false;
cycleCounter += 8;
SP = (SP - 1) & 0xFFFF;
memory.write(SP, PC >> 8, cycleCounter);
cycleCounter += 4;
SP = (SP - 1) & 0xFFFF;
memory.write(SP, PC & 0xFF, cycleCounter);
PC = address;
cycleCounter += 8;
return cycleCounter;
}

View File

@ -0,0 +1,38 @@
/***************************************************************************
* Copyright (C) 2007 by Sindre Aam<EFBFBD>s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* 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 version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INTERRUPTER_H
#define INTERRUPTER_H
class Memory;
class Interrupter {
unsigned short &SP;
unsigned short &PC;
bool &halted;
public:
Interrupter(unsigned short &SP, unsigned short &PC, bool &halted);
unsigned long interrupt(const unsigned address, unsigned long cycleCounter, Memory &memory);
void unhalt() {
halted = false;
}
};
#endif

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More