id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
752,567
Image.h
Wargus_stargus/src/dat/Image.h
/* * Image.h * * Author: Andreas Volz */ #ifndef IMAGE_H #define IMAGE_H // project #include "ObjectAccess.h" #include "PropertyNotAvailableException.h" #include "IScript.h" namespace dat { /** * Wrapper interface for Kaitai parser images_dat.ksy, but with easier access in the game logic. * New functions are added on need as wrapper functions. The function names should stay the same * and documentation in only mandatory if needed to understand the difference. * */ class Image : public ObjectAccess { public: Image(DataHub &datahub, unsigned int id); virtual ~Image(); uint32_t grp(); TblEntry grp_tbl(); bool gfx_turns(); bool clickable(); bool use_full_iscript(); bool draw_if_cloaked(); images_dat_t::draw_function_enum_t draw_function(); images_dat_t::remapping_enum_t remapping(); uint32_t iscript(); IScript iscript_obj(); uint32_t shield_overlay(); TblEntry shield_overlay_tbl(); uint32_t attack_overlay(); TblEntry attack_overlay_tbl(); uint32_t damage_overlay(); TblEntry damage_overlay_tbl(); uint32_t special_overlay(); TblEntry special_overlay_tbl(); uint32_t landing_dust_overlay(); TblEntry landing_dust_overlay_tbl(); uint32_t lift_off_dust_overlay(); TblEntry lift_off_dust_overlay_tbl(); /***/ std::string getIDString(); static const int overlay_none = 0; private: }; } /* namespace dat */ #endif /* IMAGE_H */
1,424
C++
.h
53
24.226415
96
0.729027
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,568
ObjectAccess.h
Wargus_stargus/src/dat/ObjectAccess.h
/* * ObjectAccess.h * * Author: Andreas Volz */ #ifndef OBJECTACCESS_H #define OBJECTACCESS_H // project #include "DataHub.h" namespace dat { class ObjectAccess { public: ObjectAccess(DataHub &datahub, unsigned int id) : mDatahub(datahub), mId(id) {} virtual ~ObjectAccess() {} virtual unsigned int id() {return mId;} //virtual std::string id_string() = 0; protected: DataHub &mDatahub; unsigned int mId; }; } /* namespace dat */ #endif /* OBJECTACCESS_H */
488
C++
.h
24
18.291667
81
0.714286
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,569
Techdata.h
Wargus_stargus/src/dat/Techdata.h
/* * Techdata.h * * Author: Andreas */ #ifndef TECHDATA_H #define TECHDATA_H #include "ObjectAccess.h" namespace dat { class Techdata : public ObjectAccess { public: Techdata(DataHub &datahub, unsigned int id); virtual ~Techdata(); uint16_t mineral_cost(); uint16_t vespene_cost(); uint16_t research_time(); uint16_t energy_required(); uint32_t unknown4(); uint16_t icon(); uint16_t label(); TblEntry label_tbl(); uint8_t race(); uint8_t unused(); bool broodwar_flag(); bool has_broodwar_flag(); /* constants */ static const int label_none = 0; }; } /* namespace dat */ #endif /* TECHDATA_H */
653
C++
.h
32
17.71875
46
0.691542
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,570
Tbl.h
Wargus_stargus/src/dat/Tbl.h
/* * Tbl.h * * Author: Andreas Volz */ #ifndef TBL_H #define TBL_H // Local #include "kaitai/file_tbl.h" #include "TblEntry.h" // System #include <memory> namespace dat { class Tbl { public: Tbl(); virtual ~Tbl(); std::vector<TblEntry> convertFromStream(std::shared_ptr<kaitai::kstream> ks); private: void removeDoubleSpaces(std::string &str); }; } /* namespace dat */ #endif /* TBL_H */
416
C++
.h
24
15.375
79
0.692913
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,571
Unit.h
Wargus_stargus/src/dat/Unit.h
/* * Unit.h * * Author: Andreas Volz */ #ifndef UNIT_H #define UNIT_H // project #include "Flingy.h" #include "ObjectAccess.h" #include "Portrait.h" #include "Sfx.h" #include "PropertyNotAvailableException.h" #include "Weapon.h" #include "Order.h" namespace dat { class Unit : public ObjectAccess { public: Unit(DataHub &datahub, unsigned int id, const std::string &identString); virtual ~Unit(); TblEntry name_tbl(); uint8_t flingy(); Flingy flingy_obj(); uint16_t subunit1(); Unit subunit1_obj(); uint16_t subunit2(); Unit subunit2_obj(); uint16_t infestation(); Unit infestation_obj(); uint32_t construction_animation(); Image construction_animation_obj(); uint8_t unit_direction(); uint8_t shield_enable(); uint16_t shield_amount(); uint32_t hitpoints(); uint8_t elevation_level(); uint8_t unknown(); uint8_t rank(); uint8_t ai_computer_idle(); Order ai_computer_idle_obj(); uint8_t ai_human_idle(); Order ai_human_idle_obj(); uint8_t ai_return_to_idle(); Order ai_return_to_idle_obj(); uint8_t ai_attack_unit(); Order ai_attack_unit_obj(); uint8_t ai_attack_move(); Order ai_attack_move_obj(); uint8_t ground_weapon(); Weapon ground_weapon_obj(); uint8_t max_ground_hits(); uint8_t air_weapon(); Weapon air_weapon_obj(); uint8_t max_air_hits(); uint8_t ai_internal(); units_dat_t::special_ability_flags_type_t* special_ability_flags(); uint8_t target_acquisition_range(); uint8_t sight_range(); uint8_t armor_upgrade(); units_dat_t::unit_size_enum_t unit_size(); uint8_t armor(); units_dat_t::right_click_action_enum_t right_click_action(); uint16_t ready_sound(); Sfx ready_sound_obj(); uint16_t what_sound_start(); uint16_t what_sound_end(); std::vector<Sfx> what_sound_obj(); uint16_t piss_sound_start(); uint16_t piss_sound_end(); std::vector<Sfx> piss_sound_obj(); uint16_t yes_sound_start(); uint16_t yes_sound_end(); std::vector<Sfx> yes_sound_obj(); units_dat_t::staredit_placement_box_type_t* staredit_placement_box(); units_dat_t::addon_position_type_t* addon_position(); units_dat_t::unit_dimension_type_t *unit_dimension(); uint16_t portrait(); Portrait portrait_obj(); uint16_t mineral_cost(); uint16_t vespene_cost(); uint16_t build_time(); uint16_t requirements(); units_dat_t::staredit_group_flags_type_t* staredit_group_flags(); uint8_t supply_required(); uint8_t space_provided(); uint16_t build_score(); uint16_t destroy_score(); uint16_t unit_map_string(); uint8_t broodwar_flag(); units_dat_t::staredit_availability_flags_type_t* staredit_availability_flags(); bool is_format_bw(); std::string getIDString(); /* constants */ static const int portrait_none = 65535; static const int sound_none = 0; static const int construction_none = 0; static const int subunit_none = 228; static const int infestation_none = 228; private: std::string mIdentString; }; } /* namespace dat */ #endif /* UNIT_H */
3,061
C++
.h
105
25.92381
81
0.708102
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,572
Sfx.h
Wargus_stargus/src/dat/Sfx.h
/* * Sound.h * * Author: Andreas Volz */ #ifndef SFX_H #define SFX_H // project #include "ObjectAccess.h" //system #include <memory> namespace dat { class Sfx : public ObjectAccess { public: Sfx(DataHub &datahub, unsigned int id); virtual ~Sfx(); uint32_t sound_file(); TblEntry sound_file_tbl(); uint8_t unknown1(); uint8_t unknown2(); uint8_t unknown3(); uint8_t unknown4(); private: }; } /* namespace dat */ #endif /* SFX_H */
470
C++
.h
28
14.535714
41
0.686183
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,573
Order.h
Wargus_stargus/src/dat/Order.h
/* * Order.h * * Author: Andreas Volz */ #ifndef ORDER_H #define ORDER_H // project #include "ObjectAccess.h" #include "Weapon.h" #include "Techdata.h" namespace dat { class Order : public ObjectAccess { public: Order(DataHub &datahub, unsigned int id); virtual ~Order(); uint16_t label(); TblEntry label_tbl(); bool use_weapon_targeting(); uint8_t unknown2(); uint8_t unknown3(); uint8_t unknown4(); uint8_t unknown5(); uint8_t interruptible(); uint8_t unknown7(); uint8_t queueable(); uint8_t unknown9(); uint8_t unknown10(); uint8_t unknown11(); uint8_t unknown12(); uint8_t targeting(); Weapon targeting_obj(); uint8_t energy(); Techdata energy_obj(); uint8_t animation(); uint8_t highlight(); uint8_t unknown17(); uint8_t obscured_order(); // TODO: the recursive object return logic doesn't work here as this ends in a endless loop //Order obscured_order_obj(); }; } /* namespace dat */ #endif /* ORDER_H */
1,001
C++
.h
45
19.4
93
0.697524
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,574
PropertyNotAvailableException.h
Wargus_stargus/src/dat/PropertyNotAvailableException.h
/* * PropertyNotAvailableException.h * * Author: Andreas Volz */ #ifndef PROPERTYNOTAVAILABLEEXCEPTION_H #define PROPERTYNOTAVAILABLEEXCEPTION_H #include <string> namespace dat { /** * This Exception is thrown if a property isn't available for a specific item, but requested by the caller */ class PropertyNotAvailableException : public std::exception { public: PropertyNotAvailableException(int parent_id, const std::string &property) : m_parent_id(parent_id), m_property(property) {} virtual ~PropertyNotAvailableException() throw() {} const char *what() const throw(); private: int m_parent_id; std::string m_property; }; } /* namespace dat */ #endif /* PROPERTYNOTAVAILABLEEXCEPTION_H */
732
C++
.h
27
24.814815
106
0.761494
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,575
Flingy.h
Wargus_stargus/src/dat/Flingy.h
/* * Flingy.h * * Author: andreas */ #ifndef FLINGY_H #define FLINGY_H // project #include "ObjectAccess.h" #include "Sprite.h" namespace dat { class Flingy : public ObjectAccess { public: Flingy(DataHub &datahub, unsigned int id); virtual ~Flingy(); uint16_t sprite(); Sprite sprite_obj(); uint32_t speed(); uint16_t acceleration(); uint32_t halt_distance(); uint8_t turn_radius(); uint8_t unused(); uint8_t movement_control(); private: }; } /* namespace dat */ #endif /* FLINGY_H */
529
C++
.h
29
15.896552
44
0.696907
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,576
Weapon.h
Wargus_stargus/src/dat/Weapon.h
/* * Weapon.h * * Author: Andreas Volz */ #ifndef WEAPON_H #define WEAPON_H #include "DataHub.h" #include "ObjectAccess.h" #include "PropertyNotAvailableException.h" #include "Flingy.h" #include "Upgrade.h" namespace dat { class Weapon : public ObjectAccess { public: Weapon(DataHub &datahub, unsigned int id); virtual ~Weapon(); uint16_t label(); TblEntry label_tbl(); uint32_t graphics(); Flingy graphics_obj(); // TODO: make enum as return uint8_t explosion(); uint16_t target_flags(); uint32_t minimum_range(); uint32_t maximum_range(); uint8_t damage_upgrade(); Upgrade damage_upgrade_obj(); uint8_t weapon_type(); // TODO: make enum as return uint8_t weapon_behaviour(); uint8_t remove_after(); // TODO: make enum as return uint8_t explosive_type(); uint16_t inner_splash_range(); uint16_t medium_splash_range(); uint16_t outer_splash_range(); uint16_t damage_amount(); uint16_t damage_bonus(); uint8_t weapon_cooldown(); uint8_t damage_factor(); uint8_t attack_angle(); uint8_t launch_spin(); uint8_t x_offset(); uint8_t y_offset(); uint16_t error_message(); TblEntry error_message_tbl(); uint16_t icon(); /* constants */ static const int graphics_none = 0; static const int label_none = 0; private: }; } /* namespace dat */ #endif /* WEAPON_H */
1,371
C++
.h
57
21.087719
44
0.702111
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,577
IScript.h
Wargus_stargus/src/dat/IScript.h
/* * IScript.h * * Author: Andreas Volz */ #ifndef ISCRIPT_H #define ISCRIPT_H // project #include "ObjectAccess.h" namespace dat { class IScript: public ObjectAccess { public: IScript(DataHub &datahub, unsigned int id); virtual ~IScript(); enum AnimationType { Init, // Initial animation Death, // Death animation GndAttkInit, // Initial ground attack animation AirAttkInit, // Initial air attack animation Unused1, // Unknown/unused animation GndAttkRpt, // Repeated ground attack animation AirAttkRpt, // Repeated air attack animation CastSpell, // Spell casting animation GndAttkToIdle, // Animation for returning to an idle state after a ground attack AirAttkToIdle, // Animation for returning to an idle state after an air attack Unused2, // Unknown/unused animation Walking, // Walking/moving animation WalkingToIdle, // Animation for returning to an idle state after walking/moving SpecialState1, // Some sort of category of special animations, in some cases an in-transit animation, sometimes used for special orders, sometimes having to do with the animation when something finishes morphing, or the first stage of a construction animation SpecialState2, // Some sort of category of special animations, in some cases a burrowed animation, sometimes used for special orders, sometimes having to do with the animation when canceling a morph, or the second stage of a construction animation AlmostBuilt, // An animation for one part of the building process Built, // Final animation before finishing being built Landing, // Landing animation LiftOff, // Lifting off animation IsWorking, // Animation for when researching an upgrade/technology or training/building units and some other animations for some sort of work being done WorkingToIdle, // Animation for returning to an idle state after IsWorking WarpIn, // Warping in animation Unused3, // Unknown/unused animation StarEditInit, // Previously called InitTurret, this is actually an alternate initial animation for StarEdit a.k.a. the Campaign Editor Disable, // Animation for becoming disabled, either through the "Set Doodad State" trigger action or by not being in the psi field of any pylons Burrow, // Burrowing animation UnBurrow, // Unburrowing animation Enable // Animation for becoming enabled, either through the "Set Doodad State" trigger action or by being in the psi field of a pylon }; std::vector<iscript_bin_t::opcode_type_t*> getAnimationScript(IScript::AnimationType animationType); std::vector<iscript_bin_t::opcode_type_t*> getAnimationScript(unsigned int animationType); int8_t getAnimationCount(); /** * @return true in case the iscript format is broodwar. (Nothing to do as the parser detects and handles the format itself) */ bool is_format_bw(); private: }; } /* namespace dat */ #endif /* ISCRIPT_H */
3,012
C++
.h
58
47.224138
265
0.745665
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,578
DataHub.h
Wargus_stargus/src/dat/DataHub.h
/* * DataHub.h * * Author: Andreas Volz */ #ifndef DATAHUB_H #define DATAHUB_H // project #include "KaitaiConverter.h" #include "Palette.h" #include "Palette2D.h" #include "Tbl.h" #include "kaitai/units_dat.h" #include "kaitai/weapons_dat.h" #include "kaitai/flingy_dat.h" #include "kaitai/sprites_dat.h" #include "kaitai/images_dat.h" #include "kaitai/sfxdata_dat.h" #include "kaitai/portdata_dat.h" #include "kaitai/upgrades_dat.h" #include "kaitai/orders_dat.h" #include "kaitai/techdata_dat.h" #include "kaitai/mapdata_dat.h" #include "kaitai/iscript_bin.h" // System #include <nlohmann/json.hpp> #include <map> using json = nlohmann::json; namespace dat { /** * The DataHub parses the complete data structures inside those files: * - arr\\units.dat * - arr\\orders.dat * - arr\\weapons.dat * - arr\\flingy.dat * - arr\\sprites.dat * - arr\\images.dat * - arr\\sfxdata.dat * - arr\\portdata.dat * - arr\\upgrades.dat * - arr\\techdata.dat * - arr\\mapdata.dat * - arr\\images.tbl * - arr\\sfxdata.tbl * - arr\\portdata.tbl * - arr\\mapdata.tbl * - rez\\stat_txt.tbl * * As those data has have depends on each other they're all parsed together in one run. After being parsed * to Kaitai data structures they could be accessed from outside. * * The Kaitai parsed objects in this class are by intension public. There's no benefit in putting dozen silly * getter around them. The alternative to put them private means to implement every parser logic * inside this class or friend them all. * * So the design decision is just to let them public and the outside accessing function should only read them! * If I ever put this stuff to a general purpose library this design might change. * * "with great power comes great responsibility" - (Spiderman) */ class DataHub : public KaitaiConverter { public: DataHub(std::shared_ptr<Hurricane> hurricane); virtual ~DataHub(); uint16_t getIScriptImage(uint16_t index); // Kaitai parsed objects std::shared_ptr<units_dat_t> units; std::shared_ptr<orders_dat_t> orders; std::shared_ptr<weapons_dat_t> weapons; std::shared_ptr<flingy_dat_t> flingy; std::shared_ptr<sprites_dat_t> sprites; std::shared_ptr<images_dat_t> images; std::shared_ptr<sfxdata_dat_t> sfxdata; std::shared_ptr<portdata_dat_t> portdata; std::shared_ptr<upgrades_dat_t> upgrades; std::shared_ptr<techdata_dat_t> techdata; std::shared_ptr<mapdata_dat_t> mapdata; std::shared_ptr<iscript_bin_t> iscript; // kaitai parsed Tbl vectors std::vector<TblEntry> stat_txt_tbl_vec; /*std::vector<TblEntry> stat_txt_units_tbl_vec; std::vector<TblEntry> stat_txt_weapons_tbl_vec; std::vector<TblEntry> stat_txt_error_messages_tbl_vec; std::vector<TblEntry> stat_txt_upgrades_tbl_vec; std::vector<TblEntry> stat_txt_orders_tbl_vec; std::vector<TblEntry> stat_txt_techdata_tbl_vec;*/ std::vector<TblEntry> images_tbl_vec; std::vector<TblEntry> sfxdata_tbl_vec; std::vector<TblEntry> portdata_tbl_vec; std::vector<TblEntry> mapdata_tbl_vec; private: // units.dat void init_units_dat(); // orders.dat void init_orders_dat(); // weapons.dat void init_weapons_dat(); // flingy.dat void init_flingy_dat(); // sprites.dat void init_sprites_dat(); // images.dat void init_images_dat(); // sfxdata.dat void init_sfxdata_dat(); // portdata.dat void init_portdata_dat(); // upgrades.dat void init_upgrades_dat(); // techdata.dat void init_techdata_dat(); // mapdata.dat void init_mapdata_dat(); // stat_txt.tbl void init_stat_txt_tbl(); // images.tbl void init_images_tbl(); // sfxdata.tbl void init_sfxdata_tbl(); // portdata.tbl void init_portdata_tbl(); // mapdata.tbl void init_mapdata_tbl(); // iscript.bin void init_iscript_bin(); std::shared_ptr<std::istream> m_units_stream; std::shared_ptr<std::istream> m_orders_stream; std::shared_ptr<std::istream> m_weapons_stream; std::shared_ptr<std::istream> m_flingy_stream; std::shared_ptr<std::istream> m_sprites_stream; std::shared_ptr<std::istream> m_images_stream; std::shared_ptr<std::istream> m_sfxdata_stream; std::shared_ptr<std::istream> m_portdata_stream; std::shared_ptr<std::istream> m_upgrades_stream; std::shared_ptr<std::istream> m_techdata_stream; std::shared_ptr<std::istream> m_mapdata_stream; std::shared_ptr<std::istream> m_iscript_stream; std::shared_ptr<kaitai::kstream> m_units_ks; std::shared_ptr<kaitai::kstream> m_orders_ks; std::shared_ptr<kaitai::kstream> m_weapons_ks; std::shared_ptr<kaitai::kstream> m_flingy_ks; std::shared_ptr<kaitai::kstream> m_sprites_ks; std::shared_ptr<kaitai::kstream> m_images_ks; std::shared_ptr<kaitai::kstream> m_sfxdata_ks; std::shared_ptr<kaitai::kstream> m_portdata_ks; std::shared_ptr<kaitai::kstream> m_upgrades_ks; std::shared_ptr<kaitai::kstream> m_techdata_ks; std::shared_ptr<kaitai::kstream> m_mapdata_ks; std::shared_ptr<kaitai::kstream> m_iscript_ks; std::map<uint16_t, uint16_t> m_iscriptImageEntreeMap; }; } /* namespace dat */ #endif /* DATAHUB_H */
5,105
C++
.h
155
30.380645
110
0.725442
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,579
Sprite.h
Wargus_stargus/src/dat/Sprite.h
/* * Sprite.h * * Author: Andreas */ #ifndef SPRITE_H #define SPRITE_H // project #include "ObjectAccess.h" #include "Image.h" #include "PropertyNotAvailableException.h" namespace dat { class Sprite : public ObjectAccess { public: Sprite(DataHub &datahub, unsigned int id); virtual ~Sprite(); uint16_t image(); Image image_obj(); uint8_t health_bar(); uint8_t unknown2(); bool is_visible(); uint8_t select_circle_image_size(); uint8_t select_circle_vertical_pos(); private: }; } /* namespace dat */ #endif /* SPRITE_H */
562
C++
.h
29
17.137931
44
0.712909
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,580
TblEntry.h
Wargus_stargus/src/dat/TblEntry.h
/* * TblEntry.h * * Author: Andreas Volz */ #ifndef TBLENTRY_H #define TBLENTRY_H // system #include <string> namespace dat { class TblEntry { public: TblEntry(); virtual ~TblEntry(); std::string name1(); std::string name2(); std::string name3(); int shortcut_pos(); std::string shortcut(); private: std::string m_name1; std::string m_name2; std::string m_name3; int m_shortcut_pos; std::string m_shortcut; friend class Tbl; }; } /* namespace dat */ #endif /* TBLENTRY_H */
519
C++
.h
31
14.451613
28
0.6841
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,588
FuzzerInterface.h
Wargus_stargus/subprojects/nlohmann_json/test/thirdparty/Fuzzer/FuzzerInterface.h
//===- FuzzerInterface.h - Interface header for the Fuzzer ------*- C++ -* ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Define the interface between libFuzzer and the library being tested. //===----------------------------------------------------------------------===// // NOTE: the libFuzzer interface is thin and in the majority of cases // you should not include this file into your target. In 95% of cases // all you need is to define the following function in your file: // extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size); // WARNING: keep the interface in C. #ifndef LLVM_FUZZER_INTERFACE_H #define LLVM_FUZZER_INTERFACE_H #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus // Mandatory user-provided target function. // Executes the code under test with [Data, Data+Size) as the input. // libFuzzer will invoke this function *many* times with different inputs. // Must return 0. int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size); // Optional user-provided initialization function. // If provided, this function will be called by libFuzzer once at startup. // It may read and modify argc/argv. // Must return 0. int LLVMFuzzerInitialize(int *argc, char ***argv); // Optional user-provided custom mutator. // Mutates raw data in [Data, Data+Size) inplace. // Returns the new size, which is not greater than MaxSize. // Given the same Seed produces the same mutation. size_t LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed); // Optional user-provided custom cross-over function. // Combines pieces of Data1 & Data2 together into Out. // Returns the new size, which is not greater than MaxOutSize. // Should produce the same mutation given the same Seed. size_t LLVMFuzzerCustomCrossOver(const uint8_t *Data1, size_t Size1, const uint8_t *Data2, size_t Size2, uint8_t *Out, size_t MaxOutSize, unsigned int Seed); // Experimental, may go away in future. // libFuzzer-provided function to be used inside LLVMFuzzerTestOneInput. // Mutates raw data in [Data, Data+Size) inplace. // Returns the new size, which is not greater than MaxSize. size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize); #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // LLVM_FUZZER_INTERFACE_H
2,685
C++
.h
55
45.236364
80
0.671123
Wargus/stargus
127
24
9
GPL-2.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,619
runner.cpp
byronknoll_lstm-compress/src/runner.cpp
#include <fstream> #include <ctime> #include <stdio.h> #include <cstdlib> #include <vector> #include <valarray> #include "preprocess/preprocessor.h" #include "coder/encoder.h" #include "coder/decoder.h" #include "predictor.h" namespace { const int kMinVocabFileSize = 10000; inline float Rand() { return static_cast <float> (rand()) / static_cast <float> (RAND_MAX); } } int Help() { printf("lstm-compress v3\n"); printf("With preprocessing:\n"); printf(" compress: lstm-compress -c [dictionary] [input]" " [output]\n"); printf(" only preprocessing: lstm-compress -s [dictionary] [input]" " [output]\n"); printf(" decompress: lstm-compress -d [dictionary] [input]" " [output]\n"); printf("Without preprocessing:\n"); printf(" compress: lstm-compress -c [input] [output]\n"); printf(" decompress: lstm-compress -d [input] [output]\n"); printf(" generate: lstm-compress -g [input] [output] [output size]\n"); return -1; } void WriteHeader(unsigned long long length, const std::vector<bool>& vocab, std::ofstream* os) { for (int i = 4; i >= 0; --i) { char c = length >> (8*i); os->put(c); } if (length < kMinVocabFileSize) return; for (int i = 0; i < 32; ++i) { unsigned char c = 0; for (int j = 0; j < 8; ++j) { if (vocab[i * 8 + j]) c += 1<<j; } os->put(c); } } void WriteStorageHeader(FILE* out) { for (int i = 4; i >= 0; --i) { putc(0, out); } } void ReadHeader(std::ifstream* is, unsigned long long* length, std::vector<bool>* vocab) { *length = 0; for (int i = 0; i < 5; ++i) { *length <<= 8; *length += (unsigned char)(is->get()); } if (*length == 0) return; if (*length < kMinVocabFileSize) { std::fill(vocab->begin(), vocab->end(), true); return; } for (int i = 0; i < 32; ++i) { unsigned char c = is->get(); for (int j = 0; j < 8; ++j) { if (c & (1<<j)) (*vocab)[i * 8 + j] = true; } } } void ExtractVocab(unsigned long long input_bytes, std::ifstream* is, std::vector<bool>* vocab) { for (unsigned long long pos = 0; pos < input_bytes; ++pos) { unsigned char c = is->get(); (*vocab)[c] = true; } } void Compress(unsigned long long input_bytes, std::ifstream* is, std::ofstream* os, unsigned long long* output_bytes, Predictor* p) { Encoder e(os, p); unsigned long long percent = 1 + (input_bytes / 100); for (unsigned long long pos = 0; pos < input_bytes; ++pos) { char c = is->get(); for (int j = 7; j >= 0; --j) { e.Encode((c>>j)&1); } if (pos % percent == 0) { printf("\rprogress: %lld%%", pos / percent); fflush(stdout); } } e.Flush(); *output_bytes = os->tellp(); } void Decompress(unsigned long long output_length, std::ifstream* is, std::ofstream* os, const std::vector<bool>& vocab) { Predictor p(vocab); Decoder d(is, &p); unsigned long long percent = 1 + (output_length / 100); for(unsigned long long pos = 0; pos < output_length; ++pos) { int byte = 1; while (byte < 256) { byte += byte + d.Decode(); } os->put(byte); if (pos % percent == 0) { printf("\rprogress: %lld%%", pos / percent); fflush(stdout); } } } bool Store(const std::string& input_path, const std::string& temp_path, const std::string& output_path, FILE* dictionary, unsigned long long* input_bytes, unsigned long long* output_bytes) { FILE* data_in = fopen(input_path.c_str(), "rb"); if (!data_in) return false; FILE* data_out = fopen(output_path.c_str(), "wb"); if (!data_out) return false; fseek(data_in, 0L, SEEK_END); *input_bytes = ftell(data_in); fseek(data_in, 0L, SEEK_SET); WriteStorageHeader(data_out); preprocessor::Encode(data_in, data_out, *input_bytes, temp_path, dictionary); fseek(data_out, 0L, SEEK_END); *output_bytes = ftell(data_out); fclose(data_in); fclose(data_out); return true; } bool RunCompression(bool enable_preprocess, const std::string& input_path, const std::string& temp_path, const std::string& output_path, FILE* dictionary, unsigned long long* input_bytes, unsigned long long* output_bytes) { FILE* data_in = fopen(input_path.c_str(), "rb"); if (!data_in) return false; FILE* temp_out = fopen(temp_path.c_str(), "wb"); if (!temp_out) return false; fseek(data_in, 0L, SEEK_END); *input_bytes = ftell(data_in); fseek(data_in, 0L, SEEK_SET); if (enable_preprocess) { preprocessor::Encode(data_in, temp_out, *input_bytes, temp_path, dictionary); } else { preprocessor::NoPreprocess(data_in, temp_out, *input_bytes); } fclose(data_in); fclose(temp_out); std::ifstream temp_in(temp_path, std::ios::in | std::ios::binary); if (!temp_in.is_open()) return false; std::ofstream data_out(output_path, std::ios::out | std::ios::binary); if (!data_out.is_open()) return false; temp_in.seekg(0, std::ios::end); unsigned long long temp_bytes = temp_in.tellg(); temp_in.seekg(0, std::ios::beg); std::vector<bool> vocab(256, false); if (temp_bytes < kMinVocabFileSize) { std::fill(vocab.begin(), vocab.end(), true); } else { ExtractVocab(temp_bytes, &temp_in, &vocab); temp_in.seekg(0, std::ios::beg); } WriteHeader(temp_bytes, vocab, &data_out); Predictor p(vocab); Compress(temp_bytes, &temp_in, &data_out, output_bytes, &p); temp_in.close(); data_out.close(); remove(temp_path.c_str()); return true; } bool RunGeneration(const std::string& input_path, const std::string& output_path, int output_size) { std::ifstream data_in(input_path, std::ios::in | std::ios::binary); if (!data_in.is_open()) return false; std::ofstream data_out(output_path, std::ios::out | std::ios::binary); if (!data_out.is_open()) return false; data_in.seekg(0, std::ios::end); unsigned long long input_bytes = data_in.tellg(); data_in.seekg(0, std::ios::beg); std::vector<bool> vocab(256, false); ExtractVocab(input_bytes, &data_in, &vocab); data_in.seekg(0, std::ios::beg); int vocab_size = 0; for (int i = 0; i < 256; ++i) { if (vocab[i]) ++vocab_size; } int offset = 0; std::vector<int> byte_map(256, 0), reverse_byte_map(vocab_size, 0); for (int i = 0; i < 256; ++i) { byte_map[i] = offset; if (vocab[i]) ++offset; } offset = 0; for (int i = 0; i < 256; ++i) { if (vocab[i]) { reverse_byte_map[offset] = i; ++offset; } } Lstm lstm(vocab_size, vocab_size, 90, 3, 10, 0.05, 2); std::valarray<float>& probs = lstm.Perceive(byte_map[data_in.get()]); double entropy = log2(1.0/256); unsigned long long percent = 1 + (input_bytes / 100); for (unsigned int pos = 1; pos < input_bytes; ++pos) { int c = byte_map[data_in.get()]; entropy += log2(probs[(unsigned char)c]); probs = lstm.Perceive(c); if (pos % percent == 0) { printf("\rtraining: %lld%%", pos / percent); fflush(stdout); } } entropy = -entropy / input_bytes; printf("\rcross entropy: %.4f\n", entropy); data_in.close(); percent = 1 + (output_size / 100); for (int i = 0; i < output_size; ++i) { float r = Rand(); int c = 0; for (; c < vocab_size; ++c) { r -= probs[c]; if (r < 0) break; } probs = lstm.Predict(c); data_out.put(reverse_byte_map[c]); if (i % percent == 0) { printf("\rgeneration: %lld%%", i / percent); fflush(stdout); } } printf("\rgeneration: 100%%\n"); data_out.close(); return true; } bool RunDecompression(bool enable_preprocess, const std::string& input_path, const std::string& temp_path, const std::string& output_path, FILE* dictionary, unsigned long long* input_bytes, unsigned long long* output_bytes) { std::ifstream data_in(input_path, std::ios::in | std::ios::binary); if (!data_in.is_open()) return false; data_in.seekg(0, std::ios::end); *input_bytes = data_in.tellg(); data_in.seekg(0, std::ios::beg); std::vector<bool> vocab(256, false); ReadHeader(&data_in, output_bytes, &vocab); if (*output_bytes == 0) { // undo store if (!enable_preprocess) return false; data_in.close(); FILE* in = fopen(input_path.c_str(), "rb"); if (!in) return false; FILE* data_out = fopen(output_path.c_str(), "wb"); if (!data_out) return false; fseek(in, 5L, SEEK_SET); preprocessor::Decode(in, data_out, dictionary); fseek(data_out, 0L, SEEK_END); *output_bytes = ftell(data_out); fclose(in); fclose(data_out); return true; } std::ofstream temp_out(temp_path, std::ios::out | std::ios::binary); if (!temp_out.is_open()) return false; Decompress(*output_bytes, &data_in, &temp_out, vocab); data_in.close(); temp_out.close(); FILE* temp_in = fopen(temp_path.c_str(), "rb"); if (!temp_in) return false; FILE* data_out = fopen(output_path.c_str(), "wb"); if (!data_out) return false; preprocessor::Decode(temp_in, data_out, dictionary); fseek(data_out, 0L, SEEK_END); *output_bytes = ftell(data_out); fclose(temp_in); fclose(data_out); remove(temp_path.c_str()); return true; } int main(int argc, char* argv[]) { if (argc < 4 || argc > 5 || argv[1][0] != '-' || (argv[1][1] != 'c' && argv[1][1] != 'd' && argv[1][1] != 's' && argv[1][1] != 'g')) { return Help(); } clock_t start = clock(); bool enable_preprocess = false; std::string input_path = argv[2]; std::string output_path = argv[3]; if (argv[1][1] == 'g') { if (argc != 5) return Help(); int output_size = std::stoi(argv[4]); if (!RunGeneration(input_path, output_path, output_size)) { return Help(); } return 0; } FILE* dictionary = NULL; if (argc == 5) { enable_preprocess = true; dictionary = fopen(argv[2], "rb"); if (!dictionary) return Help(); input_path = argv[3]; output_path = argv[4]; } std::string temp_path = output_path + ".lstm.temp"; unsigned long long input_bytes = 0, output_bytes = 0; if (argv[1][1] == 's') { if (!enable_preprocess) return Help(); if (!Store(input_path, temp_path, output_path, dictionary, &input_bytes, &output_bytes)) { return Help(); } } else if (argv[1][1] == 'c') { if (!RunCompression(enable_preprocess, input_path, temp_path, output_path, dictionary, &input_bytes, &output_bytes)) { return Help(); } } else { if (!RunDecompression(enable_preprocess, input_path, temp_path, output_path, dictionary, &input_bytes, &output_bytes)) { return Help(); } } printf("\r%lld bytes -> %lld bytes in %1.2f s.\n", input_bytes, output_bytes, ((double)clock() - start) / CLOCKS_PER_SEC); if (argv[1][1] == 'c') { double cross_entropy = output_bytes; cross_entropy /= input_bytes; cross_entropy *= 8; printf("cross entropy: %.3f\n", cross_entropy); } return 0; }
10,924
C++
.cpp
333
28.843844
81
0.616121
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,620
predictor.cpp
byronknoll_lstm-compress/src/predictor.cpp
#include "predictor.h" #include "lstm/byte-model.h" #include "lstm/lstm.h" Predictor::Predictor(const std::vector<bool>& vocab) : vocab_(vocab) { srand(0xDEADBEEF); unsigned int vocab_size = 0; for (unsigned int i = 0; i < vocab_.size(); ++i) { if (vocab_[i]) ++vocab_size; } lstm_.reset(new ByteModel(vocab_, new Lstm(0, vocab_size, 90, 3, 10, 0.05, 2))); } float Predictor::Predict() { return lstm_->Predict(); } void Predictor::Perceive(int bit) { lstm_->Perceive(bit); }
502
C++
.cpp
18
25.388889
70
0.659044
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,621
lstm-layer.cpp
byronknoll_lstm-compress/src/lstm/lstm-layer.cpp
#include "lstm-layer.h" #include "sigmoid.h" #include <math.h> #include <algorithm> #include <numeric> LstmLayer::LstmLayer(unsigned int input_size, unsigned int auxiliary_input_size, unsigned int output_size, unsigned int num_cells, int horizon, float learning_rate, float gradient_clip) : state_(num_cells), output_gate_error_(num_cells), state_error_(num_cells), input_node_error_(num_cells), input_gate_error_(num_cells), forget_gate_error_(num_cells), stored_error_(num_cells), tanh_state_(std::valarray<float>(num_cells), horizon), output_gate_state_(std::valarray<float>(num_cells), horizon), input_node_state_(std::valarray<float>(num_cells), horizon), input_gate_state_(std::valarray<float>(num_cells), horizon), forget_gate_state_(std::valarray<float>(num_cells), horizon), last_state_(std::valarray<float>(num_cells), horizon), forget_gate_(std::valarray<float>(input_size), num_cells), input_node_(std::valarray<float>(input_size), num_cells), input_gate_(std::valarray<float>(input_size), num_cells), output_gate_(std::valarray<float>(input_size), num_cells), forget_gate_update_(std::valarray<float>(input_size), num_cells), input_node_update_(std::valarray<float>(input_size), num_cells), input_gate_update_(std::valarray<float>(input_size), num_cells), output_gate_update_(std::valarray<float>(input_size), num_cells), learning_rate_(learning_rate), gradient_clip_(gradient_clip), num_cells_(num_cells), epoch_(0), horizon_(horizon), input_size_(auxiliary_input_size), output_size_(output_size) { float low = -0.2; float range = 0.4; for (unsigned int i = 0; i < num_cells_; ++i) { for (unsigned int j = 0; j < forget_gate_[i].size(); ++j) { forget_gate_[i][j] = low + Rand() * range; input_node_[i][j] = low + Rand() * range; input_gate_[i][j] = low + Rand() * range; output_gate_[i][j] = low + Rand() * range; } forget_gate_[i][forget_gate_[i].size() - 1] = 1; } } void LstmLayer::ForwardPass(const std::valarray<float>& input, int input_symbol, std::valarray<float>* hidden, int hidden_start) { last_state_[epoch_] = state_; for (unsigned int i = 0; i < num_cells_; ++i) { forget_gate_state_[epoch_][i] = Sigmoid::Logistic(std::inner_product( &input[0], &input[input.size()], &forget_gate_[i][output_size_], forget_gate_[i][input_symbol])); input_node_state_[epoch_][i] = tanh(std::inner_product(&input[0], &input[input.size()], &input_node_[i][output_size_], input_node_[i][input_symbol])); input_gate_state_[epoch_][i] = Sigmoid::Logistic(std::inner_product( &input[0], &input[input.size()], &input_gate_[i][output_size_], input_gate_[i][input_symbol])); output_gate_state_[epoch_][i] = Sigmoid::Logistic(std::inner_product( &input[0], &input[input.size()], &output_gate_[i][output_size_], output_gate_[i][input_symbol])); } state_ *= forget_gate_state_[epoch_]; state_ += input_node_state_[epoch_] * input_gate_state_[epoch_]; tanh_state_[epoch_] = tanh(state_); std::slice slice = std::slice(hidden_start, num_cells_, 1); (*hidden)[slice] = output_gate_state_[epoch_] * tanh_state_[epoch_]; ++epoch_; if (epoch_ == horizon_) epoch_ = 0; } void LstmLayer::ClipGradients(std::valarray<float>* arr) { for (unsigned int i = 0; i < arr->size(); ++i) { if ((*arr)[i] < -gradient_clip_) (*arr)[i] = -gradient_clip_; else if ((*arr)[i] > gradient_clip_) (*arr)[i] = gradient_clip_; } } void LstmLayer::BackwardPass(const std::valarray<float>&input, int epoch, int layer, int input_symbol, std::valarray<float>* hidden_error) { if (epoch == (int)horizon_ - 1) { stored_error_ = *hidden_error; state_error_ = 0; for (unsigned int i = 0; i < num_cells_; ++i) { forget_gate_update_[i] = 0; input_node_update_[i] = 0; input_gate_update_[i] = 0; output_gate_update_[i] = 0; } } else { stored_error_ += *hidden_error; } output_gate_error_ = tanh_state_[epoch] * stored_error_ * output_gate_state_[epoch] * (1.0f - output_gate_state_[epoch]); state_error_ += stored_error_ * output_gate_state_[epoch] * (1.0f - (tanh_state_[epoch] * tanh_state_[epoch])); input_node_error_ = state_error_ * input_gate_state_[epoch] * (1.0f - (input_node_state_[epoch] * input_node_state_[epoch])); input_gate_error_ = state_error_ * input_node_state_[epoch] * input_gate_state_[epoch] * (1.0f - input_gate_state_[epoch]); forget_gate_error_ = state_error_ * last_state_[epoch] * forget_gate_state_[epoch] * (1.0f - forget_gate_state_[epoch]); *hidden_error = 0; if (layer > 0) { int offset = output_size_ + num_cells_ + input_size_; for (unsigned int i = 0; i < num_cells_; ++i) { for (unsigned int j = offset; j < offset + num_cells_; ++j) { (*hidden_error)[j-offset] += input_node_[i][j] * input_node_error_[i]; (*hidden_error)[j-offset] += input_gate_[i][j] * input_gate_error_[i]; (*hidden_error)[j-offset] += forget_gate_[i][j] * forget_gate_error_[i]; (*hidden_error)[j-offset] += output_gate_[i][j] * output_gate_error_[i]; } } } if (epoch > 0) { state_error_ *= forget_gate_state_[epoch]; stored_error_ = 0; int offset = output_size_ + input_size_; for (unsigned int i = 0; i < num_cells_; ++i) { for (unsigned int j = offset; j < offset + num_cells_; ++j) { stored_error_[j-offset] += input_node_[i][j] * input_node_error_[i]; stored_error_[j-offset] += input_gate_[i][j] * input_gate_error_[i]; stored_error_[j-offset] += forget_gate_[i][j] * forget_gate_error_[i]; stored_error_[j-offset] += output_gate_[i][j] * output_gate_error_[i]; } } } ClipGradients(&state_error_); ClipGradients(&stored_error_); ClipGradients(hidden_error); std::slice slice = std::slice(output_size_, input.size(), 1); for (unsigned int i = 0; i < num_cells_; ++i) { forget_gate_update_[i][slice] += (learning_rate_ * forget_gate_error_[i]) * input; input_node_update_[i][slice] += (learning_rate_ * input_node_error_[i]) * input; input_gate_update_[i][slice] += (learning_rate_ * input_gate_error_[i]) * input; output_gate_update_[i][slice] += (learning_rate_ * output_gate_error_[i]) * input; forget_gate_update_[i][input_symbol] += learning_rate_ * forget_gate_error_[i]; input_node_update_[i][input_symbol] += learning_rate_ * input_node_error_[i]; input_gate_update_[i][input_symbol] += learning_rate_ * input_gate_error_[i]; output_gate_update_[i][input_symbol] += learning_rate_ * output_gate_error_[i]; } if (epoch == 0) { for (unsigned int i = 0; i < num_cells_; ++i) { forget_gate_[i] += forget_gate_update_[i]; input_node_[i] += input_node_update_[i]; input_gate_[i] += input_gate_update_[i]; output_gate_[i] += output_gate_update_[i]; } } }
7,064
C++
.cpp
151
41.576159
80
0.619386
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,622
byte-model.cpp
byronknoll_lstm-compress/src/lstm/byte-model.cpp
#include "byte-model.h" #include "lstm.h" #include <numeric> ByteModel::ByteModel(const std::vector<bool>& vocab, Lstm* lstm) : top_(255), mid_(0), bot_(0), byte_map_(0, 256), probs_(1.0 / 256, 256), bit_context_(1), lstm_(lstm), vocab_(vocab) { int offset = 0; for (int i = 0; i < 256; ++i) { byte_map_[i] = offset; if (vocab_[i]) ++offset; } } float ByteModel::Predict() { mid_ = bot_ + ((top_ - bot_) / 2); float num = std::accumulate(&probs_[mid_ + 1], &probs_[top_ + 1], 0.0f); float denom = std::accumulate(&probs_[bot_], &probs_[mid_ + 1], num); if (denom == 0) return 0.5; return num / denom; } void ByteModel::Perceive(int bit) { if (bit) { bot_ = mid_ + 1; } else { top_ = mid_; } bit_context_ += bit_context_ + bit; if (bit_context_ >= 256) { bit_context_ -= 256; const auto& output = lstm_->Perceive(byte_map_[bit_context_]); int offset = 0; for (int i = 0; i < 256; ++i) { if (vocab_[i]) { probs_[i] = output[offset]; ++offset; } else { probs_[i] = 0; } } bit_context_ = 1; top_ = 255; bot_ = 0; } }
1,144
C++
.cpp
43
22.55814
77
0.538321
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,623
lstm.cpp
byronknoll_lstm-compress/src/lstm/lstm.cpp
#include "lstm.h" #include <numeric> #include <stdlib.h> Lstm::Lstm(unsigned int input_size, unsigned int output_size, unsigned int num_cells, unsigned int num_layers, int horizon, float learning_rate, float gradient_clip) : input_history_(horizon), hidden_(num_cells * num_layers + 1), hidden_error_(num_cells), layer_input_(std::valarray<std::valarray<float>>(std::valarray<float> (input_size + 1 + num_cells * 2), num_layers), horizon), output_layer_(std::valarray<std::valarray<float>>(std::valarray<float> (num_cells * num_layers + 1), output_size), horizon), output_(std::valarray<float>(1.0 / output_size, output_size), horizon), learning_rate_(learning_rate), num_cells_(num_cells), epoch_(0), horizon_(horizon), input_size_(input_size), output_size_(output_size) { srand(69761); hidden_[hidden_.size() - 1] = 1; for (int epoch = 0; epoch < horizon; ++epoch) { layer_input_[epoch][0].resize(1 + num_cells + input_size); for (unsigned int i = 0; i < num_layers; ++i) { layer_input_[epoch][i][layer_input_[epoch][i].size() - 1] = 1; } } for (unsigned int i = 0; i < num_layers; ++i) { layers_.push_back(std::unique_ptr<LstmLayer>(new LstmLayer( layer_input_[0][i].size() + output_size, input_size_, output_size_, num_cells, horizon, learning_rate, gradient_clip))); } } void Lstm::SetInput(int index, float val) { for (unsigned int i = 0; i < layers_.size(); ++i) { layer_input_[epoch_][i][index] = val; } } std::valarray<float>& Lstm::Perceive(unsigned int input) { int last_epoch = epoch_ - 1; if (last_epoch == -1) last_epoch = horizon_ - 1; int old_input = input_history_[last_epoch]; input_history_[last_epoch] = input; if (epoch_ == 0) { for (int epoch = horizon_ - 1; epoch >= 0; --epoch) { for (int layer = layers_.size() - 1; layer >= 0; --layer) { int offset = layer * num_cells_; for (unsigned int i = 0; i < output_size_; ++i) { float error = 0; if (i == input_history_[epoch]) error = (1 - output_[epoch][i]); else error = -output_[epoch][i]; for (unsigned int j = 0; j < hidden_error_.size(); ++j) { hidden_error_[j] += output_layer_[epoch][i][j + offset] * error; } } int prev_epoch = epoch - 1; if (prev_epoch == -1) prev_epoch = horizon_ - 1; int input_symbol = input_history_[prev_epoch]; if (epoch == 0) input_symbol = old_input; layers_[layer]->BackwardPass(layer_input_[epoch][layer], epoch, layer, input_symbol, &hidden_error_); } } } output_layer_[epoch_] = output_layer_[last_epoch]; for (unsigned int i = 0; i < output_size_; ++i) { float error = 0; if (i == input) error = (1 - output_[last_epoch][i]); else error = -output_[last_epoch][i]; output_layer_[epoch_][i] += learning_rate_ * error * hidden_; } return Predict(input); } std::valarray<float>& Lstm::Predict(unsigned int input) { for (unsigned int i = 0; i < layers_.size(); ++i) { auto start = begin(hidden_) + i * num_cells_; std::copy(start, start + num_cells_, begin(layer_input_[epoch_][i]) + input_size_); layers_[i]->ForwardPass(layer_input_[epoch_][i], input, &hidden_, i * num_cells_); if (i < layers_.size() - 1) { auto start2 = begin(layer_input_[epoch_][i + 1]) + num_cells_ + input_size_; std::copy(start, start + num_cells_, start2); } } float max_out = 0; for (unsigned int i = 0; i < output_size_; ++i) { float sum = 0; for (unsigned int j = 0; j < hidden_.size(); ++j) { sum += hidden_[j] * output_layer_[epoch_][i][j]; } output_[epoch_][i] = sum; max_out = std::max(sum, max_out); } for (unsigned int i = 0; i < output_size_; ++i) { output_[epoch_][i] = exp(output_[epoch_][i] - max_out); } output_[epoch_] /= output_[epoch_].sum(); int epoch = epoch_; ++epoch_; if (epoch_ == horizon_) epoch_ = 0; return output_[epoch]; }
4,042
C++
.cpp
99
35.686869
78
0.593091
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,624
sigmoid.cpp
byronknoll_lstm-compress/src/lstm/sigmoid.cpp
#include "sigmoid.h" #include <math.h> Sigmoid::Sigmoid(int logit_size) : logit_size_(logit_size), logit_table_(logit_size, 0) { for (int i = 0; i < logit_size_; ++i) { logit_table_[i] = SlowLogit((i + 0.5) / logit_size_); } } float Sigmoid::Logit(float p) const { return logit_table_[p * logit_size_]; } float Sigmoid::Logistic(float p) { return 1 / (1 + exp(-p)); } float Sigmoid::SlowLogit(float p) { return log(p / (1 - p)); }
454
C++
.cpp
17
24.352941
59
0.631944
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,625
preprocessor.cpp
byronknoll_lstm-compress/src/preprocess/preprocessor.cpp
// This preprocessor is adapted from paq8l, paq8hp12any and paq8px. #include <vector> #include <cstdlib> #include <string.h> #include "preprocessor.h" #include "dictionary.h" namespace preprocessor { typedef unsigned char U8; typedef unsigned short U16; typedef unsigned int U32; inline int min(int a, int b) {return a<b?a:b;} inline int max(int a, int b) {return a<b?b:a;} bool IsAscii(int byte) { if (byte >= 9 && byte <= 13) return true; if (byte >= 32 && byte <= 126) return true; return false; } #define bswap(x) \ + ((((x) & 0xff000000) >> 24) | \ + (((x) & 0x00ff0000) >> 8) | \ + (((x) & 0x0000ff00) << 8) | \ + (((x) & 0x000000ff) << 24)) #define IMG_DET_NOHDR(type,start_pos,width,height) return detd=(width)*(height),info=(width),fseek(in, start+(start_pos), SEEK_SET),(type) #define IMG_DET(type,start_pos,header_len,width,height) return dett=(type),deth=(header_len),detd=(width)*(height),info=(width),fseek(in, start+(start_pos), SEEK_SET),HDR int info; Filetype detect(FILE* in, int n, Filetype type) { U32 buf2=0, buf1=0, buf0=0; long start=ftell(in); // For EXE detection std::vector<int> abspos(256, 0), relpos(256, 0); int e8e9count=0; int e8e9pos=0; int e8e9last=0; // For JPEG detection int soi=0, sof=0, sos=0, app=0; // For TEXT detection int ascii_start = -1; int ascii_run = 0; int space_count = 0; // For BMP detection uint64_t bmp=0; int imgbpp=0,bmpx=0,bmpy=0,bmpof=0; static int deth=0,detd=0; // detected header/data size in bytes static Filetype dett; // detected block type if (deth) return fseek(in, start+deth, SEEK_SET),deth=0,dett; else if (detd) return fseek(in, start+detd, SEEK_SET),detd=0,DEFAULT; // For TGA detection uint64_t tga=0; int tgaid=0, tgaw=0, tgah=0; // For PBM, PGM, PPM, PAM detection uint64_t pgm=0; int pgmcomment=0,pgmw=0,pgmh=0,pgm_ptr=0,pgmc=0,pgmn=0,pamatr=0,pamd=0; char pgm_buf[32]; for (int i=0; i<n; ++i) { int c=getc(in); if (c==EOF) return (Filetype)(-1); buf2=buf2<<8|buf1>>24; buf1=buf1<<8|buf0>>24; buf0=buf0<<8|c; if (!soi && i>=3 && (buf0&0xffffff00)==0xffd8ff00 && ((buf0&0xFE)==0xC0 || (U8)buf0==0xC4 || ((U8)buf0>=0xDB && (U8)buf0<=0xFE) )) soi=i, app=i+2, sos=sof=0; if (soi) { if (app==i && (buf0>>24)==0xff && ((buf0>>16)&0xff)>0xc1 && ((buf0>>16)&0xff)<0xff) app=i+(buf0&0xffff)+2; if (app<i && (buf1&0xff)==0xff && (buf0&0xfe0000ff)==0xc0000008) sof=i; if (sof && sof>soi && i-sof<0x1000 && (buf0&0xffff)==0xffda) { sos=i; if (type!=JPEG) return fseek(in, start+soi-3, SEEK_SET), JPEG; } if (i-soi>0x40000 && !sos) soi=0; } if (type==JPEG && sos && i>sos && (buf0&0xff00)==0xff00 && (buf0&0xff)!=0 && (buf0&0xf8)!=0xd0) return DEFAULT; if (((buf1&0xfe)==0xe8 || (buf1&0xfff0)==0x0f80) && ((buf0+1)&0xfe)==0) { int r=buf0>>24; int a=((buf0>>24)+i)&0xff; int rdist=i-relpos[r]; int adist=i-abspos[a]; if (adist<rdist && adist<0x800 && abspos[a]>5) { e8e9last=i; ++e8e9count; if (e8e9pos==0 || e8e9pos>abspos[a]) e8e9pos=abspos[a]; } else e8e9count=0; if (type!=EXE && e8e9count>=4 && e8e9pos>5) return fseek(in, start+e8e9pos-5, SEEK_SET), EXE; abspos[a]=i; relpos[r]=i; } if (type==EXE && i-e8e9last>0x4000) return fseek(in, start+e8e9last, SEEK_SET), DEFAULT; // Detect TEXT if (type == DEFAULT) { if (IsAscii(c)) { if (ascii_start == -1) { ascii_start = i; ascii_run = 0; space_count = 0; } if (c == ' ') ++space_count; ++ascii_run; if (ascii_run > 500) { if (space_count < 5) { ascii_start = -1; } else { return fseek(in, start + ascii_start, SEEK_SET), TEXT; } } } else { ascii_start = -1; } } else if (type == TEXT) { if (IsAscii(c)) { ascii_run -= 2; if (ascii_run < 0) ascii_run = 0; } else { ascii_run += 3; if (ascii_run > 300) { return fseek(in, ftell(in) - 100, SEEK_SET), DEFAULT; } } } // Detect .bmp image if ((buf0&0xffff)==16973) imgbpp=bmpx=bmpy=bmpof=0,bmp=i; if (bmp) { const int p=int(i-bmp); if (p==12) bmpof=bswap(buf0); else if (p==16 && buf0!=0x28000000) bmp=0; else if (p==20) bmpx=bswap(buf0),bmp=((bmpx==0||bmpx>0x40000)?0:bmp); else if (p==24) bmpy=abs((int)bswap(buf0)),bmp=((bmpy==0||bmpy>0x20000)?0:bmp); else if (p==27) imgbpp=c,bmp=((imgbpp!=1 && imgbpp!=4 && imgbpp!=8 && imgbpp!=24)?0:bmp); else if (p==31) { if (imgbpp!=0 && buf0==0 && bmpx>1) { if (imgbpp==24) { int width = ((bmpx*3)+3)&-4; IMG_DET(IMAGE24, (bmp-1), bmpof, width, bmpy); } } bmp=0; } } // detect .tga image if ((buf1&0xFFFFFF)==0x000200 && buf0==0x00000000) tga=i, tgaid=buf1>>24; if (tga){ if ((i-tga)==8){ tgaw = bswap(buf0)&0xffff; tgah = bswap(buf0)>>16; tga*=(!buf1 && tgaw && tgaw<0x4000 && tgah && tgah<0x4000); } else if ((i-tga)==10){ if (tga && (buf0&0xFFDF)==0x1800) IMG_DET(IMAGE24, (tga-7), 18+tgaid, tgaw*3, tgah); } } // Detect .pbm .pgm .ppm .pam image if ((buf0&0xfff0ff)==0x50300a) { pgmn=(buf0&0xf00)>>8; if ((pgmn>=4 && pgmn<=6) || pgmn==7) pgm=i,pgm_ptr=pgmw=pgmh=pgmc=pgmcomment=pamatr=pamd=0; } if (pgm) { if (i-pgm==1 && c==0x23) pgmcomment=1; //pgm comment if (!pgmcomment && pgm_ptr) { int s=0; if (pgmn==7) { if ((buf1&0xdfdf)==0x5749 && (buf0&0xdfdfdfff)==0x44544820) pgm_ptr=0, pamatr=1; // WIDTH if ((buf1&0xdfdfdf)==0x484549 && (buf0&0xdfdfdfff)==0x47485420) pgm_ptr=0, pamatr=2; // HEIGHT if ((buf1&0xdfdfdf)==0x4d4158 && (buf0&0xdfdfdfff)==0x56414c20) pgm_ptr=0, pamatr=3; // MAXVAL if ((buf1&0xdfdf)==0x4445 && (buf0&0xdfdfdfff)==0x50544820) pgm_ptr=0, pamatr=4; // DEPTH if ((buf2&0xdf)==0x54 && (buf1&0xdfdfdfdf)==0x55504c54 && (buf0&0xdfdfdfff)==0x59504520) pgm_ptr=0, pamatr=5; // TUPLTYPE if ((buf1&0xdfdfdf)==0x454e44 && (buf0&0xdfdfdfff)==0x4844520a) pgm_ptr=0, pamatr=6; // ENDHDR if (c==0x0a) { if (pamatr==0) pgm=0; else if (pamatr<5) s=pamatr; if (pamatr!=6) pamatr=0; } } else if (c==0x20 && !pgmw) s=1; else if (c==0x0a && !pgmh) s=2; else if (c==0x0a && !pgmc && pgmn!=4) s=3; if (s) { pgm_buf[pgm_ptr++]=0; int v=atoi(pgm_buf); if (s==1) pgmw=v; else if (s==2) pgmh=v; else if (s==3) pgmc=v; else if (s==4) pamd=v; if (v==0 || (s==3 && v>255)) pgm=0; else pgm_ptr=0; } } if (!pgmcomment) pgm_buf[pgm_ptr++]=c; if (pgm_ptr>=32) pgm=0; if (pgmcomment && c==0x0a) pgmcomment=0; if (pgmw && pgmh && !pgmc && pgmn==4) IMG_DET_NOHDR(IMAGE1,i-pgm+3,(pgmw+7)/8,pgmh); if (pgmw && pgmh && pgmc && (pgmn==5 || (pgmn==7 && pamd==1 && pamatr==6))) IMG_DET_NOHDR(IMAGE8GRAY,i-pgm+3,pgmw,pgmh); if (pgmw && pgmh && pgmc && (pgmn==6 || (pgmn==7 && pamd==3 && pamatr==6))) IMG_DET_NOHDR(IMAGE24,i-pgm+3,pgmw*3,pgmh); if (pgmw && pgmh && pgmc && (pgmn==7 && pamd==4 && pamatr==6)) IMG_DET_NOHDR(IMAGE32,i-pgm+3,pgmw*4,pgmh); } // Detect .tiff image if (buf1==0x49492a00 && n>i+(int)bswap(buf0)) { long savedpos=ftell(in); fseek(in, start+i+bswap(buf0)-7, SEEK_SET); // read directory int dirsize=getc(in); int tifx=0,tify=0,tifz=0,tifzb=0,tifc=0,tifofs=0,tifofval=0,b[12]; if (getc(in)==0) { for (int i=0; i<dirsize; i++) { for (int j=0; j<12; j++) b[j]=getc(in); if (b[11]==EOF) break; int tag=b[0]+(b[1]<<8); int tagfmt=b[2]+(b[3]<<8); int taglen=b[4]+(b[5]<<8)+(b[6]<<16)+(b[7]<<24); int tagval=b[8]+(b[9]<<8)+(b[10]<<16)+(b[11]<<24); if (tagfmt==3||tagfmt==4) { if (tag==256) tifx=tagval; else if (tag==257) tify=tagval; else if (tag==258) tifzb=taglen==1?tagval:8; // bits per component else if (tag==259) tifc=tagval; // 1 = no compression else if (tag==273 && tagfmt==4) tifofs=tagval,tifofval=(taglen<=1); else if (tag==277) tifz=tagval; // components per pixel } } } if (tifx && tify && tifzb && (tifz==1 || tifz==3) && (tifc==1) && (tifofs && tifofs+i<n)) { if (!tifofval) { fseek(in, start+i+tifofs-7, SEEK_SET); for (int j=0; j<4; j++) b[j]=getc(in); tifofs=b[0]+(b[1]<<8)+(b[2]<<16)+(b[3]<<24); } if (tifofs && tifofs<(1<<18) && tifofs+i<n) { if (tifz==1 && tifzb==1) IMG_DET_NOHDR(IMAGE1,(i-7)+tifofs,((tifx-1)>>3)+1,tify); else if (tifz==1 && tifzb==8) IMG_DET_NOHDR(IMAGE8, (i-7)+tifofs, tifx, tify); else if (tifz==3 && tifzb==8) IMG_DET_NOHDR(IMAGE24, (i-7)+tifofs, tifx*3, tify); } } fseek(in, savedpos, SEEK_SET); } } return type; } void encode_default(FILE* in, FILE* out, int len) { while (len--) putc(getc(in), out); } int decode_default(FILE* in) { return getc(in); } #define RGB565_MIN_RUN 63 void encode_bmp(FILE* in, FILE* out, int len, int width) { fprintf(out, "%c%c%c%c", width>>24, width>>16, width>>8, width); int r,g,b, total=0; bool isPossibleRGB565 = true; for (int i=0; i<len/width; i++) { for (int j=0; j<width/3; j++) { b=getc(in), g=getc(in), r=getc(in); if (isPossibleRGB565) { int pTotal=total; total=std::min<int>(total+1, 0xFFFF)*((b&7)==((b&8)-((b>>3)&1)) && (g&3)==((g&4)-((g>>2)&1)) && (r&7)==((r&8)-((r>>3)&1))); if (total>RGB565_MIN_RUN || pTotal>=RGB565_MIN_RUN) { b^=(b&8)-((b>>3)&1); g^=(g&4)-((g>>2)&1); r^=(r&8)-((r>>3)&1); } isPossibleRGB565=total>0; } putc(g, out); putc(g-r, out); putc(g-b, out); } for (int j=0; j<width%3; j++) putc(getc(in), out); } } int decode_bmp(FILE *in, int &reset) { static int width = 0, total = 0; static bool isPossibleRGB565 = true; if (width == 0 || reset) { width=getc(in)<<24; width|=getc(in)<<16; width|=getc(in)<<8; width|=getc(in); reset=total=0; isPossibleRGB565 = true; } static int r,g,b; static int state1 = 0, state2 = 0; if (state1 < width/3) { if (state2 == 0) { g=getc(in), r=g-getc(in), b=g-getc(in); ++state2; if (isPossibleRGB565){ if (total>=RGB565_MIN_RUN) { b^=(b&8)-((b>>3)&1); g^=(g&4)-((g>>2)&1); r^=(r&8)-((r>>3)&1); } total=std::min<int>(total+1, 0xFFFF)*((b&7)==((b&8)-((b>>3)&1)) && (g&3)==((g&4)-((g>>2)&1)) && (r&7)==((r&8)-((r>>3)&1))); isPossibleRGB565=total>0; } return b&255; } else if (state2 == 1) { ++state2; return g; } else if (state2 == 2) { ++state1; if (width%3 == 0) state1 = 0; state2 = 0; return r&255; } } else { ++state2; if (state2 == width%3) { state1 = 0; state2 = 0; } return getc(in); } return -1; } void encode_exe(FILE* in, FILE* out, int len, int begin) { const int BLOCK=0x10000; std::vector<U8> blk(BLOCK); fprintf(out, "%c%c%c%c", len>>24, len>>16, len>>8, len); fprintf(out, "%c%c%c%c", begin>>24, begin>>16, begin>>8, begin); for (int offset=0; offset<len; offset+=BLOCK) { int size=min(len-offset, BLOCK); int bytesRead=fread(&blk[0], 1, size, in); if (bytesRead!=size) abort(); for (int i=bytesRead-1; i>=5; --i) { if ((blk[i-4]==0xe8 || blk[i-4]==0xe9 || (blk[i-5]==0x0f && (blk[i-4]&0xf0)==0x80)) && (blk[i]==0||blk[i]==0xff)) { int a=(blk[i-3]|blk[i-2]<<8|blk[i-1]<<16|blk[i]<<24)+offset+begin+i+1; a<<=7; a>>=7; blk[i]=a>>24; blk[i-1]=a^176; blk[i-2]=(a>>8)^176; blk[i-3]=(a>>16)^176; } } fwrite(&blk[0], 1, bytesRead, out); } } int decode_exe(FILE* in) { const int BLOCK=0x10000; static int offset=0, q=0; static int size=0; static int begin=0; static U8 c[6]; while (offset==size && q==0) { offset=0; size=getc(in)<<24; size|=getc(in)<<16; size|=getc(in)<<8; size|=getc(in); begin=getc(in)<<24; begin|=getc(in)<<16; begin|=getc(in)<<8; begin|=getc(in); } while (offset<size && q<6) { memmove(c+1, c, 5); c[0]=getc(in); ++q; ++offset; } if (q==6 && (c[0]==0x00 || c[0]==0xFF) && (c[4]==0xE8 || c[4]==0xE9 || (c[5]==0x0F && (c[4]&0xF0)==0x80)) && (((offset-1)^(offset-6))&-BLOCK)==0 && offset<=size) { int a=((c[1]^176)|(c[2]^176)<<8|(c[3]^176)<<16|c[0]<<24)-offset-begin; a<<=7; a>>=7; c[3]=a; c[2]=a>>8; c[1]=a>>16; c[0]=a>>24; } return c[--q]; } void encode_text(FILE* in, FILE* out, int len, std::string temp_path, FILE* dictionary) { if (dictionary == NULL) { putc(0, out); for (int i = 0; i < len; ++i) { putc(getc(in), out); } return; } std::string path = temp_path + "2"; FILE* temp_output = fopen(path.c_str(), "wb+"); if (!temp_output) abort(); int orig_pos = ftell(in); Dictionary dict(dictionary, true, false); dict.Encode(in, len, temp_output); int size = ftell(temp_output); if (size > len - 50) { putc(0, out); fseek(in, orig_pos, SEEK_SET); for (int i = 0; i < len; ++i) { putc(getc(in), out); } } else { putc(1, out); rewind(temp_output); for (int i = 0; i < size; ++i) { putc(getc(temp_output), out); } } fclose(temp_output); remove(path.c_str()); } Dictionary* dict = NULL; bool wrt_enabled = true; void reset_text_decoder(FILE* in, FILE* dictionary) { int c = getc(in); if (c) { wrt_enabled = true; if (dict == NULL) dict = new Dictionary(dictionary, false, true); } else { wrt_enabled = false; } } int decode_text(FILE* in) { if (!wrt_enabled) return getc(in); return dict->Decode(in); } void Encode(FILE* in, FILE* out, int n, std::string temp_path, FILE* dictionary) { Filetype type=DEFAULT; long begin=ftell(in); long start = begin; int remainder = n; int text_bytes = 0; while (remainder > 0) { Filetype nextType=detect(in, remainder, type); long end=ftell(in); int len=int(end-begin); if (type == TEXT) text_bytes += len; remainder-=len; type=nextType; begin=end; } fseek(in, start, SEEK_SET); type = DEFAULT; begin = start; double text_fraction = text_bytes; text_fraction /= n; if (text_fraction > 0.95) { fprintf(out, "%c%c%c%c%c", TEXT, n>>24, n>>16, n>>8, n); encode_text(in, out, n, temp_path, dictionary); return; } while (n>0) { Filetype nextType=detect(in, n, type); long end=ftell(in); fseek(in, begin, SEEK_SET); int len=int(end-begin); if (len>0) { fprintf(out, "%c%c%c%c%c", type, len>>24, len>>16, len>>8, len); switch(type) { case IMAGE24: encode_bmp(in, out, len, info); break; case EXE: encode_exe(in, out, len, begin); break; case TEXT: encode_text(in, out, len, temp_path, dictionary); break; default: { if (HasInfo(type)) fprintf(out, "%c%c%c%c", info>>24, info>>16, info>>8, info); // write info encode_default(in, out, len); break; } } } n-=len; type=nextType; begin=end; } } void NoPreprocess(FILE* in, FILE* out, int n) { fprintf(out, "%c%c%c%c%c", DEFAULT, n>>24, n>>16, n>>8, n); encode_default(in, out, n); } int DecodeByte(FILE* in, FILE* dictionary) { static Filetype type=DEFAULT; static int len=0, reset=0; while (len==0) { int c = getc(in); if (c == EOF) return -1; reset=1; type=(Filetype)c; len=getc(in)<<24; len|=getc(in)<<16; len|=getc(in)<<8; len|=getc(in); if (len<0) len=1; if (type == TEXT) reset_text_decoder(in, dictionary); } --len; switch (type) { case IMAGE24: return decode_bmp(in, reset); case EXE: return decode_exe(in); case TEXT: return decode_text(in); default: { if (reset && HasInfo(type)){ for (int i=info=0;i<4;i++) info=(info<<8)|getc(in); //read info reset=0; } return decode_default(in); } } } void Decode(FILE* in, FILE* out, FILE* dictionary) { while (true) { int result = DecodeByte(in, dictionary); if (result == -1) { if (dict != NULL) delete dict; return; } putc(result, out); } } }
16,846
C++
.cpp
511
27.125245
170
0.544103
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,626
predictor.h
byronknoll_lstm-compress/src/predictor.h
#ifndef PREDICTOR_H #define PREDICTOR_H #include "lstm/byte-model.h" class Predictor { public: Predictor(const std::vector<bool>& vocab); float Predict(); void Perceive(int bit); private: std::unique_ptr<ByteModel> lstm_; std::vector<bool> vocab_; }; #endif
274
C++
.h
13
18.846154
44
0.7393
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,627
lstm.h
byronknoll_lstm-compress/src/lstm/lstm.h
#ifndef LSTM_COMPRESS_H #define LSTM_COMPRESS_H #include <valarray> #include <vector> #include <memory> #include "lstm-layer.h" class Lstm { public: Lstm(unsigned int input_size, unsigned int output_size, unsigned int num_cells, unsigned int num_layers, int horizon, float learning_rate, float gradient_clip); std::valarray<float>& Perceive(unsigned int input); std::valarray<float>& Predict(unsigned int input); void SetInput(int index, float val); private: std::vector<std::unique_ptr<LstmLayer>> layers_; std::vector<unsigned int> input_history_; std::valarray<float> hidden_, hidden_error_; std::valarray<std::valarray<std::valarray<float>>> layer_input_, output_layer_; std::valarray<std::valarray<float>> output_; float learning_rate_; unsigned int num_cells_, epoch_, horizon_, input_size_, output_size_; }; #endif
870
C++
.h
25
31.88
75
0.736591
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,628
byte-model.h
byronknoll_lstm-compress/src/lstm/byte-model.h
#ifndef BYTE_MODEL_H #define BYTE_MODEL_H #include "lstm.h" #include <valarray> #include <memory> class ByteModel { public: ByteModel(const std::vector<bool>& vocab, Lstm* lstm); float Predict(); void Perceive(int bit); protected: int top_, mid_, bot_; std::valarray<int> byte_map_; std::valarray<float> probs_; unsigned int bit_context_; std::unique_ptr<Lstm> lstm_; const std::vector<bool>& vocab_; }; #endif
436
C++
.h
19
20.631579
56
0.713592
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,629
lstm-layer.h
byronknoll_lstm-compress/src/lstm/lstm-layer.h
#ifndef LSTM_LAYER_H #define LSTM_LAYER_H #include <valarray> #include <stdlib.h> #include <math.h> class LstmLayer { public: LstmLayer(unsigned int input_size, unsigned int auxiliary_input_size, unsigned int output_size, unsigned int num_cells, int horizon, float learning_rate, float gradient_clip); void ForwardPass(const std::valarray<float>& input, int input_symbol, std::valarray<float>* hidden, int hidden_start); void BackwardPass(const std::valarray<float>& input, int epoch, int layer, int input_symbol, std::valarray<float>* hidden_error); static inline float Rand() { return static_cast <float> (rand()) / static_cast <float> (RAND_MAX); } private: std::valarray<float> state_, output_gate_error_, state_error_, input_node_error_, input_gate_error_, forget_gate_error_, stored_error_; std::valarray<std::valarray<float>> tanh_state_, output_gate_state_, input_node_state_, input_gate_state_, forget_gate_state_, last_state_, forget_gate_, input_node_, input_gate_, output_gate_, forget_gate_update_, input_node_update_, input_gate_update_, output_gate_update_; float learning_rate_, gradient_clip_; unsigned int num_cells_, epoch_, horizon_, input_size_, output_size_; void ClipGradients(std::valarray<float>* arr); }; #endif
1,317
C++
.h
29
41.689655
80
0.719408
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,630
preprocessor.h
byronknoll_lstm-compress/src/preprocess/preprocessor.h
#ifndef PREPROCESSOR_H #define PREPROCESSOR_H #include <stdio.h> #include <string> #include "../predictor.h" namespace preprocessor { typedef enum {DEFAULT, HDR, JPEG, EXE, TEXT, IMAGE1, IMAGE4, IMAGE8, IMAGE8GRAY, IMAGE24, IMAGE32, AUDIO} Filetype; inline bool HasInfo(Filetype ft) { return ft==TEXT || ft==IMAGE1 || ft==IMAGE4 || ft==IMAGE8 || ft==IMAGE8GRAY || ft==IMAGE24 || ft==IMAGE32; } void Encode(FILE* in, FILE* out, int n, std::string temp_path, FILE* dictionary); void NoPreprocess(FILE* in, FILE* out, int n); void Decode(FILE* in, FILE* out, FILE* dictionary); } #endif
606
C++
.h
16
35.5
80
0.715517
byronknoll/lstm-compress
124
16
0
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,631
HotkeybarGUI.cpp
ipatix_agbplay/src/HotkeybarGUI.cpp
#include "HotkeybarGUI.h" #include "ColorDef.h" #include "Xcept.h" #include <string> #include <cstdint> HotkeybarGUI::HotkeybarGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : CursesWin(height, width, yPos, xPos) { if (height == 0) throw Xcept("Hotkeybar can't be empty"); update(); } HotkeybarGUI::~HotkeybarGUI() { } void HotkeybarGUI::update() { //UIMutex.lock(); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); // draw initial border mvwprintw(winPtr, 0, 0, "%-*s", width, " [q=QUIT] [tab=SWITCH] [a=ADD] [d=DEL] [g=DRAG]"); for (uint32_t i = 1; i < height; i++) { mvwhline(winPtr, (int)i, 0, ' ', width); } wrefresh(winPtr); //UIMutex.unlock(); } void HotkeybarGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); this->height = height; this->width = width; update(); }
987
C++
.cpp
30
28.933333
94
0.647679
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,632
SoundChannel.cpp
ipatix_agbplay/src/SoundChannel.cpp
#include <cmath> #include <cassert> #include <string> #include <algorithm> #include "Constants.h" #include "Debug.h" #include "SoundChannel.h" #include "Util.h" #include "Xcept.h" #include "ConfigManager.h" /* * public SoundChannel */ SoundChannel::SoundChannel(SampleInfo sInfo, ADSR env, const Note& note, bool fixed) : env(env), note(note), sInfo(sInfo), fixed(fixed) { GameConfig& cfg = ConfigManager::Instance().GetCfg(); ResamplerType t = fixed ? cfg.GetResTypeFixed() : cfg.GetResType(); switch (t) { case ResamplerType::NEAREST: this->rs = std::make_unique<NearestResampler>(); break; case ResamplerType::LINEAR: this->rs = std::make_unique<LinearResampler>(); break; case ResamplerType::SINC: this->rs = std::make_unique<SincResampler>(); break; case ResamplerType::BLEP: this->rs = std::make_unique<BlepResampler>(); break; case ResamplerType::BLAMP: this->rs = std::make_unique<BlampResampler>(); break; } // Golden Sun's synth instruments are marked by having a length of zero and a loop of zero if (sInfo.loopEnabled == true && sInfo.loopPos == 0 && sInfo.endPos == 0) { this->isGS = true; } else { this->isGS = false; } // Mario Power Tennis compressed instruments have a 'negative' length // strictly speaking, these are originally only available at 'fixed' frequency, // but we enhance song #17 which otherwise would have garbled/no sound if (sInfo.endPos >= 0x80000000) { this->isMPTcompressed = true; // flip it to it's intended length this->sInfo.endPos = -this->sInfo.endPos; } else { this->isMPTcompressed = false; } this->levelMPTcompressed = 0; this->shiftMPTcompressed = 0x38; } void SoundChannel::Process(sample *buffer, size_t numSamples, const MixingArgs& args) { stepEnvelope(); if (GetState() == EnvState::DEAD) return; if (numSamples == 0) return; float samplesPerBufferInv = 1.0f / float(numSamples); VolumeFade vol = getVol(); vol.fromVolLeft *= args.vol; vol.fromVolRight *= args.vol; vol.toVolLeft *= args.vol; vol.toVolRight *= args.vol; ProcArgs cargs; cargs.lVolStep = (vol.toVolLeft - vol.fromVolLeft) * samplesPerBufferInv; cargs.rVolStep = (vol.toVolRight - vol.fromVolRight) * samplesPerBufferInv; cargs.lVol = vol.fromVolLeft; cargs.rVol = vol.fromVolRight; if (fixed && !isGS) cargs.interStep = float(args.fixedModeRate) * args.sampleRateInv; else cargs.interStep = freq * args.sampleRateInv; if (isGS) { cargs.interStep /= 64.f; // different scale for GS // switch by GS type if (sInfo.samplePtr[1] == 0) { processModPulse(buffer, numSamples, cargs, samplesPerBufferInv); } else if (sInfo.samplePtr[1] == 1) { processSaw(buffer, numSamples, cargs); } else { processTri(buffer, numSamples, cargs); } } else { processNormal(buffer, numSamples, cargs); } updateVolFade(); } uint8_t SoundChannel::GetTrackIdx() const { return note.trackIdx; } void SoundChannel::SetVol(uint16_t vol, int16_t pan) { if (!stop) { int combinedPan = std::clamp(pan + note.rhythmPan, -128, +128); /* original doesn't do the if statement below, but it retains the 0 center * panorama position while allowing the maximum pan valume of 126 (i.e. 63 on tracK) * to be completely right sided. */ if (combinedPan >= 126) combinedPan = 128; this->leftVolCur = static_cast<uint8_t>(std::clamp(note.velocity * vol * (-combinedPan + 128) >> 15, 0, 255)); this->rightVolCur = static_cast<uint8_t>(std::clamp(note.velocity * vol * (combinedPan + 128) >> 15, 0, 255)); } } VolumeFade SoundChannel::getVol() const { float envBase = float(envLevelPrev); float envDelta = (float(envLevelCur) - envBase) / float(INTERFRAMES); float finalFromEnv = envBase + envDelta * float(envInterStep); float finalToEnv = envBase + envDelta * float(envInterStep + 1); VolumeFade retval; retval.fromVolLeft = float(leftVolPrev) * finalFromEnv * (1.0f / 65536.0f); retval.fromVolRight = float(rightVolPrev) * finalFromEnv * (1.0f / 65536.0f); retval.toVolLeft = float(leftVolCur) * finalToEnv * (1.0f / 65536.0f); retval.toVolRight = float(rightVolCur) * finalToEnv * (1.0f / 65536.0f); return retval; } const Note& SoundChannel::GetNote() const { return note; } void SoundChannel::Release() { stop = true; } void SoundChannel::Kill() { envState = EnvState::DEAD; envInterStep = 0; } void SoundChannel::SetPitch(int16_t pitch) { // non original quality improving behavior if (!stop || freq <= 0.0f) freq = sInfo.midCfreq * powf(2.0f, float(note.midiKeyPitch - 60) * (1.0f / 12.0f) + float(pitch) * (1.0f / 768.0f)); } bool SoundChannel::TickNote() { if (!stop) { if (note.length > 0) { note.length--; if (note.length == 0) { stop = true; return false; } } return true; } else { return false; } } EnvState SoundChannel::GetState() const { return envState; } void SoundChannel::stepEnvelope() { if (envState == EnvState::INIT) { if (stop) { envState = EnvState::DEAD; return; } /* it's important to initialize the volume ramp here because in the constructor * the initial volume is not yet known (i.e. 0) */ updateVolFade(); /* Because we are smoothly fading all our amplitude changes, we avoid the case * where the fastest attack value will still cause a 16.6ms ramp instead of being * instant maximum amplitude. */ if (env.att == 0xFF) envLevelPrev = 0xFF; else envLevelPrev = 0x0; envLevelCur = 0; envInterStep = 0; envState = EnvState::ATK; } else { /* On GBA, envelopes update every frame but because we do a multiple of updates per frame * (to increase timing accuracy of Note ONs), only every so many sub-frames we actually update * the envelope state. */ if (++envInterStep < INTERFRAMES) return; envLevelPrev = envLevelCur; envInterStep = 0; } if (envState == EnvState::PSEUDO_ECHO) { assert(note.pseudoEchoLen != 0); if (--note.pseudoEchoLen == 0) { envState = EnvState::DIE; envLevelCur = 0; } } else if (stop) { if (envState == EnvState::DIE) { /* This is really just a transitional state that is supposed to be the last GBA frame * of fadeout. Because we smoothly ramp out envelopes, out envelopes are actually one * frame longer than on hardware- As soon as this state is reached the channel is disabled */ envState = EnvState::DEAD; } else { envLevelCur = static_cast<uint8_t>((envLevelCur * env.rel) >> 8); /* ORIGINAL "BUG": * Even when pseudo echo has no length, the following condition will kick in and may cause * an earlier then intended note release */ if (envLevelCur <= note.pseudoEchoVol) { release: if (note.pseudoEchoVol == 0 || note.pseudoEchoLen == 0) { envState = EnvState::DIE; envLevelCur = 0; } else { envState = EnvState::PSEUDO_ECHO; envLevelCur = note.pseudoEchoVol; } } } } else { if (envState == EnvState::DEC) { envLevelCur = static_cast<uint8_t>((envLevelCur * env.dec) >> 8); if (envLevelCur <= env.sus) { envLevelCur = env.sus; if (envLevelCur == 0) goto release; envState = EnvState::SUS; } } else if (envState == EnvState::ATK) { uint32_t newLevel = envLevelCur + env.att; if (newLevel >= 0xFF) { envLevelCur = 0xFF; envState = EnvState::DEC; } else { envLevelCur = static_cast<uint8_t>(newLevel); } } } } void SoundChannel::updateVolFade() { leftVolPrev = leftVolCur; rightVolPrev = rightVolCur; } /* * private SoundChannel */ void SoundChannel::processNormal(sample *buffer, size_t numSamples, ProcArgs& cargs) { if (numSamples == 0) return; float outBuffer[numSamples]; bool running; if (this->isMPTcompressed) { running = rs->Process(outBuffer, numSamples, cargs.interStep, sampleFetchCallbackMPTDecomp, this); } else { running = rs->Process(outBuffer, numSamples, cargs.interStep, sampleFetchCallback, this); } size_t i = 0; do { float samp = outBuffer[i++]; buffer->left += samp * cargs.lVol; buffer->right += samp * cargs.rVol; buffer++; cargs.lVol += cargs.lVolStep; cargs.rVol += cargs.rVolStep; } while (--numSamples > 0); if (!running) Kill(); } void SoundChannel::processModPulse(sample *buffer, size_t numSamples, ProcArgs& cargs, float nBlocksReciprocal) { #define DUTY_BASE 2 #define DUTY_STEP 3 #define DEPTH 4 #define INIT_DUTY 5 uint32_t fromPos; if (envInterStep == 0) fromPos = pos += uint32_t(sInfo.samplePtr[DUTY_STEP] << 24); else fromPos = pos; uint32_t toPos = fromPos + uint32_t(sInfo.samplePtr[DUTY_STEP] << 24); auto calcThresh = [](uint32_t val, uint8_t base, uint8_t depth, uint8_t init) { uint32_t iThreshold = uint32_t(init << 24) + val; iThreshold = int32_t(iThreshold) < 0 ? ~iThreshold >> 8 : iThreshold >> 8; iThreshold = iThreshold * depth + uint32_t(base << 24); return float(iThreshold) / float(0x100000000); }; float fromThresh = calcThresh(fromPos, (uint8_t)sInfo.samplePtr[DUTY_BASE], (uint8_t)sInfo.samplePtr[DEPTH], (uint8_t)sInfo.samplePtr[INIT_DUTY]); float toThresh = calcThresh(toPos, (uint8_t)sInfo.samplePtr[DUTY_BASE], (uint8_t)sInfo.samplePtr[DEPTH], (uint8_t)sInfo.samplePtr[INIT_DUTY]); float deltaThresh = toThresh - fromThresh; float baseThresh = fromThresh + (deltaThresh * (float(envInterStep) * (1.0f / float(INTERFRAMES)))); float threshStep = deltaThresh * (1.0f / float(INTERFRAMES)) * nBlocksReciprocal; float fThreshold = baseThresh; #undef DUTY_BASE #undef DUTY_STEP #undef DEPTH #undef INIT_DUTY do { float baseSamp = interPos < fThreshold ? 0.5f : -0.5f; // correct dc offset baseSamp += 0.5f - fThreshold; fThreshold += threshStep; buffer->left += baseSamp * cargs.lVol; buffer->right += baseSamp * cargs.rVol; buffer++; cargs.lVol += cargs.lVolStep; cargs.rVol += cargs.rVolStep; interPos += cargs.interStep; // this below might glitch for too high frequencies, which usually shouldn't be used anyway if (interPos >= 1.0f) interPos -= 1.0f; } while (--numSamples > 0); } void SoundChannel::processSaw(sample *buffer, size_t numSamples, ProcArgs& cargs) { const uint32_t fix = 0x70; do { /* * Sorry that the baseSamp calculation looks ugly. * For accuracy it's a 1 to 1 translation of the original assembly code * Could probably be reimplemented easier. Not sure if it's a perfect saw wave */ interPos += cargs.interStep; if (interPos >= 1.0f) interPos -= 1.0f; uint32_t var1 = uint32_t(interPos * 256) - fix; uint32_t var2 = uint32_t(interPos * 65536.0f) << 17; uint32_t var3 = var1 - (var2 >> 27); pos = var3 + uint32_t(int32_t(pos) >> 1); float baseSamp = float((int32_t)pos) / 256.0f; buffer->left += baseSamp * cargs.lVol; buffer->right += baseSamp * cargs.rVol; buffer++; cargs.lVol += cargs.lVolStep; cargs.rVol += cargs.rVolStep; } while (--numSamples > 0); } void SoundChannel::processTri(sample *buffer, size_t numSamples, ProcArgs& cargs) { do { interPos += cargs.interStep; if (interPos >= 1.0f) interPos -= 1.0f; float baseSamp; if (interPos < 0.5f) { baseSamp = (4.0f * interPos) - 1.0f; } else { baseSamp = 3.0f - (4.0f * interPos); } buffer->left += baseSamp * cargs.lVol; buffer->right += baseSamp * cargs.rVol; buffer++; cargs.lVol += cargs.lVolStep; cargs.rVol += cargs.rVolStep; } while (--numSamples > 0); } bool SoundChannel::sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; SoundChannel *_this = static_cast<SoundChannel *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); do { size_t samplesTilLoop = _this->sInfo.endPos - _this->pos; size_t thisFetch = std::min(samplesTilLoop, samplesToFetch); samplesToFetch -= thisFetch; do { fetchBuffer[i++] = float(_this->sInfo.samplePtr[_this->pos++]) / 128.0f; } while (--thisFetch > 0); if (_this->pos >= _this->sInfo.endPos) { if (_this->sInfo.loopEnabled) { _this->pos = _this->sInfo.loopPos; } else { std::fill(fetchBuffer.begin() + i, fetchBuffer.end(), 0.0f); return false; } } } while (samplesToFetch > 0); return true; } bool SoundChannel::sampleFetchCallbackMPTDecomp(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; SoundChannel *_this = static_cast<SoundChannel *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); do { size_t samplesTilLoop = _this->sInfo.endPos - _this->pos; size_t thisFetch = std::min(samplesTilLoop, samplesToFetch); samplesToFetch -= thisFetch; do { // once again, I just took over the assembly implementation // there is probably plenty of room to make this nicer, but it at least works for now bool loNibble = _this->pos & 1; uint32_t samplePos = _this->pos++ >> 1u; int8_t data = _this->sInfo.samplePtr[samplePos]; // 4 bit nibble is shifted up to bit 31..28 int32_t nibble; if (loNibble) nibble = (int32_t(data) << 28) & 0xF0000000; else nibble = (int32_t(data) << 24) & 0xF0000000; // in the ARM ASM you can easily just shift by more than 31, but this does not work on x86/C++ if (_this->shiftMPTcompressed <= 63) { int32_t actualShift = (int32_t)(_this->shiftMPTcompressed >> 1u); _this->levelMPTcompressed = int16_t(_this->levelMPTcompressed + (nibble >> actualShift)); } if (nibble & 0x80000000) nibble = -nibble; _this->shiftMPTcompressed = uint8_t(_this->shiftMPTcompressed + 4); _this->shiftMPTcompressed = uint8_t((uint32_t)_this->shiftMPTcompressed - ((uint32_t)nibble >> 28u)); fetchBuffer[i++] = float(_this->levelMPTcompressed) / 128.0f; } while (--thisFetch > 0); if (_this->pos >= _this->sInfo.endPos) { // MPT compressed sample cannot loop std::fill(fetchBuffer.begin() + i, fetchBuffer.end(), 0.0f); return false; } } while (samplesToFetch > 0); return true; }
16,084
C++
.cpp
419
30.835322
150
0.613073
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,633
CGBChannel.cpp
ipatix_agbplay/src/CGBChannel.cpp
#include <cmath> #include <cassert> #include <algorithm> #include "CGBChannel.h" #include "CGBPatterns.h" #include "Xcept.h" #include "Debug.h" #include "Util.h" #include "Constants.h" #include "ConfigManager.h" /* * public CGBChannel */ CGBChannel::CGBChannel(ADSR env, Note note, bool useStairstep) : env(env), note(note), useStairstep(useStairstep) { this->env.att &= 0x7; this->env.dec &= 0x7; this->env.sus &= 0xF; this->env.rel &= 0x7; //if (note.trackIdx == 6) // Debug::print("note start: this=%p att=%d dec=%d sus=%d rel=%d", this, (int)env.att, (int)env.dec, (int)env.sus, (int)env.rel); } uint8_t CGBChannel::GetTrackIdx() const { return note.trackIdx; } void CGBChannel::SetVol(uint16_t vol, int16_t pan) { if (stop) return; /* CGB volume and pan aren't applied immediately due to the nature of being heavily * intertwined with the envelope handling. So save them and actually update them during envelope handling */ this->vol = vol; /* Due to aggressive rounding apply pan "perfectly" like for PCM channels, * so clamp to 127 instead of 128 */ this->pan = std::clamp<int16_t>(pan, -128, 127); this->mp2k_sus_vol_bug_update = true; } VolumeFade CGBChannel::getVol() const { return volFade; } uint8_t CGBChannel::getPseudoEchoLevel() const { return static_cast<uint8_t>(((envPeak * note.pseudoEchoVol) + 0xFF) >> 8); } float CGBChannel::timer2freq(float timer) { assert(timer >= 0.0f); assert(timer <= 2047.0f); return 131072.0f / static_cast<float>(2048.0f - timer); } float CGBChannel::freq2timer(float freq) { assert(freq > 0.0f); return 2048.0f - std::min(131072.0f / freq, 2047.0f); } const Note& CGBChannel::GetNote() const { return note; } void CGBChannel::Release(bool fastRelease) { this->stop = true; this->fastRelease = fastRelease; //if (note.trackIdx == 6) // Debug::print("releasing: %d", fastRelease); } bool CGBChannel::TickNote() { if (envState < EnvState::REL) { if (note.length > 0) { note.length--; if (note.length == 0) { /* Notes that stop on their own never release fast */ Release(false); return false; } } return true; } else { return false; } } EnvState CGBChannel::GetState() const { return envState; } bool CGBChannel::IsReleasing() const { return stop; } bool CGBChannel::IsFastReleasing() const { return fastRelease; } bool CGBChannel::IsChn3() const { return false; } void CGBChannel::stepEnvelope() { const GameConfig& cfg = ConfigManager::Instance().GetCfg(); if (envState == EnvState::INIT) { if (stop) { envState = EnvState::DEAD; return; } applyVol(); panPrev = panCur; envInterStep = 0; envLevelCur = 0; envFrameCount = env.att; envState = EnvState::ATK; if (envFrameCount > 0) { envFadeLevel = 0.0f; return; } else { if (env.dec > 0) { envFadeLevel = envPeak; } else if (envSustain > 0) { envFadeLevel = envSustain; } else if (getPseudoEchoLevel() > 0) { envFadeLevel = getPseudoEchoLevel(); } goto decay_start; } } else { if (fastRelease && envState != EnvState::DIE) { /* if note is already releasing but we are now releasing fast, do not wait * until the next real frame but stop the note immerdiately */ if (env.rel == 0 || envState == EnvState::PSEUDO_ECHO) envInterStep = INTERFRAMES - 1; else envInterStep = 0; envState = EnvState::DIE; envFrameCount = 1; return; } if (++envInterStep < INTERFRAMES) return; envInterStep = 0; assert(envFrameCount > 0); envFrameCount--; } /* if fastRelease == true then stop == true */ assert(!fastRelease || stop); if (envState == EnvState::PSEUDO_ECHO) { assert(note.pseudoEchoLen != 0); envFrameCount = 1; if (--note.pseudoEchoLen == 0) { envState = EnvState::DIE; envInterStep = INTERFRAMES - 1; } } else if (stop && envState < EnvState::REL) { envState = EnvState::REL; envFrameCount = env.rel; if (envLevelCur == 0 || envFrameCount == 0) { /* original doesn't branch on envLevelCur == 0, but we do in order to avoid * decreasing into the negative */ goto pseudo_echo_start; } else { return; } } else if (envFrameCount == 0) { applyVol(); if (envState == EnvState::REL) { assert(envLevelCur > 0); envLevelCur--; assert((int8_t)envLevelCur >= 0); if (envLevelCur == 0) { pseudo_echo_start: envFrameCount = 1; envLevelCur = getPseudoEchoLevel(); if (envLevelCur != 0 && note.pseudoEchoLen != 0) { /* original doesn't check for pseudoEchoLen */ envState = EnvState::PSEUDO_ECHO; } else { envState = EnvState::DIE; envInterStep = INTERFRAMES - 1; return; } } else { envFrameCount = env.rel; assert(env.rel != 0); } } else if (envState == EnvState::SUS) { sustain_state: if (cfg.GetSimulateCGBSustainBug()) { envFrameCount = 7; if (IsChn3()) envLevelCur = envSustain; // else: // envLevelCur is updated conditionally in applyVol() when when the sustain bug simulation is enabled } else { envFrameCount = 1; envLevelCur = envSustain; } } else if (envState == EnvState::DEC) { envLevelCur--; assert((int8_t)envLevelCur >= 0); if (envLevelCur <= envSustain) { sustain_start: if (env.sus == 0) { envState = EnvState::REL; goto pseudo_echo_start; } else { envState = EnvState::SUS; envLevelCur = envSustain; goto sustain_state; } } envFrameCount = env.dec; assert(env.dec != 0); } else if (envState == EnvState::ATK) { envLevelCur++; if (envLevelCur >= envPeak) { decay_start: envState = EnvState::DEC; envFrameCount = env.dec; if (envPeak == 0 || envFrameCount == 0 || envPeak == envSustain) { /* original code doesn't branch on envPeak == 0, but we do that we don't do a decrease envelope even * though the level is already zero. Original also doesn't branch when peak == sustain, which we to do avoid * an envelope decrease that will increase right after again. */ goto sustain_start; } else { envLevelCur = envPeak; } } else { envFrameCount = env.att; assert(env.att != 0); } } else if (envState == EnvState::DIE) { envState = EnvState::DEAD; return; } assert(envFrameCount != 0); } } void CGBChannel::updateVolFade() { size_t fadeInterframesCount = envFrameCount * INTERFRAMES - envInterStep; assert(fadeInterframesCount != 0); uint8_t envFadeLevelTo = 0xFF; switch (envState) { case EnvState::INIT: assert(false); break; case EnvState::ATK: assert(envLevelCur < 15); envFadeLevelTo = envLevelCur + 1; break; case EnvState::DEC: case EnvState::REL: assert(envLevelCur > 0); envFadeLevelTo = envLevelCur - 1; break; case EnvState::SUS: case EnvState::PSEUDO_ECHO: envFadeLevelTo = envLevelCur; fadeInterframesCount = 1; break; case EnvState::DIE: envFadeLevelTo = 0; break; case EnvState::DEAD: assert(false); break; } assert(envFadeLevelTo != 0xFF); float envFadeLevelNew; if (useStairstep) { /* In stairstep mode, the envelope will change in the last interframe before the next envelope update. * This fixes wave channels to behave like on hardware. */ if (fadeInterframesCount == 1) envFadeLevelNew = envFadeLevelTo; else envFadeLevelNew = envFadeLevel; } else { envFadeLevelNew = envFadeLevel + (envFadeLevelTo - envFadeLevel) / static_cast<float>(fadeInterframesCount); } volFade.fromVolLeft = (panPrev == Pan::RIGHT) ? 0.0f : envFadeLevel * (1.0f / 32.0f); volFade.fromVolRight = (panPrev == Pan::LEFT) ? 0.0f : envFadeLevel * (1.0f / 32.0f); volFade.toVolLeft = (panCur == Pan::RIGHT) ? 0.0f : envFadeLevelNew * (1.0f / 32.0f); volFade.toVolRight = (panCur == Pan::LEFT) ? 0.0f : envFadeLevelNew * (1.0f / 32.0f); //if (note.trackIdx == 6) // Debug::print("this=%p envState=%d envLevelCur=%d envFadeLevel=%f envFadeLevelNew=%f envFrameCount=%d envInterStep=%d", // this, (int)envState, (int)envLevelCur, envFadeLevel, envFadeLevelNew, (int)envFrameCount, (int)envInterStep); panPrev = panCur; envFadeLevel = envFadeLevelNew; } void CGBChannel::applyVol() { const GameConfig& cfg = ConfigManager::Instance().GetCfg(); /* because agbplay generally wants to avoid the center panorama dilemma * (i.e. 0 pan not being in the center of the [-128,127] range) * we delay applying pan changes at the channel level, so we don't do the slightly * off center rounding for PCM channels. */ int trkVolML = ((127 - pan) * vol) >> 8; int trkVolMR = ((pan + 128) * vol) >> 8; int chnVolL = (((127 - note.rhythmPan) * note.velocity) * trkVolML) >> 14; int chnVolR = (((note.rhythmPan + 128) * note.velocity) * trkVolMR) >> 14; assert(chnVolL >= 0); assert(chnVolR >= 0); /* strictly speaking the panorama also is affected by the sustain bug, but I'm too lazy to implement * is since most games probably won't be affected by this. */ if (chnVolR / 2 >= chnVolL) this->panCur = Pan::RIGHT; else if (chnVolL / 2 >= chnVolR) this->panCur = Pan::LEFT; else this->panCur = Pan::CENTER; /* This envLevelCur assignment used to be below envSustain assignment and the only reason * it's now up here is because of a bug in the original mp2k where only 1 in 7 cases the * envelope sustain level would be applied correctly. */ if (cfg.GetSimulateCGBSustainBug()) { if (!IsChn3() && mp2k_sus_vol_bug_update && envState == EnvState::SUS) { envLevelCur = envSustain; mp2k_sus_vol_bug_update = false; } } envPeak = static_cast<uint8_t>(std::clamp((chnVolL + chnVolR) >> 4, 0, 15)); envSustain = static_cast<uint8_t>(std::clamp((envPeak * env.sus + 15) >> 4, 0, 15)); } /* * public SquareChannel */ SquareChannel::SquareChannel(WaveDuty wd, ADSR env, Note note, uint8_t sweep) : CGBChannel(env, note) , sweep(sweep) , sweepEnabled(isSweepEnabled(sweep)) , sweepConvergence(sweep2convergence(sweep)) , sweepCoeff(sweep2coeff(sweep)) { static const float *patterns[4] = { CGBPatterns::pat_sq12, CGBPatterns::pat_sq25, CGBPatterns::pat_sq50, CGBPatterns::pat_sq75, }; this->pat = patterns[static_cast<int>(wd)]; this->rs = std::make_unique<BlepResampler>(); } void SquareChannel::SetPitch(int16_t pitch) { // non original quality improving behavior if (!stop || freq <= 0.0f) freq = 3520.0f * powf(2.0f, float(note.midiKeyPitch - 69) * (1.0f / 12.0f) + float(pitch) * (1.0f / 768.0f)); if (sweepEnabled && sweepStartCount < 0) { sweepTimer = freq2timer(freq / 8.0f); /* Because the initial frequency of a sweeped sound can only be set * in the beginning, we have to differentiate between the first and the other * SetPitch calls. */ uint8_t time = sweepTime(sweep); assert(time != 0); sweepStartCount = static_cast<int16_t>(time * AGB_FPS * INTERFRAMES); } } void SquareChannel::Process(sample *buffer, size_t numSamples, MixingArgs& args) { stepEnvelope(); if (envState == EnvState::DEAD) return; updateVolFade(); if (numSamples == 0) return; VolumeFade vol = getVol(); assert(pat); float lVolStep = (vol.toVolLeft - vol.fromVolLeft) * args.samplesPerBufferInv; float rVolStep = (vol.toVolRight - vol.fromVolRight) * args.samplesPerBufferInv; float lVol = vol.fromVolLeft; float rVol = vol.fromVolRight; float interStep; if (sweepEnabled) { //Debug::print("sweepTimer=%f sweepConvergence=%f sweepCoeff=%f resultFreq=%f", // sweepTimer, sweepConvergence, sweepCoeff, timer2freq(sweepTimer)); interStep = 8.0f * timer2freq(sweepTimer) * args.sampleRateInv; } else { interStep = freq * args.sampleRateInv; } float outBuffer[numSamples]; rs->Process(outBuffer, numSamples, interStep, sampleFetchCallback, this); size_t i = 0; do { float samp = outBuffer[i++]; buffer->left += samp * lVol; buffer->right += samp * rVol; buffer++; lVol += lVolStep; rVol += rVolStep; } while (--numSamples > 0); if (sweepEnabled) { assert(sweepStartCount >= 0); if (sweepStartCount == 0) { sweepTimer *= sweepCoeff; if (isSweepAscending(sweep)) sweepTimer = std::min(sweepTimer, sweepConvergence); else sweepTimer = std::max(sweepTimer, sweepConvergence); } else { sweepStartCount -= 128; if (sweepStartCount < 0) sweepStartCount = 0; } } } bool SquareChannel::sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; SquareChannel *_this = static_cast<SquareChannel *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); do { fetchBuffer[i++] = _this->pat[_this->pos++]; _this->pos %= 8; } while (--samplesToFetch > 0); return true; } bool SquareChannel::isSweepEnabled(uint8_t sweep) { if (sweep >= 0x80 || (sweep & 0x7) == 0) return false; else return true; } bool SquareChannel::isSweepAscending(uint8_t sweep) { if (sweep & 8) return false; else return true; } float SquareChannel::sweep2coeff(uint8_t sweep) { /* if sweep time is zero, don't change pitch */ const int sweep_time = sweepTime(sweep); if (sweep_time == 0) return 1.0f; const int shifts = sweep & 7; float step_coeff; if (isSweepAscending(sweep)) { /* if ascending */ step_coeff = static_cast<float>(128 + (128 >> shifts)) / 128.0f; } else { /* if descending */ step_coeff = static_cast<float>(128 - (128 >> shifts)) / 128.0f; } /* convert the sweep pitch timer coefficient to the rate that agbplay runs at */ const float hardware_sweep_rate = 128 / static_cast<float>(sweep_time); const float agbplay_sweep_rate = AGB_FPS * INTERFRAMES; const float coeff = powf(step_coeff, hardware_sweep_rate / agbplay_sweep_rate); return coeff; } float SquareChannel::sweep2convergence(uint8_t sweep) { if (isSweepAscending(sweep)) { /* if ascending: * * Convergance is always at the maximum timer value to prevent hardware overflow */ return 2047.0f; } else { /* if descending: * * Because hardware calculates sweep with: * timer -= timer >> shift * the timer converges to the value which timer >> shift always results zero. */ const int shifts = sweep & 7; return static_cast<float>((1 << shifts) - 1); } } uint8_t SquareChannel::sweepTime(uint8_t sweep) { return static_cast<uint8_t>((sweep & 0x70) >> 4); } /* * public WaveChannel */ WaveChannel::WaveChannel(const uint8_t *wavePtr, ADSR env, Note note, bool useStairstep) : CGBChannel(env, note, useStairstep), wavePtr(wavePtr) { this->rs = std::make_unique<BlepResampler>(); /* wave samples are unsigned by default, so we'll calculate the required * DC offset correction */ float sum = 0.0f; for (int i = 0; i < 16; i++) { uint8_t twoNibbles = wavePtr[i]; int nibbleA = twoNibbles >> 4; int nibbleB = twoNibbles & 0xF; sum += static_cast<float>(nibbleA) / 16.0f; sum += static_cast<float>(nibbleB) / 16.0f; } dcCorrection100 = -sum * (1.0f / 32.0f); GameConfig& cfg = ConfigManager::Instance().GetCfg(); if (cfg.GetAccurateCh3Quantization()) { sum = 0.0f; for (int i = 0; i < 16; i++) { uint8_t twoNibbles = wavePtr[i]; int nibbleA = twoNibbles >> 4; int nibbleB = twoNibbles & 0xF; sum += static_cast<float>((nibbleA >> 2) + (nibbleA >> 1)) / 16.0f; sum += static_cast<float>((nibbleB >> 2) + (nibbleB >> 1)) / 16.0f; } dcCorrection75 = -sum * (1.0f / 32.0f); sum = 0.0f; for (int i = 0; i < 16; i++) { uint8_t twoNibbles = wavePtr[i]; int nibbleA = twoNibbles >> 4; int nibbleB = twoNibbles & 0xF; sum += static_cast<float>((nibbleA >> 1)) / 16.0f; sum += static_cast<float>((nibbleB >> 1)) / 16.0f; } dcCorrection50 = -sum * (1.0f / 32.0f); sum = 0.0f; for (int i = 0; i < 16; i++) { uint8_t twoNibbles = wavePtr[i]; int nibbleA = twoNibbles >> 4; int nibbleB = twoNibbles & 0xF; sum += static_cast<float>((nibbleA >> 2)) / 16.0f; sum += static_cast<float>((nibbleB >> 2)) / 16.0f; } dcCorrection25 = -sum * (1.0f / 32.0f); } } void WaveChannel::SetPitch(int16_t pitch) { freq = (440.0f * 16.0f) * powf(2.0f, float(note.midiKeyPitch - 69) * (1.0f / 12.0f) + float(pitch) * (1.0f / 768.0f)); } void WaveChannel::Process(sample *buffer, size_t numSamples, MixingArgs& args) { stepEnvelope(); if (envState == EnvState::DEAD) return; //if (note.trackIdx == 6) // Debug::print("this=%p time=%f", this, (double)args.curInterFrame / (INTERFRAMES * AGB_FPS)); updateVolFade(); if (numSamples == 0) return; VolumeFade vol = getVol(); float lVolStep = (vol.toVolLeft - vol.fromVolLeft) * args.samplesPerBufferInv; float rVolStep = (vol.toVolRight - vol.fromVolRight) * args.samplesPerBufferInv; float lVol = vol.fromVolLeft; float rVol = vol.fromVolRight; float interStep = freq * args.sampleRateInv; float outBuffer[numSamples]; rs->Process(outBuffer, numSamples, interStep, sampleFetchCallback, this); size_t i = 0; do { float samp = outBuffer[i++]; buffer->left += samp * lVol; buffer->right += samp * rVol; buffer++; lVol += lVolStep; rVol += rVolStep; } while (--numSamples > 0); } bool WaveChannel::IsChn3() const { return true; } VolumeFade WaveChannel::getVol() const { GameConfig& cfg = ConfigManager::Instance().GetCfg(); auto retval = CGBChannel::getVol(); if (!cfg.GetAccurateCh3Volume()) { return retval; } auto snapFunc = [](float x) { if (x < 1.5f / 32.0f) return 0.0f / 32.0f; else if (x < 5.5f / 32.0f) return 4.0f / 32.0f; else if (x < 9.5f / 32.0f) return 8.0f / 32.0f; else if (x < 13.5f / 32.0f) return 12.0f / 32.0f; else return 16.0f / 32.0f; }; retval.fromVolLeft = snapFunc(retval.fromVolLeft); retval.fromVolRight = snapFunc(retval.fromVolRight); retval.toVolLeft = snapFunc(retval.toVolLeft); retval.toVolRight = snapFunc(retval.toVolRight); return retval; } bool WaveChannel::sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; WaveChannel *_this = static_cast<WaveChannel *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); GameConfig& cfg = ConfigManager::Instance().GetCfg(); if (cfg.GetAccurateCh3Quantization()) { /* WARNING; VERY UGLY AND HACKY */ VolumeFade fade = _this->getVol(); const float fromVol = std::max(fade.fromVolLeft, fade.fromVolRight); const float toVol = std::max(fade.toVolLeft, fade.toVolRight); /* I'm not entirely certain whether the hardware uses arithmetic shifts or logic shifts (with bias). * Using logic shifts for now, hopefully works good enough... */ auto mapFunc = [_this](float x, float& compensationScale, float& dcCorrection, uint32_t& shiftA, uint32_t& shiftB) { if (x < 6.0f / 32.0f) { shiftA = 2; shiftB = 4; compensationScale = 4.0f; dcCorrection = _this->dcCorrection25; } else if (x < 10.0f / 32.0f) { shiftA = 1; shiftB = 4; compensationScale = 2.0f; dcCorrection = _this->dcCorrection50; } else if (x < 14.0f / 32.0f) { shiftA = 1; shiftB = 2; compensationScale = 4.0f / 3.0f; dcCorrection = _this->dcCorrection75; } else { shiftA = 0; shiftB = 4; compensationScale = 1.0f; dcCorrection = _this->dcCorrection100; } }; uint32_t shiftAFrom, shiftATo, shiftBFrom, shiftBTo; float compensationScaleFrom, compensationScaleTo; float dcCorrectionFrom, dcCorrectionTo; mapFunc(fromVol, compensationScaleFrom, dcCorrectionFrom, shiftAFrom, shiftBFrom); mapFunc(toVol, compensationScaleTo, dcCorrectionTo, shiftATo, shiftBTo); dcCorrectionFrom *= 16.0f; dcCorrectionTo *= 16.0f; float t = 0.0f; float t_inc = 1.0f / static_cast<float>(samplesToFetch); while (samplesToFetch-- > 0) { uint32_t pos = (_this->pos++) % 32; uint8_t nibble; if (pos % 2 == 0) nibble = static_cast<uint8_t>(_this->wavePtr[pos / 2] >> 4u); else nibble = static_cast<uint8_t>(_this->wavePtr[pos / 2] & 0xF); float sampleFrom = (static_cast<float>((nibble >> shiftAFrom) + (nibble >> shiftBFrom)) + dcCorrectionFrom) * compensationScaleFrom; float sampleTo = (static_cast<float>((nibble >> shiftATo ) + (nibble >> shiftBTo )) + dcCorrectionTo ) * compensationScaleTo; float sample = (sampleFrom + t * (sampleTo - sampleFrom)) * (1.0f / 16.0f); t += t_inc; fetchBuffer[i++] = sample; } } else { while (samplesToFetch-- > 0) { uint32_t pos = (_this->pos++) % 32; uint8_t nibble; if (pos % 2 == 0) nibble = static_cast<uint8_t>(_this->wavePtr[pos / 2] >> 4u); else nibble = static_cast<uint8_t>(_this->wavePtr[pos / 2] & 0xF); float sample = nibble * (1.0f / 16.0f) + _this->dcCorrection100; fetchBuffer[i++] = sample; } } return true; } /* * public NoiseChannel */ NoiseChannel::NoiseChannel(NoisePatt np, ADSR env, Note note) : CGBChannel(env, note) { this->rs = std::make_unique<NearestResampler>(); if (np == NoisePatt::FINE) { noiseState = 0x4000; noiseLfsrMask = 0x6000; } else { noiseState = 0x40; noiseLfsrMask = 0x60; } } void NoiseChannel::SetPitch(int16_t pitch) { float fkey = note.midiKeyPitch + static_cast<float>(pitch) * (1.0f / 64.0f); float noisefreq; if (fkey < 76.0f) noisefreq = 4096.0f * powf(8.0f, (fkey - 60.0f) * (1.0f / 12.0f)); else if (fkey < 78.0f) noisefreq = 65536.0f * powf(2.0f, (fkey - 76.0f) * (1.0f / 2.0f)); else if (fkey < 80.0f) noisefreq = 131072.0f * powf(2.0f, (fkey - 78.0f)); else noisefreq = 524288.0f; freq = std::max(4.5714f, noisefreq); } void NoiseChannel::Process(sample *buffer, size_t numSamples, MixingArgs& args) { stepEnvelope(); if (envState == EnvState::DEAD) return; updateVolFade(); VolumeFade vol = getVol(); float lVolStep = (vol.toVolLeft - vol.fromVolLeft) * args.samplesPerBufferInv; float rVolStep = (vol.toVolRight - vol.fromVolRight) * args.samplesPerBufferInv; float lVol = vol.fromVolLeft; float rVol = vol.fromVolRight; float interStep = freq / NOISE_SAMPLING_FREQ; float outBuffer[numSamples]; Resampler::ResamplerChainData rcd; rcd._this = rs.get(); rcd.phaseInc = interStep; rcd.cbPtr = sampleFetchCallback; rcd.cbdata = this; srs.Process(outBuffer, numSamples, NOISE_SAMPLING_FREQ / float(STREAM_SAMPLERATE), Resampler::ResamplerChainSampleFetchCB, &rcd); size_t i = 0; do { float samp = outBuffer[i++]; buffer->left += samp * lVol; buffer->right += samp * rVol; buffer++; lVol += lVolStep; rVol += rVolStep; } while (--numSamples > 0); } bool NoiseChannel::sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; NoiseChannel *_this = static_cast<NoiseChannel *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); do { float sample; if (_this->noiseState & 1) { sample = 0.5f; _this->noiseState >>= 1; _this->noiseState ^= _this->noiseLfsrMask; } else { sample = -0.5f; _this->noiseState >>= 1; } fetchBuffer[i++] = sample; } while (--samplesToFetch > 0); return true; }
26,992
C++
.cpp
745
28.405369
144
0.590878
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,634
GameConfig.cpp
ipatix_agbplay/src/GameConfig.cpp
#include "GameConfig.h" #include "Util.h" #include <algorithm> /* * public GameConfig */ GameConfig::GameConfig(const std::string& gameCode) { gameCodes.push_back(gameCode); } GameConfig::GameConfig(const std::vector<std::string>& gameCodes) { this->gameCodes = gameCodes; } const std::vector<std::string>& GameConfig::GetGameCodes() const { return gameCodes; } ReverbType GameConfig::GetRevType() const { return revType; } void GameConfig::SetRevType(ReverbType revType) { this->revType = revType; } ResamplerType GameConfig::GetResTypeFixed() const { return resTypeFixed; } void GameConfig::SetResTypeFixed(ResamplerType resType) { this->resTypeFixed = resType; } ResamplerType GameConfig::GetResType() const { return resType; } void GameConfig::SetResType(ResamplerType resType) { this->resType = resType; } uint8_t GameConfig::GetPCMVol() const { return pcmVol; } void GameConfig::SetPCMVol(uint8_t pcmVol) { this->pcmVol = std::clamp<uint8_t>(pcmVol, 0, 0xF); } uint8_t GameConfig::GetEngineFreq() const { return engineFreq; } void GameConfig::SetEngineFreq(uint8_t engineFreq) { this->engineFreq = std::clamp<uint8_t>(engineFreq, 1, 12); } uint8_t GameConfig::GetEngineRev() const { return engineRev; } void GameConfig::SetEngineRev(uint8_t engineRev) { this->engineRev = engineRev; } uint8_t GameConfig::GetTrackLimit() const { return trackLimit; } void GameConfig::SetTrackLimit(uint8_t trackLimit) { this->trackLimit = std::clamp<uint8_t>(trackLimit, 0, 16); } uint16_t GameConfig::GetRevBufSize() const { return revBufSize; } void GameConfig::SetRevBufSize(uint16_t revBufSize) { this->revBufSize = revBufSize; } std::vector<SongEntry>& GameConfig::GetGameEntries() { return gameEntries; } bool GameConfig::GetAccurateCh3Volume() const { return accurateCh3Volume; } void GameConfig::SetAccurateCh3Volume(bool enabled) { this->accurateCh3Volume = enabled; } bool GameConfig::GetAccurateCh3Quantization() const { return accurateCh3Quantization; } void GameConfig::SetAccurateCh3Quantization(bool enabled) { this->accurateCh3Quantization = enabled; } bool GameConfig::GetSimulateCGBSustainBug() const { return simulateCGBSustainBug; } void GameConfig::SetSimulateCGBSustainBug(bool enabled) { this->simulateCGBSustainBug = enabled; }
2,375
C++
.cpp
110
19.372727
65
0.775145
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,635
SongEntry.cpp
ipatix_agbplay/src/SongEntry.cpp
#include "SongEntry.h" /* * SongEntry */ SongEntry::SongEntry(const std::string& name, uint16_t uid) : name(name), uid(uid) { } const std::string& SongEntry::GetName() const { return name; } uint16_t SongEntry::GetUID() const { return uid; }
261
C++
.cpp
16
14.125
60
0.692946
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,636
Debug.cpp
ipatix_agbplay/src/Debug.cpp
#include <cstdio> #include <cstdarg> #include <string> #include <mutex> #include <cstdarg> #include "Debug.h" static FILE *debug_file = nullptr; bool Debug::open(const char *file) { if (!file) return true; debug_file = fopen(file, "w"); if (debug_file == nullptr) { perror("fopen"); return false; } return true; } bool Debug::close() { if (debug_file == nullptr) return true; if (fclose(debug_file) != 0) return false; debug_file = nullptr; return true; } static void (*callback)(const std::string&, void *) = nullptr; static void *cb_obj = nullptr; void Debug::set_callback(void (*cb)(const std::string&, void *), void *obj) { callback = cb; cb_obj = obj; } void Debug::print(const char *str, ...) { va_list args; va_start(args, str); char txtbuf[512]; vsnprintf(txtbuf, sizeof(txtbuf), str, args); if (debug_file) { fprintf(debug_file, "%s\n", txtbuf); fflush(debug_file); } va_end(args); if (callback) { callback(txtbuf, cb_obj); } }
1,091
C++
.cpp
45
19.822222
77
0.610039
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,637
Resampler.cpp
ipatix_agbplay/src/Resampler.cpp
#include <boost/math/special_functions/sinc.hpp> #include "Resampler.h" #include "Util.h" #include "Debug.h" Resampler::~Resampler() { } bool Resampler::ResamplerChainSampleFetchCB(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata) { if (fetchBuffer.size() >= samplesRequired) return true; ResamplerChainData *chainData = static_cast<ResamplerChainData *>(cbdata); size_t samplesToFetch = samplesRequired - fetchBuffer.size(); size_t i = fetchBuffer.size(); fetchBuffer.resize(samplesRequired); return chainData->_this->Process(&fetchBuffer[i], samplesToFetch, chainData->phaseInc, chainData->cbPtr, chainData->cbdata); } NearestResampler::NearestResampler() { Reset(); } NearestResampler::~NearestResampler() { } void NearestResampler::Reset() { fetchBuffer.clear(); phase = 0.0f; } bool NearestResampler::Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) { if (numBlocks == 0) return true; size_t samplesRequired = size_t(phase + phaseInc * static_cast<float>(numBlocks)); // be sure and fetch one more sample in case of odd rounding errors samplesRequired += 1; bool result = cbPtr(fetchBuffer, samplesRequired, cbdata); int i = 0; do { float sample = fetchBuffer[i]; phase += phaseInc; int istep = static_cast<int>(phase); phase -= static_cast<float>(istep); i += istep; *outData++ = sample; } while (--numBlocks > 0); // remove first i elements from the fetch buffer since they are no longer needed fetchBuffer.erase(fetchBuffer.begin(), fetchBuffer.begin() + i); return result; } LinearResampler::LinearResampler() { Reset(); } LinearResampler::~LinearResampler() { } void LinearResampler::Reset() { fetchBuffer.clear(); phase = 0.0f; } bool LinearResampler::Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) { if (numBlocks == 0) return true; size_t samplesRequired = static_cast<size_t>( phase + phaseInc * static_cast<float>(numBlocks)); // be sure and fetch one more sample in case of odd rounding errors samplesRequired += 1; // fetch one more for linear interpolation samplesRequired += 1; bool result = cbPtr(fetchBuffer, samplesRequired, cbdata); int i = 0; do { float a = fetchBuffer[i]; float b = fetchBuffer[i+1]; float sample = a + phase * (b - a); phase += phaseInc; int istep = static_cast<int>(phase); phase -= static_cast<float>(istep); i += istep; *outData++ = sample; } while (--numBlocks > 0); // remove first i elements from the fetch buffer since they are no longer needed fetchBuffer.erase(fetchBuffer.begin(), fetchBuffer.begin() + i); return result; } //static float triangle(float t) //{ // if (t < -1.0f) // return 0.0f; // else if (t < 0.0f) // return t + 1.0f; // else if (t < 1.0f) // return 1.0f - t; // else // return 0.0f; //} #define SINC_WINDOW_SIZE 16 #define SINC_FILT_THRESH 0.85f SincResampler::SincResampler() { Reset(); } SincResampler::~SincResampler() { } void SincResampler::Reset() { fetchBuffer.clear(); fetchBuffer.resize(SINC_WINDOW_SIZE, 0.0f); phase = 0.0f; } bool SincResampler::Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) { if (numBlocks == 0) return true; size_t samplesRequired = static_cast<size_t>( phase + phaseInc * static_cast<float>(numBlocks)); // be sure and fetch one more sample in case of odd rounding errors samplesRequired += 1; // fetch a few more for complete windowed sinc interpolation samplesRequired += SINC_WINDOW_SIZE * 2; bool result = cbPtr(fetchBuffer, samplesRequired, cbdata); float sincStep = phaseInc > SINC_FILT_THRESH ? SINC_FILT_THRESH / phaseInc : 1.00f; //float sincStep = 1.0; //_print_debug("phaseInc=%f sincStep=%f", phaseInc, sincStep); int i = 0; do { float sampleSum = 0.0f; float kernelSum = 0.0f; for (int wi = -SINC_WINDOW_SIZE + 1; wi <= SINC_WINDOW_SIZE; wi++) { float sincIndex = (float(wi) - phase) * sincStep; float windowIndex = float(wi) - phase; //_print_debug("wi=%zu phase=%f sincStep=%f sincIndex=%f", wi, phase, sincStep, sincIndex); float s = fast_sincf(sincIndex); float w = window_func(windowIndex); //float s = triangle(sincIndex); //float w = 1.0f; float kernel = s * w; sampleSum += kernel * fetchBuffer[i + wi + SINC_WINDOW_SIZE - 1]; kernelSum += kernel; //_print_debug("s=%f w=%f fetchBuffer[i + wi]=%f", s, w, fetchBuffer[i + wi]); } //_print_debug("sum=%f", sum); phase += phaseInc; int istep = static_cast<int>(phase); phase -= static_cast<float>(istep); i += istep; *outData++ = sampleSum / kernelSum; //*outData++ = sampleSum; //_print_debug("kernel sum: %f\n", kernelSum); } while (--numBlocks > 0); // remove first i elements from the fetch buffer since they are no longer needed fetchBuffer.erase(fetchBuffer.begin(), fetchBuffer.begin() + i); return result; } /* * fast trigonometric functions */ // anything higher than 256 LUT size seems to be indistinguishable #define LUT_SIZE 256 static const std::vector<float> cos_lut = []() { std::vector<float> l(LUT_SIZE); for (size_t i = 0; i < l.size(); i++) { float index = float(i) * float(2.0 * M_PI / double(LUT_SIZE)); l[i] = cosf(index); } l.shrink_to_fit(); return l; }(); static const std::vector<float> sinc_lut = []() { std::vector<float> l(LUT_SIZE+2); for (size_t i = 0; i < LUT_SIZE+1; i++) { float index = float(i) * float(SINC_WINDOW_SIZE * M_PI / double(LUT_SIZE)); l[i] = boost::math::sinc_pi(index); } l[LUT_SIZE+1] = 0.0f; l.shrink_to_fit(); return l; }(); static const std::vector<float> win_lut = []() { // hann window (raised cosine) std::vector<float> l(LUT_SIZE+2); for (size_t i = 0; i < LUT_SIZE+1; i++) { float index = float(i) * float(M_PI / double(LUT_SIZE)); l[i] = 0.5f + (0.5f * cosf(index)); } l[LUT_SIZE+1] = 0.0f; l.shrink_to_fit(); return l; }(); /* static const std::vector<float> win_lut = []() { // nuttall window, experimental, performs worse than hann ? std::vector<float> l(LUT_SIZE+2); for (size_t i = 0; i < LUT_SIZE+1; i++) { const double a0 = 0.355768; const double a1 = 0.487396; const double a2 = 0.144232; const double a3 = 0.012604; const double N = static_cast<double>(LUT_SIZE); const double pi_i_N = 0.5 * M_PI + static_cast<double>(i) * M_PI / (2.0 * N); const double coeff = a0 - a1 * cos(2.0 * pi_i_N) + a2 * cos(4.0 * pi_i_N) - a3 * cos(6.0 * pi_i_N); l[i] = static_cast<float>(coeff); } l[LUT_SIZE+1] = l[LUT_SIZE]; l.shrink_to_fit(); return l; }(); */ float SincResampler::fast_sinf(float t) { return SincResampler::fast_cosf(t - float(M_PI / 2.0)); } float SincResampler::fast_cosf(float t) { t = fabs(t); t *= float(double(LUT_SIZE) / (2.0 * M_PI)); uint32_t left_index = static_cast<uint32_t>(t); float fraction = t - static_cast<float>(left_index); uint32_t right_index = (left_index + 1) % LUT_SIZE; left_index %= LUT_SIZE; return cos_lut[left_index] + fraction * (cos_lut[right_index] - cos_lut[left_index]); } float SincResampler::fast_sincf(float t) { t = fabs(t); assert(t <= SINC_WINDOW_SIZE); t *= float(double(LUT_SIZE) / double(SINC_WINDOW_SIZE)); uint32_t left_index = static_cast<uint32_t>(t); float fraction = t - static_cast<float>(left_index); uint32_t right_index = left_index + 1; return sinc_lut[left_index] + fraction * (sinc_lut[right_index] - sinc_lut[left_index]); } float SincResampler::window_func(float t) { assert(t >= -float(SINC_WINDOW_SIZE)); assert(t <= +float(SINC_WINDOW_SIZE)); //return 0.42659f - 0.49656f * cosf(2.0f * PI_F * t / float(SINC_WINDOW_SIZE - 1)) + // 0.076849f * cosf(4.0f * PI_F * t / float(SINC_WINDOW_SIZE - 1)); t = fabs(t); t *= float(double(LUT_SIZE) / double(SINC_WINDOW_SIZE)); uint32_t left_index = static_cast<uint32_t>(t); float fraction = t - static_cast<float>(left_index); uint32_t right_index = left_index + 1; return win_lut[left_index] + fraction * (win_lut[right_index] - win_lut[left_index]); } BlepResampler::BlepResampler() { Reset(); } BlepResampler::~BlepResampler() { } void BlepResampler::Reset() { fetchBuffer.clear(); fetchBuffer.resize(SINC_WINDOW_SIZE, 0.0f); phase = 0.0f; } bool BlepResampler::Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) { if (numBlocks == 0) return true; size_t samplesRequired = static_cast<size_t>( phase + phaseInc * static_cast<float>(numBlocks)); // be sure and fetch one more sample in case of odd rounding errors samplesRequired += 1; // fetch a few more for complete windowed sinc interpolation samplesRequired += SINC_WINDOW_SIZE * 2; bool result = cbPtr(fetchBuffer, samplesRequired, cbdata); float sincStep = SINC_FILT_THRESH / phaseInc; int i = 0; do { float sampleSum = 0.0f; float kernelSum = 0.0f; for (int wi = -SINC_WINDOW_SIZE + 1; wi <= SINC_WINDOW_SIZE; wi++) { float SiIndexLeft = (float(wi) - phase - 0.5f) * sincStep; float SiIndexRight = (float(wi) - phase + 0.5f) * sincStep; float sl = fast_Si(SiIndexLeft); float sr = fast_Si(SiIndexRight); float kernel = sr - sl; sampleSum += kernel * fetchBuffer[i + wi + SINC_WINDOW_SIZE - 1]; kernelSum += kernel; } phase += phaseInc; int istep = static_cast<int>(phase); phase -= static_cast<float>(istep); i += istep; *outData++ = sampleSum / kernelSum; //*outData++ = sampleSum; //_print_debug("kernel sum: %f\n", kernelSum); } while (--numBlocks > 0); // remove first i elements from the fetch buffer since they are no longer needed fetchBuffer.erase(fetchBuffer.begin(), fetchBuffer.begin() + i); return result; } #define INTEGRAL_RESOLUTION 256 static const std::vector<float> Si_lut = []() { std::vector<float> l(LUT_SIZE+2); double acc = 0.0; double step_per_index = double(SINC_WINDOW_SIZE) / double(LUT_SIZE); double integration_inc = step_per_index / double(INTEGRAL_RESOLUTION); double index = 0.0; double prev_value = 1.0; for (size_t i = 0; i < LUT_SIZE+1; i++) { double convergence_level = 0.5 - 0.5 * cos(double(i) * M_PI / double(LUT_SIZE)); double integral_level = 1.0 - convergence_level; l[i] = static_cast<float>(acc * integral_level + 0.5 * convergence_level); for (size_t j = 0; j < INTEGRAL_RESOLUTION; j++) { index += integration_inc; double new_value = boost::math::sinc_pi(M_PI * index); acc += (new_value + prev_value) * integration_inc * 0.5; prev_value = new_value; } } l[LUT_SIZE+1] = 0.5f; l.shrink_to_fit(); return l; }(); float BlepResampler::fast_Si(float t) { float signed_t = t; t = fabs(t); t = std::min(t, float(SINC_WINDOW_SIZE)); t *= float(double(LUT_SIZE) / double(SINC_WINDOW_SIZE)); uint32_t left_index = static_cast<uint32_t>(t); float fraction = t - static_cast<float>(left_index); uint32_t right_index = left_index + 1; float retval = Si_lut[left_index] + fraction * (Si_lut[right_index] - Si_lut[left_index]); return copysignf(retval, signed_t); } BlampResampler::BlampResampler() { Reset(); } BlampResampler::~BlampResampler() { } void BlampResampler::Reset() { fetchBuffer.clear(); fetchBuffer.resize(SINC_WINDOW_SIZE, 0.0f); phase = 0.0f; } bool BlampResampler::Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) { if (numBlocks == 0) return true; size_t samplesRequired = static_cast<size_t>( phase + phaseInc * static_cast<float>(numBlocks)); // be sure and fetch one more sample in case of odd rounding errors samplesRequired += 1; // fetch a few more for complete windowed sinc interpolation samplesRequired += SINC_WINDOW_SIZE * 2; bool result = cbPtr(fetchBuffer, samplesRequired, cbdata); float sincStep = SINC_FILT_THRESH / phaseInc; int i = 0; do { float sampleSum = 0.0f; float kernelSum = 0.0f; for (int wi = -SINC_WINDOW_SIZE + 1; wi <= SINC_WINDOW_SIZE; wi++) { float TiIndexLeft = (float(wi) - phase - 1.0f) * sincStep; float TiIndexMiddle = (float(wi) - phase) * sincStep; float TiIndexRight = (float(wi) - phase + 1.0f) * sincStep; float sl = fast_Ti(TiIndexLeft); float sm = fast_Ti(TiIndexMiddle); float sr = fast_Ti(TiIndexRight); float kernel = sr - 2.0f * sm + sl; sampleSum += kernel * fetchBuffer[i + wi + SINC_WINDOW_SIZE - 1]; kernelSum += kernel; } phase += phaseInc; int istep = static_cast<int>(phase); phase -= static_cast<float>(istep); i += istep; *outData++ = sampleSum / kernelSum; } while (--numBlocks > 0); // remove first i elements from the fetch buffer since they are no longer needed fetchBuffer.erase(fetchBuffer.begin(), fetchBuffer.begin() + i); return result; } // I call "Ti" the integral of Si function. I don't know its proper name static const std::vector<float> Ti_lut = []() { std::vector<float> l(LUT_SIZE+2); double acc = 0.0; double step_per_index = double(SINC_WINDOW_SIZE) / double(LUT_SIZE); double integration_inc = step_per_index / double(INTEGRAL_RESOLUTION); double index = 0.0; double prev_value = 1.0; for (size_t i = 0; i < LUT_SIZE+1; i++) { const double t = double(i) * step_per_index; const double convergence_value = t * 0.5; const double function_value = t * acc + cos(M_PI * t) / (M_PI * M_PI); const double interpolation_t = 0.5 - 0.5 * cos(double(i) * M_PI / double(LUT_SIZE)); const double interpolated_value = function_value + interpolation_t * (convergence_value - function_value); l[i] = static_cast<float>(interpolated_value); for (size_t j = 0; j < INTEGRAL_RESOLUTION; j++) { index += integration_inc; double new_value = boost::math::sinc_pi(M_PI * index); acc += (new_value + prev_value) * integration_inc * 0.5; prev_value = new_value; } } l[LUT_SIZE+1] = static_cast<float>(((LUT_SIZE+1) * step_per_index) * 0.5); l.shrink_to_fit(); return l; }(); float BlampResampler::fast_Ti(float t) { t = fabs(t); float ct = t; ct = std::min(ct, float(SINC_WINDOW_SIZE)); ct *= float(double(LUT_SIZE) / double(SINC_WINDOW_SIZE)); uint32_t left_index = static_cast<uint32_t>(ct); float fraction = ct - static_cast<float>(left_index); uint32_t right_index = left_index + 1; float retval = Ti_lut[left_index] + fraction * (Ti_lut[right_index] - Ti_lut[left_index]); if (t > float(SINC_WINDOW_SIZE)) return t * 0.5f; else return retval; }
15,795
C++
.cpp
426
31.544601
119
0.623137
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,638
ConfigManager.cpp
ipatix_agbplay/src/ConfigManager.cpp
#include <fstream> #include <regex> #include <cstring> #include <iostream> #include <cstdlib> // sorry, for some reason multiple versions of jsoncpp use different paths :/ #if __has_include(<json/json.h>) #include <json/json.h> #include <json/writer.h> #else #include <jsoncpp/json/json.h> #include <jsoncpp/json/writer.h> #endif #include "ConfigManager.h" #include "Util.h" #include "Xcept.h" #include "Debug.h" #include "OS.h" ConfigManager& ConfigManager::Instance() { static ConfigManager cm; return cm; } GameConfig& ConfigManager::GetCfg() { if (curCfg) return *curCfg; else throw Xcept("Trying to get the game config without setting the game code"); } const GameConfig& ConfigManager::GetCfg() const { if (curCfg) return *curCfg; else throw Xcept("Trying to get the game config without setting the game code"); } void ConfigManager::SetGameCode(const std::string& gameCode) { for (GameConfig& config : configs) { const auto &gameCodesToCheck = config.GetGameCodes(); if (std::find(gameCodesToCheck.begin(), gameCodesToCheck.end(), gameCode) != gameCodesToCheck.end()) { curCfg = &config; return; } } configs.emplace_back(gameCode); curCfg = &configs.back(); } void ConfigManager::Load() { configPath = OS::GetLocalConfigDirectory() / "agbplay.json"; const auto globalConfigPath = OS::GetGlobalConfigDirectory() / "agbplay.json"; /* Parse things from config file. * If the config file in home directory is not found, * try reading it from /etc/agbplay/agbplay.json. * If this isn't found either, use an empty config file. */ Json::Value root; if (std::ifstream configFile; configFile.open(configPath), configFile.is_open()) { Debug::print("User local configuration found!"); configFile >> root; } else if (configFile.open(globalConfigPath); configFile.is_open()) { Debug::print("Global configuration found!"); configFile >> root; } else { Debug::print("No configuration file found. Creating new configuration."); root["id"] = "agbplay"; root["playlists"] = Json::Value(); // null value } if (root["id"].asString() != "agbplay") throw Xcept("Bad JSON ID: %s", root["id"].asString().c_str()); // output directory used for saving rendered sogs if (root.isMember("wav-output-dir")) { confWavOutputDir = root["wav-output-dir"].asString(); } else { confWavOutputDir = OS::GetMusicDirectory() / "agbplay"; } // CGB channel polyphony configuration confCgbPolyphony = str2cgbPoly(root.get("cgb-polyphony", "mono-strict").asString()); // Loop configuration maxLoopsPlaylist = static_cast<int8_t>(root.get("max-loops-playlist", 1).asInt()); maxLoopsExport = static_cast<int8_t>(root.get("max-loops-export", 1).asInt()); // Silence padding padSecondsStart = root.get("pad-seconds-start", 0.0).asDouble(); padSecondsEnd = root.get("pad-seconds-end", 0.0).asDouble(); for (Json::Value playlist : root["playlists"]) { // parse games std::vector<std::string> games; for (Json::Value game : playlist["games"]) games.emplace_back(game.asString()); configs.emplace_back(games); // parse other parameters configs.back().SetPCMVol(uint8_t(std::clamp<int>(playlist.get("pcm-master-volume", 15).asInt(), 0, 15))); configs.back().SetEngineFreq(uint8_t(std::clamp<int>(playlist.get("pcm-samplerate", 4).asInt(), 0, 15))); configs.back().SetEngineRev(uint8_t(std::clamp<int>(playlist.get("pcm-reverb-level", 0).asInt(), 0, 255))); configs.back().SetRevBufSize(uint16_t(playlist.get("pcm-reverb-buffer-len", 0x630).asUInt())); configs.back().SetRevType(str2rev(playlist.get("pcm-reverb-type", "normal").asString())); configs.back().SetResType(str2res(playlist.get("pcm-resampling-algo", "linear").asString())); configs.back().SetResTypeFixed(str2res(playlist.get("pcm-fixed-rate-resampling-algo", "linear").asString())); configs.back().SetTrackLimit(uint8_t(std::clamp<int>(playlist.get("song-track-limit", 16).asInt(), 0, 16))); configs.back().SetAccurateCh3Volume(playlist.get("accurate-ch3-volume", false).asBool()); configs.back().SetAccurateCh3Quantization(playlist.get("accurate-ch3-quantization", false).asBool()); configs.back().SetSimulateCGBSustainBug(playlist.get("simulate-cgb-sustain-bug", false).asBool()); for (Json::Value song : playlist["songs"]) { configs.back().GetGameEntries().emplace_back( song.get("name", "?").asString(), static_cast<uint16_t>(song.get("index", "0").asUInt())); } } } void ConfigManager::Save() { Json::Value playlists; for (GameConfig& cfg : configs) { Json::Value playlist; playlist["pcm-master-volume"] = static_cast<int>(cfg.GetPCMVol()); playlist["pcm-samplerate"] = static_cast<int>(cfg.GetEngineFreq()); playlist["pcm-reverb-level"] = static_cast<int>(cfg.GetEngineRev()); playlist["pcm-reverb-buffer-len"] = static_cast<int>(cfg.GetRevBufSize()); playlist["pcm-reverb-type"] = rev2str(cfg.GetRevType()); playlist["pcm-resampling-algo"] = res2str(cfg.GetResType()); playlist["pcm-fixed-rate-resampling-algo"] = res2str(cfg.GetResTypeFixed()); playlist["song-track-limit"] = static_cast<int>(cfg.GetTrackLimit()); playlist["accurate-ch3-volume"] = cfg.GetAccurateCh3Volume(); playlist["accurate-ch3-quantization"] = cfg.GetAccurateCh3Quantization(); playlist["simulate-cgb-sustain-bug"] = cfg.GetSimulateCGBSustainBug(); Json::Value games; for (const std::string& code : cfg.GetGameCodes()) games.append(code); playlist["games"] = games; Json::Value songs; for (SongEntry entr : cfg.GetGameEntries()) { Json::Value song; song["index"] = entr.GetUID(); song["name"] = entr.name; songs.append(song); } playlist["songs"] = songs; playlists.append(playlist); } Json::Value root; root["id"] = "agbplay"; root["wav-output-dir"] = confWavOutputDir.string(); root["cgb-polyphony"] = cgbPoly2str(confCgbPolyphony); root["playlists"] = playlists; root["max-loops-playlist"] = maxLoopsPlaylist; root["max-loops-export"] = maxLoopsExport; root["pad-seconds-start"] = padSecondsStart; root["pad-seconds-end"] = padSecondsEnd; std::filesystem::create_directories(configPath.parent_path()); std::ofstream jsonFile(configPath); if (!jsonFile.is_open()) throw Xcept("Error while writing agbplay.json: %s", strerror(errno)); Json::StreamWriterBuilder builder; builder["emitUTF8"] = true; builder["commentStyle"] = "None"; // <-- this prevents trailing whitespaces in all versions std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); writer->write(root, &jsonFile); jsonFile << std::endl; Debug::print("Configuration/Playlist saved!"); } const std::filesystem::path& ConfigManager::GetWavOutputDir() { return confWavOutputDir; } CGBPolyphony ConfigManager::GetCgbPolyphony() const { return confCgbPolyphony; } void ConfigManager::SetCgbPolyphony(CGBPolyphony value) { confCgbPolyphony = value; } int8_t ConfigManager::GetMaxLoopsPlaylist() const { return maxLoopsPlaylist < -1 ? 0 : maxLoopsPlaylist; } void ConfigManager::SetMaxLoopsPlaylist(int8_t value) { maxLoopsPlaylist = value; } int8_t ConfigManager::GetMaxLoopsExport() const { return maxLoopsExport < 0 ? 0 : maxLoopsExport; } void ConfigManager::SetMaxLoopsExport(int8_t value) { maxLoopsExport = value; } double ConfigManager::GetPadSecondsStart() const { return padSecondsStart; } void ConfigManager::SetPadSecondsStart(double value) { padSecondsStart = value; } double ConfigManager::GetPadSecondsEnd() const { return padSecondsEnd; } void ConfigManager::SetPadSecondsEnd(double value) { padSecondsEnd = value; }
8,223
C++
.cpp
207
34.289855
117
0.676106
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,639
PlaylistGUI.cpp
ipatix_agbplay/src/PlaylistGUI.cpp
#include <algorithm> #include <cstring> #include "PlaylistGUI.h" #include "ColorDef.h" #include "Util.h" #include "Xcept.h" #include "Debug.h" #include "ConfigManager.h" /* * public */ PlaylistGUI::PlaylistGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : SonglistGUI(height, width, yPos, xPos, false) { // init ticked.resize(ConfigManager::Instance().GetCfg().GetGameEntries().size(), true); dragging = false; update(); } PlaylistGUI::~PlaylistGUI() { } void PlaylistGUI::AddSong(SongEntry entry) { ConfigManager::Instance().GetCfg().GetGameEntries().push_back(entry); ticked.push_back(true); update(); } void PlaylistGUI::RemoveSong() { GameConfig& cfg = ConfigManager::Instance().GetCfg(); if (cfg.GetGameEntries().size() == 0) return; cfg.GetGameEntries().erase(cfg.GetGameEntries().begin() + cursorPos); ticked.erase(ticked.begin() + cursorPos); if (cursorPos != 0 && cursorPos >= cfg.GetGameEntries().size()) { cursorPos--; } update(); } void PlaylistGUI::ClearSongs() { viewPos = 0; cursorPos = 0; GameConfig& cfg = ConfigManager::Instance().GetCfg(); cfg.GetGameEntries().clear(); ticked.clear(); update(); } SongEntry *PlaylistGUI::GetSong() { GameConfig& cfg = ConfigManager::Instance().GetCfg(); if (this->cursorPos >= cfg.GetGameEntries().size()) return nullptr; return &cfg.GetGameEntries()[cursorPos]; } std::vector<bool>& PlaylistGUI::GetTicked() { return ticked; } void PlaylistGUI::Tick() { if (ticked.size() == 0) return; ticked.at(cursorPos) = true; update(); } void PlaylistGUI::Untick() { if (ticked.size() == 0) return; ticked.at(cursorPos) = false; update(); } void PlaylistGUI::ToggleTick() { if (ticked.size() == 0) return; ticked.at(cursorPos) = !ticked.at(cursorPos); update(); } void PlaylistGUI::ToggleDrag() { dragging = !dragging; update(); } void PlaylistGUI::UntickAll() { fill(ticked.begin(), ticked.end(), false); update(); } bool PlaylistGUI::IsDragging() { return dragging; } void PlaylistGUI::Leave() { dragging = false; SonglistGUI::Leave(); } /* * private */ void PlaylistGUI::update() { //UIMutex.lock(); GameConfig& cfg = ConfigManager::Instance().GetCfg(); std::string bar = "Playlist:"; bar.resize(contentWidth, ' '); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); mvwprintw(winPtr, 0, 0, bar.c_str()); for (uint32_t i = 0; i < contentHeight; i++) { uint32_t entry = i + viewPos; if (entry == cursorPos && cursorVisible) { if (dragging) { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::LIST_SEL)) | A_REVERSE); } else { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::LIST_ENTRY)) | A_REVERSE); } } else wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::LIST_ENTRY))); std::string songText; if (entry < cfg.GetGameEntries().size()) { songText = (ticked.at(entry)) ? "[x] " : "[ ] "; songText.append(cfg.GetGameEntries()[entry].name); } else { songText = ""; } songText.resize(width, ' '); mvwprintw(winPtr, (int)(height - contentHeight + (uint32_t)i), 0, songText.c_str()); } wrefresh(winPtr); //UIMutex.unlock(); } void PlaylistGUI::scrollDownNoUpdate() { GameConfig& cfg = ConfigManager::Instance().GetCfg(); uint32_t pcursor = cursorPos; if (cursorPos + 1 >= cfg.GetGameEntries().size()) return; cursorPos++; if (viewPos + contentHeight < cfg.GetGameEntries().size() && cursorPos > viewPos + contentHeight - 5) viewPos++; if (dragging && pcursor != cursorPos) swapEntry(pcursor, cursorPos); } void PlaylistGUI::scrollUpNoUpdate() { uint32_t pcursor = cursorPos; if (cursorPos == 0) return; cursorPos--; if (viewPos > 0 && cursorPos < viewPos + 4) viewPos--; if (dragging && pcursor != cursorPos) swapEntry(pcursor, cursorPos); } void PlaylistGUI::swapEntry(uint32_t a, uint32_t b) { GameConfig& cfg = ConfigManager::Instance().GetCfg(); size_t s = cfg.GetGameEntries().size(); if (a >= s || b >= s) return; std::swap(cfg.GetGameEntries()[a], cfg.GetGameEntries()[b]); std::vector<bool>::swap(ticked[a], ticked[b]); update(); }
4,531
C++
.cpp
165
22.866667
105
0.631567
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,640
OS.cpp
ipatix_agbplay/src/OS.cpp
#include "OS.h" #include "Xcept.h" #include <filesystem> #include <iostream> #if defined(_WIN32) // if we compile for Windows native #include <windows.h> #include <shlobj.h> void OS::LowerThreadPriority() { // ignore errors if this fails SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); } const std::filesystem::path OS::GetMusicDirectory() { PWSTR folderPath = NULL; HRESULT result = SHGetKnownFolderPath(FOLDERID_Music, KF_FLAG_DEFAULT, NULL, &folderPath); if (result != S_OK) throw Xcept("SHGetKnownFolderPath: Failed to retrieve AppData folder"); std::filesystem::path retval(folderPath); CoTaskMemFree(folderPath); return retval; } const std::filesystem::path OS::GetLocalConfigDirectory() { PWSTR folderPath = NULL; HRESULT result = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, NULL, &folderPath); if (result != S_OK) throw Xcept("SHGetKnownFolderPath: Failed to retrieve AppData folder"); std::filesystem::path retval(folderPath); CoTaskMemFree(folderPath); return retval; } const std::filesystem::path OS::GetGlobalConfigDirectory() { PWSTR folderPath = NULL; HRESULT result = SHGetKnownFolderPath(FOLDERID_ProgramData, KF_FLAG_DEFAULT, NULL, &folderPath); if (result != S_OK) throw Xcept("SHGetKnownFolderPath: Failed to retrieve ProgramData folder"); std::filesystem::path retval(folderPath); CoTaskMemFree(folderPath); return retval; } #elif __has_include(<unistd.h>) // if we compile for a UNIX'oid #include <unistd.h> #include <pwd.h> #include <string.h> void OS::LowerThreadPriority() { // we don't really care about errors here, so ignore errno nice(15); } const std::filesystem::path OS::GetMusicDirectory() { passwd *pw = getpwuid(getuid()); if (!pw) throw Xcept("getpwuid failed: %s", strerror(errno)); std::filesystem::path retval(pw->pw_dir); return retval / "Music"; } const std::filesystem::path OS::GetLocalConfigDirectory() { passwd *pw = getpwuid(getuid()); if (!pw) throw Xcept("getpwuid failed: %s", strerror(errno)); std::filesystem::path retval(pw->pw_dir); return retval / ".config"; } const std::filesystem::path OS::GetGlobalConfigDirectory() { return std::filesystem::path("/etc"); } #else // Unsupported OS #error "Apparently your OS is neither Windows nor appears to be a UNIX variant (no unistd.h). You will have to add support for your OS in src/OS.cpp :/" #endif #ifdef __APPLE__ #include <libproc.h> #include <unistd.h> #include <sys/sysctl.h> // http://www.objectpark.net/en/parentpid.html #define OPProcessValueUnknown UINT_MAX static int OPParentIDForProcessID(int pid) /*" Returns the parent process id for the given process id (pid). "*/ { struct kinfo_proc info; size_t length = sizeof(struct kinfo_proc); int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }; if (sysctl(mib, 4, &info, &length, NULL, 0) < 0) return OPProcessValueUnknown; if (length == 0) return OPProcessValueUnknown; return info.kp_eproc.e_ppid; } // adapted from https://stackoverflow.com/a/8149198 /* * Attempts to check for Apple Terminal. * Apple Terminal performs hilariously bad in comparison * to iTerm2 to the point where it is almost unusable. */ void OS::CheckTerminal() { pid_t pid = getpid(); int ret; pid_t oldpid = getpid(); char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; do { ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf)); if (strncmp(pathbuf, "/Applications/Utilities/Terminal.app", 37) == 0) { std::cout << "It appears that you are using macOS's built-in Terminal.app." << std::endl << std::endl << "This terminal is prone to some serious lag with agbplay." << std::endl << "It is recommended to use iTerm2 (https://www.iterm2.com/), as it can" << std::endl << "run agbplay without any lag." << std::endl << std::endl << "Press Return to continue, or Ctrl+C to exit."; std::cin.ignore(); return; } oldpid = pid; pid = (pid_t)OPParentIDForProcessID(pid); } while (ret > 0 && pid > 1 /* launchd */ && pid != oldpid && pid != OPProcessValueUnknown); } #else void OS::CheckTerminal() { return; } #endif
4,402
C++
.cpp
126
30.468254
152
0.680556
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,641
LoudnessCalculator.cpp
ipatix_agbplay/src/LoudnessCalculator.cpp
#include <cmath> #include <cassert> #include "LoudnessCalculator.h" #include "Constants.h" #include "Util.h" LoudnessCalculator::LoudnessCalculator(const float lowpassFreq) : lpAlpha(calcAlpha(lowpassFreq)) { } void LoudnessCalculator::CalcLoudness(const sample *audio, size_t numSamples) { do { float l = audio->left; float r = audio->right; audio++; assert(!std::isnan(l) && !std::isnan(r)); assert(!std::isinf(l) && !std::isinf(r)); l *= l; r *= r; avgVolLeftSq = avgVolLeftSq + lpAlpha * (l - avgVolLeftSq); avgVolRightSq = avgVolRightSq + lpAlpha * (r - avgVolRightSq); } while (--numSamples > 0); static const float sqrt_2 = sqrtf(2.0f); volLeft = sqrtf(avgVolLeftSq) * sqrt_2; volRight = sqrtf(avgVolRightSq) * sqrt_2; } void LoudnessCalculator::GetLoudness(float& lVol, float& rVol) { lVol = volLeft; rVol = volRight; } void LoudnessCalculator::Reset() { avgVolLeftSq = 0.f; avgVolRightSq = 0.f; volLeft = 0.f; volRight = 0.f; } float LoudnessCalculator::calcAlpha(float lowpassFreq) { float rc = 1.0f / (lowpassFreq * 2.0f * float(M_PI)); float dt = 1.0f / float(STREAM_SAMPLERATE); return dt / (rc + dt); }
1,257
C++
.cpp
44
24.386364
77
0.653942
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,642
TrackviewGUI.cpp
ipatix_agbplay/src/TrackviewGUI.cpp
#include <cstring> #include <algorithm> #include <cassert> #include "Util.h" #include "TrackviewGUI.h" #include "ColorDef.h" #include "Debug.h" #include "Xcept.h" const std::vector<const char *> TrackviewGUI::noteNames = { "C-2", "C#-2", "D-2", "D#-2", "E-2", "F-2", "F#-2", "G-2", "G#-2", "A-2", "A#-2", "B-2", "C-1", "C#-1", "D-1", "D#-1", "E-1", "F-1", "F#-1", "G-1", "G#-1", "A-1", "A#-1", "B-1", "C0", "C#0", "D0", "D#0", "E0", "F0", "F#0", "G0", "G#0", "A0", "A#0", "B0", "C1", "C#1", "D1", "D#1", "E1", "F1", "F#1", "G1", "G#1", "A1", "A#1", "B1", "C2", "C#2", "D2", "D#2", "E2", "F2", "F#2", "G2", "G#2", "A2", "A#2", "B2", "C3", "C#3", "D3", "D#3", "E3", "F3", "F#3", "G3", "G#3", "A3", "A#3", "B3", "C4", "C#4", "D4", "D#4", "E4", "F4", "F#4", "G4", "G#4", "A4", "A#4", "B4", "C5", "C#5", "D5", "D#5", "E5", "F5", "F#5", "G5", "G#5", "A5", "A#5", "B5", "C6", "C#6", "D6", "D#6", "E6", "F6", "F#6", "G6", "G#6", "A6", "A#6", "B6", "C7", "C#7", "D7", "D#7", "E7", "F7", "F#7", "G7", "G#7", "A7", "A#7", "B7", "C8", "C#8", "D8", "D#8", "E8", "F8", "F#8", "G8" }; /* * public */ TrackviewGUI::TrackviewGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : CursesWin(height, width, yPos, xPos) { // will clear the screen due to not overriding from CursesWin base class cursorPos = 0; maxChannels = 0; activeChannels = 0; cursorVisible = false; update(); } TrackviewGUI::~TrackviewGUI() { } void TrackviewGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); update(); } void TrackviewGUI::SetState(const Sequence& seq, const float *vols, int activeChannels, int maxChannels) { this->activeChannels = activeChannels; if (maxChannels == -1) { this->maxChannels = std::max(this->maxChannels, this->activeChannels); } else { this->maxChannels = maxChannels; } size_t sz = seq.tracks.size(); if (disp.data.size() != sz) { disp.data.resize(sz); } for (size_t i = 0; i < sz; i++) { disp.data[i].trackPtr = uint32_t(seq.tracks[i].pos); disp.data[i].isCalling = seq.tracks[i].reptCount > 0; disp.data[i].isMuted = seq.tracks[i].muted; disp.data[i].vol = seq.tracks[i].vol; disp.data[i].mod = seq.tracks[i].mod; disp.data[i].prog = seq.tracks[i].prog; disp.data[i].pan = seq.tracks[i].pan; disp.data[i].pitch = seq.tracks[i].pitch; disp.data[i].envL = uint8_t(std::clamp<uint32_t>(uint32_t(vols[i*2 ] * 768.f), 0, 255)); disp.data[i].envR = uint8_t(std::clamp<uint32_t>(uint32_t(vols[i*2+1] * 768.f), 0, 255)); disp.data[i].delay = std::max<uint8_t>(0, static_cast<uint8_t>(seq.tracks[i].delay)); disp.data[i].activeNotes = seq.tracks[i].activeNotes; } update(); } void TrackviewGUI::SetTitle(const std::string& name) { songName = name; } void TrackviewGUI::Enter() { this->cursorVisible = true; update(); } void TrackviewGUI::Leave() { this->cursorVisible = false; update(); } void TrackviewGUI::PageDown() { for (int i = 0; i < 5; i++) { scrollDownNoUpdate(); } update(); } void TrackviewGUI::PageUp() { for (int i = 0; i < 5; i++) { scrollUpNoUpdate(); } update(); } void TrackviewGUI::ScrollDown() { scrollDownNoUpdate(); update(); } void TrackviewGUI::ScrollUp() { scrollUpNoUpdate(); update(); } /* * private Trackview */ void TrackviewGUI::update() { // init draw const uint32_t yBias = 1; const uint32_t xBias = 1; // clear field if (cursorPos >= disp.data.size() && cursorPos > 0) { cursorPos = (uint32_t)disp.data.size() - 1; } wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); for (uint32_t i = yBias + 1 + (uint32_t)disp.data.size() * 2; i < height; i++) { mvwhline(winPtr, (int)i, xBias, ' ', width - xBias); } // draw borderlines wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); mvwvline(winPtr, 1, 0, ' ', height - 1); mvwprintw(winPtr, 0, 0, "%-*s", width, " Tracker"); // draw track titlebar wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_UNDERLINE); mvwprintw(winPtr, yBias, xBias, "["); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_NUM)) | A_UNDERLINE); wprintw(winPtr, "#T"); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_UNDERLINE); wprintw(winPtr, "] "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_LOC)) | A_UNDERLINE); wprintw(winPtr, "Location "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_UNDERLINE); wprintw(winPtr, " "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_DEL)) | A_UNDERLINE); wprintw(winPtr, "Del"); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_UNDERLINE); wprintw(winPtr, " "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_NOTE)) | A_UNDERLINE); wprintw(winPtr, "Note"); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_UNDERLINE); wprintw(winPtr, " - %-*s %3d/%3d", width - 24 - 3 - 8, songName.c_str(), activeChannels, maxChannels); for (uint32_t i = 0, th = 0; i < disp.data.size(); i++, th += 2) { int aFlag = (cursorVisible && i == cursorPos) ? A_REVERSE : 0; // print tickbox and first line wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, (int)(yBias + 1 + th), xBias, "["); wattrset(winPtr, COLOR_PAIR(static_cast<int>(disp.data[i].isMuted ? Color::TRK_NUM_MUTED : Color::TRK_NUM)) | aFlag); wprintw(winPtr, "%02d", i); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); wprintw(winPtr, "] "); wattrset(winPtr, (disp.data[i].isCalling ? COLOR_PAIR(static_cast<int>(Color::TRK_LOC_CALL)) : COLOR_PAIR(static_cast<int>(Color::TRK_LOC)))); wprintw(winPtr, "0x%07X", disp.data[i].trackPtr); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); wprintw(winPtr, " "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_DEL))); wprintw(winPtr, "W%02d", disp.data[i].delay); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); wprintw(winPtr, " "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_NOTE))); // print notes #define DECIDE_COL_C(a, b)\ !a && !b ? static_cast<int>(Color::TRK_FGB_BGCW) :\ !a && b ? static_cast<int>(Color::TRK_FGC_BGCW) :\ a && !b ? static_cast<int>(Color::TRK_FGB_BGC) :\ static_cast<int>(Color::TRK_FGC_BGC) #define DECIDE_COL_D(a, b)\ !a && !b ? static_cast<int>(Color::TRK_FGB_BGW) :\ !a && b ? static_cast<int>(Color::TRK_FGC_BGW) :\ a && !b ? static_cast<int>(Color::TRK_FGB_BGC) :\ static_cast<int>(Color::TRK_FGC_BGC) #define DECIDE_COL_E(a, b)\ !a && !b ? static_cast<int>(Color::TRK_FGW_BGW) :\ !a && b ? static_cast<int>(Color::TRK_FGEC_BGW) :\ a && !b ? static_cast<int>(Color::TRK_FGW_BGC) :\ static_cast<int>(Color::TRK_FGEC_BGC) for (size_t j = 0;; j++) { // C and C# wattrset(winPtr, COLOR_PAIR(DECIDE_COL_C( disp.data[i].activeNotes[j*12+0], disp.data[i].activeNotes[j*12+1]))); waddstr(winPtr, "\u259D"); // D and D# wattrset(winPtr, COLOR_PAIR(DECIDE_COL_D( disp.data[i].activeNotes[j*12+2], disp.data[i].activeNotes[j*12+3]))); waddstr(winPtr, "\u259D"); // E and F wattrset(winPtr, COLOR_PAIR(DECIDE_COL_E( disp.data[i].activeNotes[j*12+4], disp.data[i].activeNotes[j*12+5]))); waddstr(winPtr, "\u2590"); // F# and G wattrset(winPtr, COLOR_PAIR(DECIDE_COL_D( disp.data[i].activeNotes[j*12+7], disp.data[i].activeNotes[j*12+6]))); waddstr(winPtr, "\u2598"); // keys only go up to key 127, this is the breakout point if (j == 10) break; // G# and A wattrset(winPtr, COLOR_PAIR(DECIDE_COL_D( disp.data[i].activeNotes[j*12+9], disp.data[i].activeNotes[j*12+8]))); waddstr(winPtr, "\u2598"); // A# and B wattrset(winPtr, COLOR_PAIR(DECIDE_COL_D( disp.data[i].activeNotes[j*12+11], disp.data[i].activeNotes[j*12+10]))); waddstr(winPtr, "\u2598"); } #undef DECIDE_COL_C #undef DECIDE_COL_D #undef DECIDE_COL_E // FIXME //char noteBuffer[width + 1]; //size_t noteBufferIndex = 0; //for (size_t j = 0; j < disp.data[i].activeNotes.size(); j++) { //if (disp.data[i].activeNotes[j]) { //CStrAppend(noteBuffer, &noteBufferIndex, noteNames[j]); //noteBuffer[noteBufferIndex++] = ' '; //} //} //if (width < 20) { //noteBuffer[0] = '\0'; //} else if (noteBufferIndex > width - 20) { //noteBuffer[width - 20] = '\0'; //} else { //size_t leftChars = width - 20 - noteBufferIndex; //for (size_t j = 0; j < leftChars; j++) //noteBuffer[noteBufferIndex++] = ' '; //noteBuffer[noteBufferIndex++] = '\0'; //} //wprintw(winPtr, "%s", noteBuffer); // FIXME // print track values and sencond line wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, (int)(yBias + 2 + th), xBias, " "); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_VOICE))); if (disp.data[i].prog == PROG_UNDEFINED) { wprintw(winPtr, "---"); } else { wprintw(winPtr, "%-3d", disp.data[i].prog); } wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_PAN))); wprintw(winPtr, " %-+3d", disp.data[i].pan); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_VOL))); wprintw(winPtr, " %-3d", disp.data[i].vol); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_MOD))); wprintw(winPtr, " %-3d", disp.data[i].mod); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_PITCH))); wprintw(winPtr, " %-+6d", disp.data[i].pitch); // print volume level static const char *fracBar[] = { " ", "\u258f", "\u258e", "\u258d", "\u258c", "\u258b", "\u258a", "\u2589", "\u2588" }; auto printBar16 = [](char *buffer, int level) { assert(level <= 128 && level >= 0); for (size_t i = 0; i < 16; i++) { char ch; const char *part; if (level > 8) { part = fracBar[8]; while ((ch = *part++) != '\0') *buffer++ = ch; level -= 8; } else if (level > 0) { part = fracBar[level]; while ((ch = *part++) != '\0') *buffer++ = ch; level -= 8; } else { part = fracBar[0]; while ((ch = *part++) != '\0') *buffer++ = ch; } } *buffer = '\0'; return; }; // should be big enough for 16 unicode block bars char bar[16 * strlen("\u2688") + 1]; uint32_t leftBar = disp.data[i].envL / 2; uint32_t rightBar = disp.data[i].envR / 2; printBar16(bar, 128 - leftBar); wattrset(winPtr, COLOR_PAIR(static_cast<int>(!disp.data[i].isMuted ? Color::TRK_LOUDNESS : Color::TRK_LOUDNESS_MUTED)) | A_REVERSE); wprintw(winPtr, "%s", bar); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::TRK_LOUDNESS))); wprintw(winPtr, "\u2503"); printBar16(bar, rightBar); wattrset(winPtr, COLOR_PAIR(static_cast<int>(!disp.data[i].isMuted ? Color::TRK_LOUDNESS : Color::TRK_LOUDNESS_MUTED))); wprintw(winPtr, "%s", bar); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); whline(winPtr, ' ', width - 60); } wrefresh(winPtr); } void TrackviewGUI::scrollDownNoUpdate() { if (cursorPos + 1 < disp.data.size()) cursorPos++; } void TrackviewGUI::scrollUpNoUpdate() { if (cursorPos > 0) cursorPos--; } void TrackviewGUI::ForceUpdate() { update(); }
12,915
C++
.cpp
316
32.658228
150
0.539546
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,643
ReverbEffect.cpp
ipatix_agbplay/src/ReverbEffect.cpp
#include <algorithm> #include <cassert> #include "ReverbEffect.h" #include "Debug.h" #include "Util.h" #include "Constants.h" /* * public ReverbEffect */ ReverbEffect::ReverbEffect(uint8_t intensity, size_t streamRate, uint8_t numAgbBuffers) : reverbBuffer((streamRate / AGB_FPS) * numAgbBuffers, sample{0.0f, 0.0f}) { this->intensity = intensity / 128.0f; size_t bufferLen = streamRate / AGB_FPS; bufferPos = 0; bufferPos2 = bufferLen; } ReverbEffect::~ReverbEffect() { } void ReverbEffect::ProcessData(sample *buffer, size_t numSamples) { while (numSamples > 0) { size_t left = processInternal(buffer, numSamples); buffer += (numSamples - left); numSamples = left; } } /* * protected ReverbEffect */ size_t ReverbEffect::getBlocksPerBuffer() const { return reverbBuffer.size(); } size_t ReverbEffect::processInternal(sample *buffer, size_t numSamples) { assert(numSamples > 0); std::vector<sample>& rbuf = reverbBuffer; size_t count = std::min(std::min(getBlocksPerBuffer() - bufferPos2, getBlocksPerBuffer() - bufferPos), numSamples); bool reset = false, reset2 = false; if (getBlocksPerBuffer() - bufferPos == count) { reset = true; } if (getBlocksPerBuffer() - bufferPos2 == count) { reset2 = true; } size_t c = count; do { float rev = (rbuf[bufferPos].left + rbuf[bufferPos].right + rbuf[bufferPos2].left + rbuf[bufferPos2].right) * intensity * (1.0f / 4.0f); rbuf[bufferPos].left = buffer->left += rev; rbuf[bufferPos].right = buffer->right += rev; buffer++; bufferPos++; bufferPos2++; } while (--c > 0); if (reset2) bufferPos2 = 0; if (reset) bufferPos = 0; return numSamples - count; } /* * ReverbGS1 */ ReverbGS1::ReverbGS1(uint8_t intensity, size_t streamRate, uint8_t numAgbBuffers) : ReverbEffect(intensity, streamRate, numAgbBuffers), gsBuffer((streamRate / AGB_FPS), sample{0.0f, 0.0f}) { bufferPos2 = 0; } ReverbGS1::~ReverbGS1() { } size_t ReverbGS1::getBlocksPerGsBuffer() const { return gsBuffer.size(); } size_t ReverbGS1::processInternal(sample *buffer, size_t numSamples) { std::vector<sample>& rbuf = reverbBuffer; const size_t bPerBuf = getBlocksPerBuffer(); const size_t bPerGsBuf = getBlocksPerGsBuffer(); size_t count = std::min(std::min(bPerBuf - bufferPos, bPerGsBuf - bufferPos2), numSamples); bool reset = false, resetGS = false; if (count == bPerBuf - bufferPos) reset = true; if (count == bPerGsBuf - bufferPos2) resetGS = true; size_t c = count; do { float mixL = buffer->left + gsBuffer[bufferPos2].left; float mixR = buffer->right + gsBuffer[bufferPos2].right; float lA = rbuf[bufferPos].left; float rA = rbuf[bufferPos].right; buffer->left = rbuf[bufferPos].left = mixL; buffer->right = rbuf[bufferPos].right = mixR; float lRMix = 0.25f * mixL + 0.25f * rA; float rRMix = 0.25f * mixR + 0.25f * lA; gsBuffer[bufferPos2].left = lRMix; gsBuffer[bufferPos2].right = rRMix; buffer++; bufferPos++; bufferPos2++; } while (--c > 0); if (resetGS) bufferPos2 = 0; if (reset) bufferPos = 0; return numSamples - count; } /* * ReverbGS2 */ ReverbGS2::ReverbGS2(uint8_t intensity, size_t streamRate, uint8_t numAgbBuffers, float rPrimFac, float rSecFac) : ReverbEffect(intensity, streamRate, numAgbBuffers), gs2Buffer(streamRate / AGB_FPS, sample{0.0f, 0.0f}) { // equivalent to the offset of -0xB0 samples for a 0x210 buffer size bufferPos2 = getBlocksPerBuffer() - (gs2Buffer.size() / 3); gs2Pos = 0; this->rPrimFac = rPrimFac; this->rSecFac = rSecFac; } ReverbGS2::~ReverbGS2() { } size_t ReverbGS2::processInternal(sample *buffer, size_t numSamples) { assert(numSamples > 0); std::vector<sample>& rbuf = reverbBuffer; size_t count = std::min( std::min(getBlocksPerBuffer() - bufferPos2, getBlocksPerBuffer() - bufferPos), std::min(numSamples, gs2Buffer.size() - gs2Pos) ); bool reset = false, reset2 = false, resetgs2 = false; if (getBlocksPerBuffer() - bufferPos2 == count) { reset2 = true; } if (getBlocksPerBuffer() - bufferPos == count) { reset = true; } if ((gs2Buffer.size() / 2) - gs2Pos == count) { resetgs2 = true; } size_t c = count; do { float mixL = buffer->left + gs2Buffer[gs2Pos].left; float mixR = buffer->right + gs2Buffer[gs2Pos].right; float lA = rbuf[bufferPos].left; float rA = rbuf[bufferPos].right; buffer->left = rbuf[bufferPos].left = mixL; buffer->right = rbuf[bufferPos].right = mixR; float lRMix = lA * rPrimFac + rA * rSecFac; float rRMix = rA * rPrimFac + lA * rSecFac; float lB = rbuf[bufferPos2].right * 0.25f; float rB = mixR * 0.25f; gs2Buffer[gs2Pos].left = lRMix + lB; gs2Buffer[gs2Pos].right = rRMix + rB; buffer++; bufferPos++; bufferPos2++; gs2Pos++; } while (--c > 0); if (reset2) bufferPos2 = 0; if (reset) bufferPos = 0; if (resetgs2) gs2Pos = 0; return numSamples - count; } /* * ReverbTest */ ReverbTest::ReverbTest(uint8_t intensity, size_t streamRate, uint8_t numAgbBuffers) : ReverbEffect(intensity, streamRate, numAgbBuffers) { } ReverbTest::~ReverbTest() { } size_t ReverbTest::processInternal(sample *buffer, size_t numSamples) { assert(numSamples > 0); std::vector<sample>& rbuf = reverbBuffer; size_t count = std::min(std::min(getBlocksPerBuffer() - bufferPos, getBlocksPerBuffer() - bufferPos2), numSamples); bool reset = false, reset2 = false; if (getBlocksPerBuffer() - bufferPos2 == count) { reset2 = true; } if (getBlocksPerBuffer() - bufferPos == count) { reset = true; } size_t c = count; do { const float g = 0.8f; float input_l = buffer->left; float input_r = buffer->right; float feedback_l = rbuf[bufferPos].left; float feedback_r = rbuf[bufferPos].right; float new_feedback_l = input_l + g * feedback_l; float new_feedback_r = input_r + g * feedback_r; float output_l = -g * new_feedback_l + feedback_l; float output_r = -g * new_feedback_r + feedback_r; buffer->left = output_l; buffer->right = output_r; buffer++; rbuf[bufferPos].left = -new_feedback_l; rbuf[bufferPos].right = -new_feedback_r; /* float in_delay_1_l = rbuf[bufferPos * 2], in_delay_1_r = rbuf[bufferPos * 2 + 1]; float in_delay_2_l = rbuf[bufferPos2 * 2], in_delay_2_r = rbuf[bufferPos2 * 2 + 1]; delay1HPcarryL = (in_delay_1_l + delay1HPcarryL - delay1HPprevL) * 0.95f; delay1HPcarryR = (in_delay_1_r + delay1HPcarryR - delay1HPprevR) * 0.95f; delay2HPcarryL = (in_delay_2_l + delay2HPcarryL - delay2HPprevL) * 0.95f; delay2HPcarryR = (in_delay_2_r + delay2HPcarryR - delay2HPprevR) * 0.95f; delay1HPprevL = in_delay_1_l; delay1HPprevR = in_delay_1_r; delay2HPprevL = in_delay_2_l; delay2HPprevR = in_delay_2_r; in_delay_1_l = delay1HPcarryL; in_delay_1_r = delay1HPcarryR; in_delay_2_l = delay2HPcarryL; in_delay_2_r = delay2HPcarryR; float r_left = in_delay_1_r * (4.0f / 8.0f) + in_delay_2_l * (4.0f / 8.0f); float r_right = -in_delay_1_l * (4.0f / 8.0f) - in_delay_2_r * (4.0f / 8.0f); rbuf[bufferPos * 2] = *buffer++ += r_left; rbuf[bufferPos * 2 + 1] = *buffer++ += r_right; */ bufferPos++; bufferPos2++; } while (--c > 0); if (reset2) bufferPos2 = 0; if (reset) bufferPos = 0; return numSamples - count; }
8,050
C++
.cpp
233
28.55794
119
0.622248
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,644
SonglistGUI.cpp
ipatix_agbplay/src/SonglistGUI.cpp
#include "SonglistGUI.h" #include "Xcept.h" #include "ColorDef.h" #include "Debug.h" #include <cstring> #include <string> #include <vector> #include <algorithm> /* * -- public -- */ SonglistGUI::SonglistGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos, bool upd) : CursesWin(height, width, yPos, xPos) { checkDimensions(height, width); this->viewPos = 0; this->cursorPos = 0; this->cursorVisible = false; this->contentHeight = height - 1; this->contentWidth = width; if (upd) update(); } SonglistGUI::~SonglistGUI() { } void SonglistGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { checkDimensions(height, width); CursesWin::Resize(height, width, yPos, xPos); this->contentHeight = height - 1; this->contentWidth = width; update(); } void SonglistGUI::Enter() { cursorVisible = true; update(); } void SonglistGUI::Leave() { cursorVisible = false; update(); } void SonglistGUI::ScrollDown() { scrollDownNoUpdate(); update(); } void SonglistGUI::ScrollUp() { scrollUpNoUpdate(); update(); } void SonglistGUI::PageDown() { for (uint32_t i = 0; i < contentHeight; i++) { scrollDownNoUpdate(); } update(); } void SonglistGUI::PageUp() { for (uint32_t i = 0; i < contentHeight; i++) { scrollUpNoUpdate(); } update(); } bool SonglistGUI::IsLast() const { if (cursorPos + 1 >= songlist.size()) return true; return false; } void SonglistGUI::AddSong(SongEntry entry) { songlist.push_back(entry); update(); } void SonglistGUI::ClearSongs() { viewPos = 0; cursorPos = 0; songlist.clear(); update(); } void SonglistGUI::RemoveSong() { if (songlist.size() == 0) return; songlist.erase(songlist.begin() + cursorPos); if (cursorPos != 0 && cursorPos >= songlist.size()) { cursorPos--; } update(); } SongEntry *SonglistGUI::GetSong() { if (cursorPos >= songlist.size()) return nullptr; return &songlist[cursorPos]; } /* * -- private -- */ void SonglistGUI::scrollDownNoUpdate() { // return if bounds are reached if (cursorPos + 1 >= songlist.size()) return; cursorPos++; /* move viewport down of the cursor is in the lower area * and the screen may be scrolled down */ if (viewPos + contentHeight < songlist.size() && cursorPos > viewPos + contentHeight - 5) viewPos++; } void SonglistGUI::scrollUpNoUpdate() { // return if bounds are reached if (cursorPos == 0) return; cursorPos--; if (viewPos > 0 && cursorPos < viewPos + 4) viewPos--; } void SonglistGUI::update() { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); mvwprintw(winPtr, 0, 0, "%-*.*s", contentWidth, contentWidth, "Songlist:"); for (uint32_t i = 0; i < contentHeight; i++) { if (i + viewPos == cursorPos && cursorVisible) wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::LIST_ENTRY)) | A_REVERSE); else wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::LIST_ENTRY))); // generate list of songs if (i + viewPos < songlist.size()) { mvwprintw(winPtr, (int)(height - contentHeight + (uint32_t)i), 0, "%-*.*s", width, width, songlist[i + viewPos].name.c_str()); } else { mvwprintw(winPtr, (int)(height - contentHeight + (uint32_t)i), 0, "%-*.*s", width, width, ""); } } wrefresh(winPtr); } void SonglistGUI::checkDimensions(uint32_t height, uint32_t width) { if (height <= 1) throw Xcept("Songlist GUI height must not be 0"); if (width < 5) throw Xcept("Songlist GUI width must be wider than 5"); }
3,842
C++
.cpp
152
20.894737
98
0.628338
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,645
CursesWin.cpp
ipatix_agbplay/src/CursesWin.cpp
#include <cstdint> #include <iostream> #include <cstdlib> #include "ColorDef.h" #include "CursesWin.h" #include "Xcept.h" CursesWin::CursesWin(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { if ((winPtr = newwin((int)height, (int)width, (int)yPos, (int)xPos)) == nullptr) { throw Xcept("Error while creating curses window [newwin]"); } this->height = height; this->width = width; } CursesWin::~CursesWin() { if (delwin(winPtr) == ERR) { //throw Xcept("Error while deleteing curses window [delwin]"); std::cerr << "FATAL ERROR: deleting window of curses window failed" << std::endl; abort(); } } void CursesWin::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { if (delwin(winPtr) == ERR) { throw Xcept("Error while resizing curses window [delwin]"); } this->height = height; this->width = width; if ((winPtr = newwin((int)height, (int)width, (int)yPos, (int)xPos)) == nullptr) { throw Xcept("Error while resizing curses window [newwin]"); } } void CursesWin::update() { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); wclear(winPtr); }
1,208
C++
.cpp
35
30.171429
89
0.652397
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,646
SequenceReader.cpp
ipatix_agbplay/src/SequenceReader.cpp
#include <cmath> #include <cassert> #include "SequenceReader.h" #include "Xcept.h" #include "Util.h" #include "Debug.h" #include "Rom.h" #include "PlayerContext.h" #include "ConfigManager.h" #define NOTE_TIE -1 #define NOTE_ALL 0xFE #define LOOP_ENDLESS -1 /* * SequenceReader data */ const std::vector<uint32_t> SequenceReader::freqLut = { 5734, 7884, 10512, 13379, 15768, 18157, 21024, 26758, 31536, 36314, 40137, 42048 }; const std::map<uint8_t, int8_t> SequenceReader::delayLut = { {0x80,0 }, {0x81,1 }, {0x82,2 }, {0x83,3 }, {0x84,4 }, {0x85,5 }, {0x86,6 }, {0x87,7 }, {0x88,8 }, {0x89,9 }, {0x8A,10}, {0x8B,11}, {0x8C,12}, {0x8D,13}, {0x8E,14}, {0x8F,15}, {0x90,16}, {0x91,17}, {0x92,18}, {0x93,19}, {0x94,20}, {0x95,21}, {0x96,22}, {0x97,23}, {0x98,24}, {0x99,28}, {0x9A,30}, {0x9B,32}, {0x9C,36}, {0x9D,40}, {0x9E,42}, {0x9F,44}, {0xA0,48}, {0xA1,52}, {0xA2,54}, {0xA3,56}, {0xA4,60}, {0xA5,64}, {0xA6,66}, {0xA7,68}, {0xA8,72}, {0xA9,76}, {0xAA,78}, {0xAB,80}, {0xAC,84}, {0xAD,88}, {0xAE,90}, {0xAF,92}, {0xB0,96} }; const std::map<uint8_t, int8_t> SequenceReader::noteLut = { {0xCF,0 }, {0xD0,1 }, {0xD1,2 }, {0xD2,3 }, {0xD3,4 }, {0xD4,5 }, {0xD5,6 }, {0xD6,7 }, {0xD7,8 }, {0xD8,9 }, {0xD9,10}, {0xDA,11}, {0xDB,12}, {0xDC,13}, {0xDD,14}, {0xDE,15}, {0xDF,16}, {0xE0,17}, {0xE1,18}, {0xE2,19}, {0xE3,20}, {0xE4,21}, {0xE5,22}, {0xE6,23}, {0xE7,24}, {0xE8,28}, {0xE9,30}, {0xEA,32}, {0xEB,36}, {0xEC,40}, {0xED,42}, {0xEE,44}, {0xEF,48}, {0xF0,52}, {0xF1,54}, {0xF2,56}, {0xF3,60}, {0xF4,64}, {0xF5,66}, {0xF6,68}, {0xF7,72}, {0xF8,76}, {0xF9,78}, {0xFA,80}, {0xFB,84}, {0xFC,88}, {0xFD,90}, {0xFE,92}, {0xFF,96} }; /* * public SequenceReader */ SequenceReader::SequenceReader(PlayerContext& ctx, int8_t maxLoops) : ctx(ctx), maxLoops(maxLoops) { } void SequenceReader::Process() { ctx.seq.bpmStack += uint32_t(float(ctx.seq.bpm) * speedFactor); while (ctx.seq.bpmStack >= BPM_PER_FRAME * INTERFRAMES) { processSequenceTick(); ctx.seq.bpmStack -= BPM_PER_FRAME * INTERFRAMES; } } bool SequenceReader::EndReached() const { return endReached; } void SequenceReader::Restart() { numLoops = 0; endReached = false; } void SequenceReader::SetSpeedFactor(float speedFactor) { this->speedFactor = speedFactor; } /* * private SequenceReader */ void SequenceReader::processSequenceTick() { Rom& rom = Rom::Instance(); // process all tracks bool isSongRunning = false; int itrk = -1; for (Track& trk : ctx.seq.tracks) { itrk += 1; const uint8_t trackIdx = static_cast<uint8_t>(itrk); if (!trk.isRunning) continue; isSongRunning = true; tickTrackNotes(uint8_t(itrk), trk.activeNotes); // count down last delay and process while (trk.isRunning && trk.delay == 0) { uint8_t cmd = rom.ReadU8(trk.pos); // check if a previous command should be repeated if (cmd < 0x80) { cmd = trk.lastCmd; if (cmd < 0x80) { // song data error, command not initialized cmdPlayFine(trackIdx); break; } } else { trk.pos++; if (cmd >= 0xBD) { // repeatable command trk.lastCmd = cmd; } } if (cmd >= 0xCF) { // note command cmdPlayNote(cmd, trackIdx); } else if (cmd >= 0xB1) { // state altering command cmdPlayCommand(cmd, trackIdx); } else { trk.delay = delayLut.at(cmd); } } // end of processing loop if (trk.isRunning) trk.delay--; if (trk.lfos != 0 && trk.mod != 0) { if (trk.lfodlCount == 0) { trk.lfoPhase += trk.lfos; int lfoPoint; if (static_cast<int8_t>(trk.lfoPhase - 64) >= 0) lfoPoint = 128 - trk.lfoPhase; else lfoPoint = static_cast<int8_t>(trk.lfoPhase); lfoPoint *= trk.mod; lfoPoint >>= 6; if (trk.lfoValue != lfoPoint) { trk.lfoValue = static_cast<int8_t>(lfoPoint); if (trk.modt == MODT::PITCH) trk.updatePitch = true; else trk.updateVolume = true; } } else { trk.lfodlCount--; } } // TODO actually only update one or there other and not always both if (trk.updateVolume || trk.updatePitch || trk.mod > 0) { setTrackPV(trackIdx, trk.GetVol(), trk.GetPan(), trk.pitch = trk.GetPitch(), trk.updateVolume, trk.updatePitch); trk.updateVolume = false; trk.updatePitch = false; } else { trk.pitch = trk.GetPitch(); } } if (!isSongRunning && !endReached) { ctx.mixer.StartFadeOut(SONG_FINISH_TIME); endReached = true; } ctx.seq.tickCount++; } int SequenceReader::tickTrackNotes(uint8_t track_idx, std::bitset<NUM_NOTES>& activeNotes) { std::bitset<128> backBuffer; int active = 0; auto tickFunc = [&](auto& channels) { for (auto& chn : channels) { if (chn.GetTrackIdx() == track_idx) { if (chn.TickNote()) { active++; backBuffer[chn.GetNote().midiKeyTrackData % 128] = true; } } } }; tickFunc(ctx.sndChannels); tickFunc(ctx.sq1Channels); tickFunc(ctx.sq2Channels); tickFunc(ctx.waveChannels); tickFunc(ctx.noiseChannels); activeNotes = backBuffer; return active; } void SequenceReader::setTrackPV(uint8_t track_idx, uint16_t vol, int16_t pan, int16_t pitch, bool updateVolume, bool updatePitch) { auto setFunc = [&](auto& channels) { for (auto& chn : channels) { if (chn.GetTrackIdx() == track_idx) { if (updateVolume) chn.SetVol(vol, pan); if (updatePitch) chn.SetPitch(pitch); } } }; setFunc(ctx.sndChannels); setFunc(ctx.sq1Channels); setFunc(ctx.sq2Channels); setFunc(ctx.waveChannels); setFunc(ctx.noiseChannels); } void SequenceReader::cmdPlayNote(uint8_t cmd, uint8_t trackIdx) { Rom& rom = Rom::Instance(); Track& trk = ctx.seq.tracks[trackIdx]; trk.lastNoteLen = noteLut.at(cmd); // parse command from track data if (rom.ReadU8(trk.pos) < 0x80) { trk.lastNoteKey = rom.ReadU8(trk.pos++); if (rom.ReadU8(trk.pos) < 0x80) { trk.lastNoteVel = rom.ReadU8(trk.pos++); if (rom.ReadU8(trk.pos) < 0x80) { trk.lastNoteLen += rom.ReadU8(trk.pos++); } } } // don't play invalid instruments if (trk.prog > 127) return; trk.lfodlCount = trk.lfodl; if (trk.lfodl != 0) trk.ResetLfoValue(); // initialize note data Note note; note.length = trk.lastNoteLen; note.midiKeyTrackData = trk.lastNoteKey; note.midiKeyPitch = ctx.bnk.GetMidiKey(trk.prog, trk.lastNoteKey); note.velocity = trk.lastNoteVel; note.priority = trk.priority; note.rhythmPan = ctx.bnk.GetPan(trk.prog, trk.lastNoteKey) * 2; note.pseudoEchoVol = trk.pseudoEchoVol; note.pseudoEchoLen = trk.pseudoEchoLen; note.trackIdx = trackIdx; // prepare cgb polyphony suppression const ConfigManager& cm = ConfigManager::Instance(); CGBPolyphony cgbPolyphony = cm.GetCgbPolyphony(); auto cgbPolyphonySuppressFunc = [&](auto& channels) { // return 'true' if a note is allowed to play, 'false' if others with higher priority are playing if (cgbPolyphony == CGBPolyphony::MONO_STRICT) { // only one tone should play in mono strict mode assert(channels.size() <= 1); if (channels.size() > 0) { const Note& playing_note = channels.front().GetNote(); if (!channels.front().IsReleasing()) { if (playing_note.priority > note.priority) return false; if (playing_note.priority == note.priority) { if (channels.front().GetTrackIdx() < trackIdx) return false; } } } channels.clear(); } else if (cgbPolyphony == CGBPolyphony::MONO_SMOOTH) { for (auto& chn : channels) { if (chn.GetState() < EnvState::PSEUDO_ECHO && !chn.IsFastReleasing()) { const Note& playing_note = chn.GetNote(); if (playing_note.priority > note.priority) return false; if (playing_note.priority == note.priority) { if (chn.GetTrackIdx() < trackIdx) return false; } } chn.Release(true); } } return true; }; // enqueue actual note switch (ctx.bnk.GetInstrType(trk.prog, trk.lastNoteKey)) { case InstrType::PCM: ctx.sndChannels.emplace_back( ctx.bnk.GetSampInfo(trk.prog, trk.lastNoteKey), ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note, false); break; case InstrType::PCM_FIXED: ctx.sndChannels.emplace_back( ctx.bnk.GetSampInfo(trk.prog, trk.lastNoteKey), ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note, true); break; case InstrType::SQ1: if (!cgbPolyphonySuppressFunc(ctx.sq1Channels)) return; ctx.sq1Channels.emplace_back( ctx.bnk.GetCGBDef(trk.prog, trk.lastNoteKey).wd, ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note, ctx.bnk.GetSweep(trk.prog, trk.lastNoteKey)); break; case InstrType::SQ2: if (!cgbPolyphonySuppressFunc(ctx.sq2Channels)) return; ctx.sq2Channels.emplace_back( ctx.bnk.GetCGBDef(trk.prog, trk.lastNoteKey).wd, ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note, 0); break; case InstrType::WAVE: if (!cgbPolyphonySuppressFunc(ctx.waveChannels)) return; ctx.waveChannels.emplace_back( ctx.bnk.GetCGBDef(trk.prog, trk.lastNoteKey).wavePtr, ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note, cm.GetCfg().GetAccurateCh3Volume()); break; case InstrType::NOISE: if (!cgbPolyphonySuppressFunc(ctx.noiseChannels)) return; ctx.noiseChannels.emplace_back( ctx.bnk.GetCGBDef(trk.prog, trk.lastNoteKey).np, ctx.bnk.GetADSR(trk.prog, trk.lastNoteKey), note); break; case InstrType::INVALID: return; } // new notes need correct pitch and volume applied trk.updateVolume = true; trk.updatePitch = true; } void SequenceReader::cmdPlayCommand(uint8_t cmd, uint8_t trackIdx) { Rom& rom = Rom::Instance(); Track& trk = ctx.seq.tracks[trackIdx]; switch (cmd) { case 0xB1: // FINE cmdPlayFine(trackIdx); break; case 0xB2: // GOTO if (trackIdx == 0) { // handle agbplay's internal loop counter if (maxLoops != LOOP_ENDLESS && numLoops++ >= maxLoops && !endReached) { endReached = true; ctx.mixer.StartFadeOut(SONG_FADE_OUT_TIME); } } trk.pos = rom.ReadAgbPtrToPos(trk.pos); break; case 0xB3: // PATT if (trk.patternLevel >= TRACK_CALL_STACK_SIZE) { cmdPlayFine(trackIdx); break; } trk.returnPos[trk.patternLevel++] = trk.pos + 4; trk.pos = rom.ReadAgbPtrToPos(trk.pos); break; case 0xB4: // PEND if (trk.patternLevel == 0) break; trk.pos = trk.returnPos[--trk.patternLevel]; break; case 0xB5: // REPT { uint8_t count = rom.ReadU8(trk.pos++); if (count == 0) { cmdPlayFine(trackIdx); break; } if (++trk.reptCount < count) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); } else { trk.reptCount = 0; trk.pos += 4; } } break; case 0xB9: // MEMACC cmdPlayMemacc(trackIdx); break; case 0xBA: // PRIO trk.priority = rom.ReadU8(trk.pos++); break; case 0xBB: // TEMPO ctx.seq.bpm = static_cast<uint16_t>(rom.ReadU8(trk.pos++) * 2); break; case 0xBC: // KEYSH trk.keyShift = rom.ReadS8(trk.pos++); break; case 0xBD: // VOICE trk.prog = rom.ReadU8(trk.pos++); break; case 0xBE: // VOL trk.vol = rom.ReadU8(trk.pos++); trk.updateVolume = true; break; case 0xBF: // PAN trk.pan = static_cast<int8_t>(rom.ReadS8(trk.pos++) - 0x40); trk.updateVolume = true; break; case 0xC0: // BEND trk.bend = static_cast<int8_t>(rom.ReadS8(trk.pos++) - 0x40); trk.updatePitch = true; break; case 0xC1: // BENDR trk.bendr = rom.ReadU8(trk.pos++); trk.updatePitch = true; break; case 0xC2: // LFOS trk.lfos = rom.ReadU8(trk.pos++); if (trk.lfos == 0) trk.ResetLfoValue(); break; case 0xC3: // LFODL trk.lfodlCount = trk.lfodl = rom.ReadU8(trk.pos++); break; case 0xC4: // MOD trk.mod = rom.ReadU8(trk.pos++); if (trk.mod == 0) trk.ResetLfoValue(); break; case 0xC5: // MODT { uint8_t modt = rom.ReadU8(trk.pos++); if (static_cast<MODT>(modt) == trk.modt) return; trk.modt = static_cast<MODT>(modt); trk.updateVolume = true; trk.updatePitch = true; } break; case 0xC8: // TUNE trk.tune = static_cast<int8_t>(rom.ReadS8(trk.pos++) - 0x40); trk.updatePitch = true; break; case 0xCD: // xCMD cmdPlayXCmd(trackIdx); break; case 0xCE: // EOT { uint8_t key = rom.ReadU8(trk.pos); if (key >= 0x80) { key = trk.lastNoteKey; } else { trk.pos++; trk.lastNoteKey = key; } auto stopFunc = [&](auto& channels) { for (auto& chn : channels) { if (chn.GetTrackIdx() == trackIdx && chn.GetNote().midiKeyTrackData == key) { chn.Release(); break; } } }; stopFunc(ctx.sndChannels); stopFunc(ctx.sq1Channels); stopFunc(ctx.sq2Channels); stopFunc(ctx.waveChannels); stopFunc(ctx.noiseChannels); } break; default: cmdPlayFine(trackIdx); break; } } void SequenceReader::cmdPlayFine(uint8_t trackIdx) { auto stopFunc = [&](auto& channels) { for (auto& chn : channels) { if (chn.GetTrackIdx() == trackIdx) chn.Release(); } }; stopFunc(ctx.sndChannels); stopFunc(ctx.sq1Channels); stopFunc(ctx.sq2Channels); stopFunc(ctx.waveChannels); stopFunc(ctx.noiseChannels); ctx.seq.tracks[trackIdx].isRunning = false; } void SequenceReader::cmdPlayMemacc(uint8_t trackIdx) { Rom& rom = Rom::Instance(); Track& trk = ctx.seq.tracks[trackIdx]; uint8_t op = rom.ReadU8(trk.pos++); uint8_t& memory = ctx.seq.memaccArea[rom.ReadU8(trk.pos++)]; uint8_t data = rom.ReadU8(trk.pos++); switch (op) { case 0: memory = data; return; case 1: memory += data; return; case 2: memory -= data; return; case 3: memory = ctx.seq.memaccArea[data]; return; case 4: memory += ctx.seq.memaccArea[data]; return; case 5: memory -= ctx.seq.memaccArea[data]; return; case 6: if (memory == data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 7: if (memory != data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 8: if (memory > data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 9: if (memory >= data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 10: if (memory <= data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 11: if (memory < data) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 12: if (memory == ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 13: if (memory != ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 14: if (memory > ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 15: if (memory >= ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 16: if (memory <= ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; case 17: if (memory < ctx.seq.memaccArea[data]) { trk.pos = rom.ReadAgbPtrToPos(trk.pos); return; } break; default: return; } // only "false" jump commands should come by here trk.pos += 4; } void SequenceReader::cmdPlayXCmd(uint8_t trackIdx) { Rom& rom = Rom::Instance(); Track& trk = ctx.seq.tracks[trackIdx]; uint8_t xCmdNo = rom.ReadU8(trk.pos++); switch (xCmdNo) { case 0: // XXX cmdPlayFine(trackIdx); break; case 1: // XWAVE (stub) trk.pos += 4; break; case 2: // XTYPE (stub) trk.pos++; break; case 3: // XXX cmdPlayFine(trackIdx); break; case 4: // XATTA (stub) trk.pos++; break; case 5: // XDECA (stub) trk.pos++; break; case 6: // XSUST (stub) trk.pos++; break; case 7: // XRELA (stub) trk.pos++; break; case 8: // XIECV trk.pseudoEchoVol = rom.ReadU8(trk.pos++); break; case 9: // XIECL trk.pseudoEchoLen = rom.ReadU8(trk.pos++); break; case 10: // XLENG (stub) trk.pos++; break; case 11: // XSWEE (stub) trk.pos++; break; case 12: // XWAIT trk.delay = rom.ReadU16(trk.pos); trk.pos += 2; break; case 13: // XSOFF (stub) trk.pos += 4; break; default: cmdPlayFine(trackIdx); break; } }
20,383
C++
.cpp
663
21.05279
129
0.516526
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,647
SoundExporter.cpp
ipatix_agbplay/src/SoundExporter.cpp
#include <filesystem> #include <boost/algorithm/string/replace.hpp> #include <chrono> #include <climits> #include <cmath> #include <atomic> #include <thread> #include <mutex> #include "SoundExporter.h" #include "Util.h" #include "Xcept.h" #include "Constants.h" #include "Debug.h" #include "ConfigManager.h" #include "PlayerContext.h" #include "OS.h" /* * public SoundExporter */ SoundExporter::SoundExporter(SongTable& songTable, bool benchmarkOnly, bool seperate) : songTable(songTable), benchmarkOnly(benchmarkOnly), seperate(seperate) { } void SoundExporter::Export(const std::vector<SongEntry>& entries) { /* create directories for file export */ std::filesystem::path dir = ConfigManager::Instance().GetWavOutputDir(); if (std::filesystem::exists(dir)) { if (!std::filesystem::is_directory(dir)) { throw Xcept("Output directory exists but isn't a dir"); } } else if (!std::filesystem::create_directories(dir)) { throw Xcept("Creating output directory failed"); } /* setup export thread worker function */ std::atomic<size_t> currentSong = 0; std::atomic<size_t> totalBlocksRendered = 0; std::function<void(void)> threadFunc = [&]() { OS::LowerThreadPriority(); while (true) { size_t i = currentSong++; // atomic ++ if (i >= entries.size()) return; std::string fname = entries[i].name; boost::replace_all(fname, "/", "_"); Debug::print("%3d %% - Rendering to file: \"%s\"", (i + 1) * 100 / entries.size(), fname.c_str()); char fileName[512]; snprintf(fileName, sizeof(fileName), "%s/%03zu - %s", dir.c_str(), i + 1, fname.c_str()); totalBlocksRendered += exportSong(fileName, entries[i].GetUID()); } }; /* run the actual export threads */ auto startTime = std::chrono::high_resolution_clock::now(); size_t numThreads = std::thread::hardware_concurrency(); if (numThreads == 0) numThreads = 1; std::vector<std::thread> workers; for (size_t i = 0; i < numThreads; i++) workers.emplace_back(threadFunc); for (auto& w : workers) w.join(); workers.clear(); auto endTime = std::chrono::high_resolution_clock::now(); /* report finished progress */ if (std::chrono::duration_cast<std::chrono::seconds>(endTime - startTime).count() == 0) { Debug::print("Successfully wrote %zu files", entries.size()); } else { size_t secondsTotal = static_cast<size_t>(std::chrono::duration_cast<std::chrono::seconds>(endTime - startTime).count()); size_t blocksPerSecond = totalBlocksRendered / secondsTotal; Debug::print("Successfully wrote %zu files at %zu blocks per second (%zu seconds total)", entries.size(), blocksPerSecond, secondsTotal); } } /* * private SoundExporter */ void SoundExporter::writeSilence(SNDFILE *ofile, double seconds) { if (seconds <= 0.0) return; size_t samples = static_cast<size_t>(std::round(STREAM_SAMPLERATE * seconds)); std::vector<sample> silence(samples, {0.0f, 0.0f}); sf_writef_float(ofile, reinterpret_cast<float *>(silence.data()), static_cast<sf_count_t>(silence.size())); } size_t SoundExporter::exportSong(const std::filesystem::path& fileName, uint16_t uid) { // setup our generators GameConfig& cfg = ConfigManager::Instance().GetCfg(); PlayerContext ctx( ConfigManager::Instance().GetMaxLoopsExport(), cfg.GetTrackLimit(), EnginePars(cfg.GetPCMVol(), cfg.GetEngineRev(), cfg.GetEngineFreq()) ); ctx.InitSong(songTable.GetPosOfSong(uid)); size_t blocksRendered = 0; size_t nBlocks = ctx.mixer.GetSamplesPerBuffer(); size_t nTracks = ctx.seq.tracks.size(); std::vector<std::vector<sample>> trackAudio; double padSecondsStart = ConfigManager::Instance().GetPadSecondsStart(); double padSecondsEnd = ConfigManager::Instance().GetPadSecondsEnd(); if (!benchmarkOnly) { /* save each track to a separate file */ if (seperate) { std::vector<SNDFILE *> ofiles(nTracks, nullptr); std::vector<SF_INFO> oinfos(nTracks); for (size_t i = 0; i < nTracks; i++) { memset(&oinfos[i], 0, sizeof(oinfos[i])); oinfos[i].samplerate = STREAM_SAMPLERATE; oinfos[i].channels = 2; // stereo oinfos[i].format = SF_FORMAT_WAV | SF_FORMAT_FLOAT; char outName[PATH_MAX]; snprintf(outName, sizeof(outName), "%s.%02zu.wav", fileName.c_str(), i); ofiles[i] = sf_open(outName, SFM_WRITE, &oinfos[i]); if (ofiles[i] == NULL) Debug::print("Error: %s", sf_strerror(NULL)); } while (true) { ctx.reader.Process(); ctx.mixer.Process(trackAudio); if (ctx.HasEnded()) break; assert(trackAudio.size() == nTracks); for (size_t i = 0; i < nTracks; i++) { // do not write to invalid files if (ofiles[i] == NULL) continue; sf_count_t processed = 0; do { processed += sf_writef_float(ofiles[i], &trackAudio[i][processed].left, sf_count_t(nBlocks) - processed); } while (processed < sf_count_t(nBlocks)); } blocksRendered += nBlocks; } for (SNDFILE *& i : ofiles) { int err = sf_close(i); if (err != 0) Debug::print("Error: %s", sf_error_number(err)); } } else { SF_INFO oinfo; memset(&oinfo, 0, sizeof(oinfo)); oinfo.samplerate = STREAM_SAMPLERATE; oinfo.channels = 2; // sterep oinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT; SNDFILE *ofile = sf_open((fileName.string() + ".wav").c_str(), SFM_WRITE, &oinfo); if (ofile == NULL) { Debug::print("Error: %s", sf_strerror(NULL)); return 0; } // do rendering and write std::vector<sample> renderedData(nBlocks); writeSilence(ofile, padSecondsStart); while (true) { ctx.reader.Process(); ctx.mixer.Process(trackAudio); if (ctx.HasEnded()) break; // mix streams to one master assert(trackAudio.size() == nTracks); // clear mixing buffer fill(renderedData.begin(), renderedData.end(), sample{0.0f, 0.0f}); // mix all tracks to buffer for (std::vector<sample>& b : trackAudio) { assert(b.size() == renderedData.size()); for (size_t i = 0; i < b.size(); i++) { renderedData[i].left += b[i].left; renderedData[i].right += b[i].right; } } sf_count_t processed = 0; do { processed += sf_writef_float(ofile, &renderedData[processed].left, sf_count_t(nBlocks) - processed); } while (processed < sf_count_t(nBlocks)); blocksRendered += nBlocks; } writeSilence(ofile, padSecondsEnd); int err; if ((err = sf_close(ofile)) != 0) Debug::print("Error: %s", sf_error_number(err)); } } // if benchmark only else { while (true) { ctx.reader.Process(); ctx.mixer.Process(trackAudio); blocksRendered += nBlocks; if (ctx.HasEnded()) break; } } return blocksRendered; }
8,090
C++
.cpp
204
29.27451
145
0.553335
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,648
CGBPatterns.cpp
ipatix_agbplay/src/CGBPatterns.cpp
#include "CGBPatterns.h" // square wave LUT const float CGBPatterns::pat_sq12[] = { 0.875f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f, -0.125f }; const float CGBPatterns::pat_sq25[] = { 0.75f, 0.75f, -0.25f, -0.25f, -0.25f, -0.25f, -0.25f, -0.25f }; const float CGBPatterns::pat_sq50[] = { 0.50f, 0.50f, 0.50f, 0.50f, -0.50f, -0.50f, -0.50f, -0.50f }; const float CGBPatterns::pat_sq75[] = { 0.25f, 0.25f, 0.25f, 0.25f, 0.25f, 0.25f, -0.75, -0.75f };
480
C++
.cpp
14
32
73
0.601293
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,649
TitlebarGUI.cpp
ipatix_agbplay/src/TitlebarGUI.cpp
#include <cstring> #include <string> #include <vector> #include "Constants.h" #include "TitlebarGUI.h" #include "ColorDef.h" #include "Xcept.h" static const std::vector<std::string> bannerText = { " _ _ ", " __ _ __ _| |__ _ __| |__ _ _ _ ", "/ _` / _` | '_ \\ '_ \\ / _` | || |", "\\__,_\\__, |_.__/ .__/_\\__,_|\\_, |", " |___/ |_| |__/ " }; TitlebarGUI::TitlebarGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : CursesWin(height, width, yPos, xPos) { if (width < bannerText[0].size()) throw Xcept("Terminal too narrow for banner text"); if (height < bannerText.size()) throw Xcept("Terminal to flat for banner text"); keypad(winPtr, true); nodelay(winPtr, true); update(); } TitlebarGUI::~TitlebarGUI() { } void TitlebarGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); keypad(winPtr, true); nodelay(winPtr, true); update(); } int TitlebarGUI::GetKey() { return wgetch(winPtr); } /* * private TitlebarGUI */ void TitlebarGUI::update() { uint32_t textHeight = uint32_t(bannerText.size()); uint32_t upperPadding = uint32_t((height - textHeight) / 2); // unused for now for (uint32_t i = 0; i < height; i++) { // print upper padding if (i < upperPadding || i > height - upperPadding) { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::BANNER_TEXT))); mvwhline(winPtr, (int)i, 0, ' ', width); } else { uint32_t leftPadding = (uint32_t)((width - bannerText[i - upperPadding].size()) / 2); uint32_t rightPadding = (uint32_t)((width - bannerText[i - upperPadding].size()) / 2 + ((width - bannerText[i - upperPadding].size()) % 2)); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::BANNER_TEXT))); mvwprintw(winPtr, (int)i, 0, "%*s%s%*s", leftPadding, "", bannerText[i - upperPadding].c_str(), rightPadding, ""); } } wrefresh(winPtr); }
2,123
C++
.cpp
63
28.777778
126
0.570872
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,650
ConsoleGUI.cpp
ipatix_agbplay/src/ConsoleGUI.cpp
#include <string> #include <mutex> #include "ConsoleGUI.h" #include "Debug.h" #include "WindowGUI.h" #include "Xcept.h" #include "ColorDef.h" /* * -- public -- */ ConsoleGUI::ConsoleGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : CursesWin(height, width, yPos, xPos), msgQueue(32) { textWidth = width - 2; textHeight = height; update(); Debug::set_callback(remoteWrite, this); } ConsoleGUI::~ConsoleGUI() { } void ConsoleGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); textHeight = height; textWidth = width - 2; update(); } void ConsoleGUI::Refresh() { std::string newText; bool modified = false; while (msgQueue.pop(newText)) { writeToBuffer(newText); modified = true; } if (modified) update(); } /* * -- private -- */ void ConsoleGUI::update() { for (uint32_t i = 0; i < textHeight; i++) { wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); mvwprintw(winPtr, (int)i, 0, ">"); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_REVERSE); mvwprintw(winPtr, (int)i, 1, " "); std::string txt; if (i < textBuffer.size()) { txt = textBuffer.at(i); } else { txt = ""; } txt.resize(textWidth, ' '); mvwprintw(winPtr, (int)i, 2, txt.c_str()); } wrefresh(winPtr); } void ConsoleGUI::writeToBuffer(const std::string& str) { textBuffer.push_back(str); if (textBuffer.size() > textHeight) { textBuffer.erase(textBuffer.begin() + 0); } } void ConsoleGUI::remoteWrite(const std::string& str, void *obj) { ConsoleGUI *ui = (ConsoleGUI *)obj; std::scoped_lock<std::mutex> l(ui->writeMutex); ui->msgQueue.push(str); }
1,902
C++
.cpp
73
21.520548
88
0.620804
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,651
RomviewGUI.cpp
ipatix_agbplay/src/RomviewGUI.cpp
#include "RomviewGUI.h" #include "ColorDef.h" #include "Util.h" #include "Debug.h" #include "Rom.h" /* * public */ RomviewGUI::RomviewGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos, SongTable& songTable) : CursesWin(height, width, yPos, xPos) { gameName = Rom::Instance().ReadString(0xA0, 12); gameCode = Rom::Instance().ReadString(0xAC, 4); songTablePos = songTable.GetSongTablePos(); numSongs = songTable.GetNumSongs(); update(); } RomviewGUI::~RomviewGUI() { } void RomviewGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); update(); } /* * private */ void RomviewGUI::update() { // clear wattrset(winPtr, A_NORMAL); wclear(winPtr); // draw borders wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME)) | A_REVERSE); mvwvline(winPtr, 1, 0, ' ', height-1); mvwprintw(winPtr, 0, 0, "%-*s", width, " ROM Information"); // print information wattrset(winPtr, A_UNDERLINE | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 2, 2, "ROM Name:"); wattrset(winPtr, A_BOLD | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 3, 2, "%s", gameName.c_str()); wattrset(winPtr, A_UNDERLINE | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 5, 2, "ROM Code:"); wattrset(winPtr, A_BOLD | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 6, 2, "%s", gameCode.c_str()); wattrset(winPtr, A_UNDERLINE | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 8, 2, "Songtable Offset:"); wattrset(winPtr, A_BOLD | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 9, 2, "0x%lX", songTablePos); wattrset(winPtr, A_UNDERLINE | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 11, 2, "Number of Songs:"); wattrset(winPtr, A_BOLD | COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); mvwprintw(winPtr, 12, 2, "%zu", numSongs); wrefresh(winPtr); }
2,073
C++
.cpp
56
33.375
107
0.671478
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,652
PlayerInterface.cpp
ipatix_agbplay/src/PlayerInterface.cpp
#include <thread> #include <chrono> #include <cstdlib> #include <algorithm> #include <cmath> #include <cassert> #include <cstring> #if __has_include(<pa_win_wasapi.h>) #include <pa_win_wasapi.h> #endif #include "PlayerInterface.h" #include "Xcept.h" #include "Debug.h" #include "Util.h" #include "ConfigManager.h" /* * PlayerInterface data */ // first portaudio hostapi has highest priority, last hostapi has lowest // if none are available, the default one is selected. // they are also the ones which are known to work const std::vector<PaHostApiTypeId> PlayerInterface::hostApiPriority = { // Unix paJACK, paALSA, // Windows paWASAPI, paMME, // Mac OS paCoreAudio, paSoundManager, }; /* * public PlayerInterface */ PlayerInterface::PlayerInterface(TrackviewGUI& trackUI, size_t initSongPos) : trackUI(trackUI), mutedTracks(ConfigManager::Instance().GetCfg().GetTrackLimit()) { initContext(); ctx->InitSong(initSongPos); setupLoudnessCalcs(); portaudioOpen(); } PlayerInterface::~PlayerInterface() { // stop and deallocate player thread if required Stop(); portaudioClose(); } void PlayerInterface::LoadSong(size_t songPos) { bool play = playerState == State::PLAYING; Stop(); ctx->InitSong(songPos); setupLoudnessCalcs(); // TODO replace this with pairs float vols[ctx->seq.tracks.size() * 2]; for (size_t i = 0; i < ctx->seq.tracks.size() * 2; i++) vols[i] = 0.0f; trackUI.SetState(ctx->seq, vols, 0, 0); if (play) Play(); } void PlayerInterface::Play() { switch (playerState) { case State::RESTART: // --> handled by worker break; case State::PLAYING: // restart song if player is running playerState = State::RESTART; break; case State::PAUSED: // continue paused playback playerState = State::PLAYING; break; case State::TERMINATED: // thread needs to be deleted before restarting Stop(); Play(); break; case State::SHUTDOWN: // --> handled by worker break; case State::THREAD_DELETED: playerState = State::PLAYING; playerThread = std::make_unique<std::thread>(&PlayerInterface::threadWorker, this); #ifdef __linux__ pthread_setname_np(playerThread->native_handle(), "mixer thread"); #endif // start thread and play back song break; } } void PlayerInterface::Pause() { switch (playerState) { case State::RESTART: // --> handled by worker break; case State::PLAYING: playerState = State::PAUSED; break; case State::PAUSED: playerState = State::PLAYING; break; case State::TERMINATED: // ingore this break; case State::SHUTDOWN: // --> handled by worker break; case State::THREAD_DELETED: Play(); break; } } void PlayerInterface::Stop() { switch (playerState) { case State::RESTART: // wait until player has initialized and quit then while (playerState != State::PLAYING) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); } Stop(); break; case State::PLAYING: playerState = State::SHUTDOWN; Stop(); break; case State::PAUSED: playerState = State::SHUTDOWN; Stop(); break; case State::TERMINATED: case State::SHUTDOWN: playerThread->join(); playerThread.reset(); playerState = State::THREAD_DELETED; break; case State::THREAD_DELETED: // ignore this break; } } void PlayerInterface::SpeedDouble() { speedFactor <<= 1; if (speedFactor > 1024) speedFactor = 1024; ctx->reader.SetSpeedFactor(float(speedFactor) / 64.0f); } void PlayerInterface::SpeedHalve() { speedFactor >>= 1; if (speedFactor < 1) speedFactor = 1; ctx->reader.SetSpeedFactor(float(speedFactor) / 64.0f); } bool PlayerInterface::IsPlaying() { return playerState != State::THREAD_DELETED && playerState != State::TERMINATED; } bool PlayerInterface::IsPaused() const { return playerState == State::PAUSED; } void PlayerInterface::UpdateView() { if (playerState != State::THREAD_DELETED && playerState != State::SHUTDOWN && playerState != State::TERMINATED) { size_t trks = ctx->seq.tracks.size(); assert(trks == trackLoudness.size()); float vols[trks * 2]; for (size_t i = 0; i < trks; i++) trackLoudness[i].GetLoudness(vols[i*2], vols[i*2+1]); /* count number of active PCM channels */ trackUI.SetState(ctx->seq, vols, static_cast<int>(ctx->sndChannels.size()), -1); } } void PlayerInterface::ToggleMute(size_t index) { mutedTracks[index] = !mutedTracks[index]; } void PlayerInterface::Mute(size_t index, bool mute) { mutedTracks[index] = mute; } void PlayerInterface::GetMasterVolLevels(float& left, float& right) { masterLoudness.GetLoudness(left, right); } SongInfo PlayerInterface::GetSongInfo() const { SongInfo result; result.songHeaderPos = ctx->seq.GetSongHeaderPos(); result.voiceTablePos = ctx->seq.GetSoundBankPos(); result.reverb = ctx->seq.GetReverb(); result.priority = ctx->seq.GetPriority(); return result; } /* * private PlayerInterface */ void PlayerInterface::initContext() { const auto& cfg = ConfigManager::Instance().GetCfg(); /* We could make the context a member variable instead of * a unique_ptr, but initialization get's a little messy that way */ ctx = std::make_unique<PlayerContext>( ConfigManager::Instance().GetMaxLoopsPlaylist(), cfg.GetTrackLimit(), EnginePars(cfg.GetPCMVol(), cfg.GetEngineRev(), cfg.GetEngineFreq()) ); } void PlayerInterface::threadWorker() { size_t samplesPerBuffer = ctx->mixer.GetSamplesPerBuffer(); std::vector<sample> silence(samplesPerBuffer, sample{0.0f, 0.0f}); std::vector<sample> masterAudio(samplesPerBuffer, sample{0.0f, 0.0f}); std::vector<std::vector<sample>> trackAudio; try { while (playerState != State::SHUTDOWN) { switch (playerState) { case State::RESTART: ctx->InitSong(ctx->seq.GetSongHeaderPos()); playerState = State::PLAYING; [[fallthrough]]; case State::PLAYING: { // clear high level mixing buffer fill(masterAudio.begin(), masterAudio.end(), sample{0.0f, 0.0f}); // render audio buffers for tracks ctx->Process(trackAudio); for (size_t i = 0; i < trackAudio.size(); i++) { assert(trackAudio[i].size() == masterAudio.size()); bool muteThis = mutedTracks[i]; ctx->seq.tracks[i].muted = muteThis; trackLoudness[i].CalcLoudness(trackAudio[i].data(), samplesPerBuffer); if (muteThis) continue; for (size_t j = 0; j < masterAudio.size(); j++) { masterAudio[j].left += trackAudio[i][j].left; masterAudio[j].right += trackAudio[i][j].right; } } // blocking write to audio buffer rBuf.Put(masterAudio.data(), masterAudio.size()); masterLoudness.CalcLoudness(masterAudio.data(), samplesPerBuffer); if (ctx->HasEnded()) { playerState = State::SHUTDOWN; break; } } break; case State::PAUSED: rBuf.Put(silence.data(), silence.size()); break; default: throw Xcept("Internal PlayerInterface error: %d", (int)playerState); } } // reset song state after it has finished ctx->InitSong(ctx->seq.GetSongHeaderPos()); } catch (std::exception& e) { Debug::print("FATAL ERROR on streaming thread: %s", e.what()); } masterLoudness.Reset(); for (LoudnessCalculator& c : trackLoudness) c.Reset(); // flush buffer rBuf.Clear(); playerState = State::TERMINATED; } int PlayerInterface::audioCallback(const void *inputBuffer, void *outputBuffer, size_t framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { (void)inputBuffer; (void)timeInfo; (void)statusFlags; Ringbuffer *rBuf = (Ringbuffer *)userData; rBuf->Take((sample *)outputBuffer, framesPerBuffer); return 0; } void PlayerInterface::setupLoudnessCalcs() { trackLoudness.clear(); for (size_t i = 0; i < ctx->seq.tracks.size(); i++) trackLoudness.emplace_back(5.0f); } void PlayerInterface::portaudioOpen() { // init host api std::vector<PaHostApiTypeId> hostApiPrioritiesWithFallback = hostApiPriority; const PaHostApiIndex defaultHostApiIndex = Pa_GetDefaultHostApi(); if (defaultHostApiIndex < 0) throw Xcept("Pa_GetDefaultHostApi(): No host API avilable: %s", Pa_GetErrorText(defaultHostApiIndex)); const PaHostApiInfo *defaultHostApiInfo = Pa_GetHostApiInfo(defaultHostApiIndex); if (defaultHostApiInfo == nullptr) throw Xcept("Pa_GetHostApiInfo(): failed with valid index"); const auto f = std::find(hostApiPrioritiesWithFallback.begin(), hostApiPrioritiesWithFallback.end(), defaultHostApiInfo->type); if (f == hostApiPrioritiesWithFallback.end()) hostApiPrioritiesWithFallback.push_back(defaultHostApiInfo->type); bool streamOpen = false; for (const auto apiType : hostApiPrioritiesWithFallback) { const PaHostApiIndex hostApiIndex = Pa_HostApiTypeIdToHostApiIndex(apiType); // prioritized host api available ? if (hostApiIndex < 0) continue; const PaHostApiInfo *apiInfo = Pa_GetHostApiInfo(hostApiIndex); if (apiInfo == nullptr) throw Xcept("Pa_GetHostApiInfo with valid index failed"); const PaDeviceIndex deviceIndex = apiInfo->defaultOutputDevice; std::shared_ptr<void> hostApiSpecificStreamInfo; #if __has_include(<pa_win_wasapi.h>) if (apiType == paWASAPI) { PaWasapiStreamInfo info; memset(&info, 0, sizeof(info)); info.size = sizeof(info); info.hostApiType = paWASAPI; info.version = 1; info.flags = paWinWasapiAutoConvert; hostApiSpecificStreamInfo = std::make_shared<PaWasapiStreamInfo>(info); } #endif const PaDeviceInfo *devInfo = Pa_GetDeviceInfo(deviceIndex); if (devInfo == nullptr) throw Xcept("Pa_GetDeviceInfo(): failed with valid index"); PaStreamParameters outputStreamParameters; outputStreamParameters.device = deviceIndex; outputStreamParameters.channelCount = 2; // stereo outputStreamParameters.sampleFormat = paFloat32; outputStreamParameters.suggestedLatency = devInfo->defaultLowOutputLatency; outputStreamParameters.hostApiSpecificStreamInfo = hostApiSpecificStreamInfo.get(); const uint32_t rate = ctx->mixer.GetSampleRate(); PaError err = Pa_OpenStream(&audioStream, nullptr, &outputStreamParameters, rate, paFramesPerBufferUnspecified, paNoFlag, audioCallback, (void *)&rBuf); if (err != paNoError) { Debug::print("Pa_OpenStream(): unable to open stream with host API %s: %s", apiInfo->name, Pa_GetErrorText(err)); continue; } err = Pa_StartStream(audioStream); if (err != paNoError) { Debug::print("Pa_StartStream(): unable to start stream for Host API %s: %s", apiInfo->name, Pa_GetErrorText(err)); err = Pa_CloseStream(audioStream); if (err != paNoError) Debug::print("Pa_CloseStream(): unable to close fail-started stream for Host API %s: %s", apiInfo->name, Pa_GetErrorText(err)); continue; } streamOpen = true; break; } if (!streamOpen) throw Xcept("Unable to initialize sound output: Host API could not be initialized"); } void PlayerInterface::portaudioClose() { PaError err; if ((err = Pa_StopStream(audioStream)) != paNoError) { Debug::print("Pa_StopStream: %s", Pa_GetErrorText(err)); } if ((err = Pa_CloseStream(audioStream)) != paNoError) { Debug::print("Pa_CloseStream: %s", Pa_GetErrorText(err)); } }
13,005
C++
.cpp
368
27.546196
160
0.623045
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,653
WindowGUI.cpp
ipatix_agbplay/src/WindowGUI.cpp
#include <string> #include <algorithm> #include <sstream> #include <cstdlib> #include <stdexcept> #include <thread> #include <chrono> #include <cstring> #include <iomanip> #include "Constants.h" #include "Xcept.h" #include "Debug.h" #include "ColorDef.h" #include "WindowGUI.h" #include "Util.h" #include "SoundExporter.h" #define KEY_TAB 9 WindowGUI::WindowGUI(SongTable& songTable) : songTable(songTable) { // init ncurses stuff this->containerWin = initscr(); updateWindowSize(); if (has_colors() == false) throw Xcept("Error, your terminal doesn't support colors"); initColors(); noecho(); curs_set(0); keypad(stdscr, true); this->play = false; this->cursorl = SONGLIST; // create subwindows conUI = std::make_unique<ConsoleGUI>( CONSOLE_HEIGHT(height, width), CONSOLE_WIDTH(height, width), CONSOLE_YPOS(height, width), CONSOLE_XPOS(height, width)); hotUI = std::make_unique<HotkeybarGUI>( HOTKEYBAR_HEIGHT(height, width), HOTKEYBAR_WIDTH(height, width), HOTKEYBAR_YPOS(height, width), HOTKEYBAR_XPOS(height, width)); songUI = std::make_unique<SonglistGUI>( SONGLIST_HEIGHT(height, width), SONGLIST_WIDTH(height, width), SONGLIST_YPOS(height, width), SONGLIST_XPOS(height, width), true); // add songs to table for (uint16_t i = 0; i < songTable.GetNumSongs(); i++) { std::ostringstream txt; txt << std::setw(4) << std::setfill('0') << i; songUI->AddSong(SongEntry(txt.str(), i)); } songUI->Enter(); playUI = std::make_unique<PlaylistGUI>( PLAYLIST_HEIGHT(height, width), PLAYLIST_WIDTH(height, width), PLAYLIST_YPOS(height, width), PLAYLIST_XPOS(height, width)); titleUI = std::make_unique<TitlebarGUI>( TITLEBAR_HEIGHT(height, width), TITLEBAR_WIDTH(height, width), TITLEBAR_YPOS(height, width), TITLEBAR_XPOS(height, width)); romUI = std::make_unique<RomviewGUI>( ROMVIEW_HEIGHT(height, width), ROMVIEW_WIDTH(height, width), ROMVIEW_YPOS(height, width), ROMVIEW_XPOS(height, width), songTable); trackUI = std::make_unique<TrackviewGUI>( TRACKVIEW_HEIGHT(height, width), TRACKVIEW_WIDTH(height, width), TRACKVIEW_YPOS(height, width), TRACKVIEW_XPOS(height, width)); meterUI = std::make_unique<VUMeterGUI>( VUMETER_HEIGHT(height, width), VUMETER_WIDTH(height, width), VUMETER_YPOS(height, width), VUMETER_XPOS(height, width)); Rom& rom = Rom::Instance(); mplay = std::make_unique<PlayerInterface>( *trackUI, rom.ReadAgbPtrToPos(songTable.GetSongTablePos()) ); mplay->LoadSong(songTable.GetPosOfSong(0)); trackUI->SetTitle(songUI->GetSong()->GetName()); } WindowGUI::~WindowGUI() { endwin(); } bool WindowGUI::Handle() { int ch; while ((ch = titleUI->GetKey()) != ERR) { switch (ch) { case '\n': enter(); break; case 18: // CTRL+R case KEY_RESIZE: updateWindowSize(); resizeWindows(); break; case KEY_UP: case 'k': scrollUp(); break; case KEY_DOWN: case 'j': scrollDown(); break; case KEY_LEFT: case 'h': scrollLeft(); break; case KEY_RIGHT: case 'l': scrollRight(); break; case KEY_PPAGE: pageUp(); break; case KEY_NPAGE: pageDown(); break; case KEY_TAB: cycleFocus(); break; case 'a': add(); break; case 'd': del(); break; case 't': if (cursorl == PLAYLIST) playUI->ToggleTick(); break; case 'g': if (cursorl == PLAYLIST) playUI->ToggleDrag(); break; case 'T': if (cursorl == PLAYLIST) playUI->UntickAll(); break; case 'i': mplay->Play(); play = true; break; case 'o': case ' ': play = mplay->IsPaused(); mplay->Pause(); break; case 'p': play = false; mplay->Stop(); break; case '+': case '=': mplay->SpeedDouble(); break; case '-': mplay->SpeedHalve(); break; case 'n': playUI->Leave(); rename(); if (SongEntry *entry = playUI->GetSong(); entry != nullptr) trackUI->SetTitle(entry->GetName()); trackUI->ForceUpdate(); playUI->Enter(); break; case 'e': if (exportReady()) exportLaunch(false, true); break; case 'r': if (exportReady()) exportLaunch(false, false); break; case 'b': if (exportReady()) exportLaunch(true, false); break; case 'm': mute(); break; case 's': solo(); break; case 'u': tutti(); break; case 'f': ConfigManager::Instance().Save(); break; case '!': songInfo(); break; case EOF: case 4: // EOT case 'q': case 27: // Escape Key // don't allow closing if an export is still running if (!exportReady()) break; Debug::print("Exiting..."); ConfigManager::Instance().Save(); mplay->Stop(); return false; } // end key handling switch } // end key loop if (play) { if (!mplay->IsPlaying()) { if ((cursorl != PLAYLIST && cursorl != SONGLIST) || isLastSong()) { play = false; } else { scrollDown(); mplay->Play(); } } mplay->UpdateView(); float lVol; float rVol; mplay->GetMasterVolLevels(lVol, rVol); meterUI->SetVol(lVol, rVol); } conUI->Refresh(); return true; } void WindowGUI::resizeWindows() { conUI->Resize( CONSOLE_HEIGHT(height, width), CONSOLE_WIDTH(height, width), CONSOLE_YPOS(height, width), CONSOLE_XPOS(height, width)); hotUI->Resize( HOTKEYBAR_HEIGHT(height, width), HOTKEYBAR_WIDTH(height, width), HOTKEYBAR_YPOS(height, width), HOTKEYBAR_XPOS(height, width)); songUI->Resize( SONGLIST_HEIGHT(height, width), SONGLIST_WIDTH(height, width), SONGLIST_YPOS(height, width), SONGLIST_XPOS(height, width)); playUI->Resize( PLAYLIST_HEIGHT(height, width), PLAYLIST_WIDTH(height, width), PLAYLIST_YPOS(height, width), PLAYLIST_XPOS(height, width)); titleUI->Resize( TITLEBAR_HEIGHT(height, width), TITLEBAR_WIDTH(height, width), TITLEBAR_YPOS(height, width), TITLEBAR_XPOS(height, width)); romUI->Resize( ROMVIEW_HEIGHT(height, width), ROMVIEW_WIDTH(height, width), ROMVIEW_YPOS(height, width), ROMVIEW_XPOS(height, width)); trackUI->Resize( TRACKVIEW_HEIGHT(height, width), TRACKVIEW_WIDTH(height, width), TRACKVIEW_YPOS(height, width), TRACKVIEW_XPOS(height, width)); meterUI->Resize( VUMETER_HEIGHT(height, width), VUMETER_WIDTH(height, width), VUMETER_YPOS(height, width), VUMETER_XPOS(height, width)); } void WindowGUI::initColors() { start_color(); short defFg = -1, defBg = -1; if (use_default_colors() == ERR) { // if this call could have been successful -1 would be the valid default color defFg = COLOR_WHITE; defBg = COLOR_BLACK; } if (COLORS != 256) throw Xcept("Terminal does not support 256 colors"); init_pair((int)Color::DEF_DEF, defFg, defBg); init_pair((int)Color::BANNER_TEXT, COLOR_YELLOW, defBg); init_pair((int)Color::WINDOW_FRAME, COLOR_GREEN, defBg); init_pair((int)Color::LIST_ENTRY, COLOR_YELLOW, defBg); init_pair((int)Color::LIST_SEL, COLOR_RED, defBg); init_pair((int)Color::VU_LOW, 82, defBg); init_pair((int)Color::VU_MID, 226, defBg); init_pair((int)Color::VU_HIGH, 202, defBg); init_pair((int)Color::TRK_NUM, 76, defBg); init_pair((int)Color::TRK_NUM_MUTED, 196, defBg); init_pair((int)Color::TRK_LOC, 118, defBg); init_pair((int)Color::TRK_LOC_CALL, 184, defBg); init_pair((int)Color::TRK_DEL, 196, defBg); init_pair((int)Color::TRK_NOTE, 45, defBg); init_pair((int)Color::TRK_VOICE, 217, defBg); init_pair((int)Color::TRK_PAN, 214, defBg); init_pair((int)Color::TRK_VOL, 154, defBg); init_pair((int)Color::TRK_MOD, 43, defBg); init_pair((int)Color::TRK_PITCH, 129, defBg); init_pair((int)Color::TRK_LOUDNESS, 70, /*238*/defBg); init_pair((int)Color::TRK_LOUDNESS_MUTED, 166, /*238*/defBg); init_pair((int)Color::TRK_LOUD_SPLIT, defFg, /*238*/defBg); init_pair((int)Color::TRK_FGB_BGCW, 232, 251); init_pair((int)Color::TRK_FGC_BGCW, 161, 251); init_pair((int)Color::TRK_FGB_BGW, 232, 255); init_pair((int)Color::TRK_FGC_BGW, 161, 255); init_pair((int)Color::TRK_FGB_BGC, 232, 199); init_pair((int)Color::TRK_FGC_BGC, 161, 199); init_pair((int)Color::TRK_FGW_BGW, 255, 255); init_pair((int)Color::TRK_FGW_BGC, 255, 199); init_pair((int)Color::TRK_FGEC_BGW, 199, 255); init_pair((int)Color::TRK_FGEC_BGC, 199, 199); } void WindowGUI::cycleFocus() { switch (cursorl) { case SONGLIST: songUI->Leave(); cursorl = PLAYLIST; playUI->Enter(); if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case PLAYLIST: playUI->Leave(); cursorl = SONGLIST; songUI->Enter(); if (SongEntry *entry = songUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; default: break; } } void WindowGUI::scrollLeft() { switch (cursorl) { case TRACKS_SONGLIST: trackUI->Leave(); cursorl = SONGLIST; songUI->Enter(); break; case TRACKS_PLAYLIST: trackUI->Leave(); cursorl = PLAYLIST; playUI->Enter(); default: break; } } void WindowGUI::scrollRight() { switch (cursorl) { case SONGLIST: songUI->Leave(); cursorl = TRACKS_SONGLIST; trackUI->Enter(); break; case PLAYLIST: playUI->Leave(); cursorl = TRACKS_PLAYLIST; trackUI->Enter(); break; default: break; } } void WindowGUI::scrollDown() { switch (cursorl) { case SONGLIST: songUI->ScrollDown(); if (SongEntry *entry = songUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case PLAYLIST: playUI->ScrollDown(); if (!playUI->IsDragging()) { if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } } break; case TRACKS_SONGLIST: case TRACKS_PLAYLIST: trackUI->ScrollDown(); break; default: break; } } void WindowGUI::scrollUp() { switch (cursorl) { case SONGLIST: songUI->ScrollUp(); if (SongEntry *entry = songUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case PLAYLIST: playUI->ScrollUp(); if (playUI->IsDragging()) break; if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case TRACKS_SONGLIST: case TRACKS_PLAYLIST: trackUI->ScrollUp(); break; default: break; } } bool WindowGUI::isLastSong() const { switch (cursorl) { case SONGLIST: return songUI->IsLast(); case PLAYLIST: return playUI->IsLast(); default: return false; } } void WindowGUI::pageDown() { switch (cursorl) { case SONGLIST: songUI->PageDown(); if (SongEntry *entry = songUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case PLAYLIST: playUI->PageDown(); if (playUI->IsDragging()) break; if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case TRACKS_SONGLIST: case TRACKS_PLAYLIST: trackUI->PageDown(); break; default: break; } } void WindowGUI::pageUp() { switch (cursorl) { case SONGLIST: songUI->PageUp(); if (SongEntry *entry = songUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case PLAYLIST: playUI->PageUp(); if (playUI->IsDragging()) break; if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } break; case TRACKS_SONGLIST: case TRACKS_PLAYLIST: trackUI->PageUp(); break; default: break; } } void WindowGUI::songInfo() { SongEntry *entry; if (cursorl == SONGLIST) { entry = songUI->GetSong(); } else if (cursorl == PLAYLIST) { entry = playUI->GetSong(); } else { return; } if (entry == nullptr) { Debug::print("Cannot get song info: No song loaded!"); return; } SongInfo sinfo = mplay->GetSongInfo(); Debug::print("Song Info: num=%d header=0x%X voicetable=0x%X reverb=%d priority=%d", static_cast<int>(entry->GetUID()), sinfo.songHeaderPos, sinfo.voiceTablePos, sinfo.reverb, sinfo.priority ); } void WindowGUI::enter() { switch (cursorl) { case TRACKS_SONGLIST: case TRACKS_PLAYLIST: // TODO mute/unmute mplay->ToggleMute(trackUI->GetCursorLoc()); break; default: break; } } void WindowGUI::add() { if (cursorl != SONGLIST) return; SongEntry *entry = songUI->GetSong(); if (entry != nullptr) playUI->AddSong(*entry); } void WindowGUI::del() { if (cursorl != PLAYLIST) return; playUI->RemoveSong(); if (SongEntry *entry = playUI->GetSong(); entry != nullptr) { mplay->LoadSong(songTable.GetPosOfSong(entry->GetUID())); trackUI->SetTitle(entry->GetName()); } } void WindowGUI::mute() { size_t cur; size_t count; switch (cursorl) { case TRACKS_SONGLIST: case TRACKS_PLAYLIST: cur = trackUI->GetCursorLoc(); count = mplay->GetMaxTracks(); for (size_t i = 0; i < count; i++) { if (cur == i) mplay->Mute(i, true); } break; default: break; } } void WindowGUI::solo() { size_t cur; size_t count; switch (cursorl) { case TRACKS_SONGLIST: case TRACKS_PLAYLIST: cur = trackUI->GetCursorLoc(); count = mplay->GetMaxTracks(); for (size_t i = 0; i < count; i++) { mplay->Mute(i, cur != i); } break; default: break; } } void WindowGUI::tutti() { size_t count; switch (cursorl) { case TRACKS_SONGLIST: case TRACKS_PLAYLIST: count = mplay->GetMaxTracks(); for (size_t i = 0; i < count; i++) { mplay->Mute(i, false); } break; default: break; } } void WindowGUI::rename() { if (cursorl != PLAYLIST) return; SongEntry *ent = playUI->GetSong(); if (ent == nullptr) return; const int renHeight = 5; const int renWidth = 60; WINDOW *renWin = newwin(renHeight, renWidth, (height / 2) - (renHeight / 2), (width / 2) - (renWidth / 2)); keypad(renWin, true); curs_set(1); if (renWin == nullptr) throw Xcept("Error creating renaming window"); wattrset(renWin, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_REVERSE); mvwhline(renWin, 0, 0, ' ', renWidth); // pls no unicode in title or size() below requires fix std::string title = "New Name"; std::string line = " \u250c"; std::string leftBar = ""; std::string rightBar = ""; for (int i = 0; i < (renWidth - (int)title.size())/2 - 3; i++) { leftBar.append("\u2500"); } for (int i = 0; i < (renWidth - (int)title.size())/2 + (renWidth - (int)title.size())%2 - 3; i++) { rightBar.append("\u2500"); } line.append(leftBar); line.append(" "); line.append(title); line.append(" "); line.append(rightBar); line.append("\u2510 "); mvwprintw(renWin, 1, 0, "%s", line.c_str()); mvwprintw(renWin, 2, 0, " \u2502 "); wattrset(renWin, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); line = ""; line.resize(renWidth - 6, ' '); wprintw(renWin, "%s", line.c_str()); wattrset(renWin, COLOR_PAIR(static_cast<int>(Color::DEF_DEF)) | A_REVERSE); wprintw(renWin, " \u2502 "); line = " \u2514"; for (int i = 0; i < renWidth - 4; i++) { line.append("\u2500"); } line.append("\u2518 "); mvwprintw(renWin, 3, 0, "%s", line.c_str()); line = ""; line.resize(renWidth, ' '); mvwprintw(renWin, 4, 0, "%s", line.c_str()); // finished drawing windows, now read the user input wattrset(renWin, COLOR_PAIR(static_cast<int>(Color::DEF_DEF))); char inputBuf[renWidth - 6]; echo(); if (mvwgetnstr(renWin, 2, 3, inputBuf, sizeof(inputBuf) - 1) != ERR) { if (strlen(inputBuf) > 0) { // only change the name if it's not blank ent->name = std::string(inputBuf, strlen(inputBuf)); } } noecho(); curs_set(0); if (delwin(renWin) == ERR) { throw Xcept("Error while deleting renaming window"); } } void WindowGUI::updateWindowSize() { getmaxyx(stdscr, height, width); width = std::clamp(width, WINDOW_MIN_WIDTH, WINDOW_MAX_WIDTH); height = std::clamp(height, WINDOW_MIN_HEIGHT, WINDOW_MAX_HEIGHT); } void WindowGUI::exportLaunch(bool benchmarkOnly, bool separate) { const auto& cfgEntries = ConfigManager::Instance().GetCfg().GetGameEntries(); const auto& ticked = playUI->GetTicked(); assert(cfgEntries.size() == ticked.size()); // we have to pass a copy of the song list to the other thread so that // the list doesn't get destroyed on the fly std::vector<SongEntry> entries; for (size_t i = 0; i < cfgEntries.size(); i++) { if (ticked[i]) entries.emplace_back(cfgEntries[i]); } exportBusy.store(true); exportThread = std::make_unique<std::thread>([&](std::vector<SongEntry> tEntries, bool tBenchmarkOnly, bool tSeparate) { SoundExporter se(songTable, tBenchmarkOnly, tSeparate); se.Export(tEntries); exportBusy.store(false); }, entries, benchmarkOnly, separate ); } bool WindowGUI::exportReady() { if (exportBusy.load()) { Debug::print("Please wait until the current export is finished"); return false; } if (exportThread) { exportThread->join(); exportThread.reset(); } return true; }
22,158
C++
.cpp
711
21.676512
124
0.528048
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,654
Xcept.cpp
ipatix_agbplay/src/Xcept.cpp
#include <cstdarg> #include "Xcept.h" Xcept::Xcept(const char *format, ...) { va_list args; va_start(args, format); char msg_buf[MAX_EXCEPTION_LENGTH]; vsnprintf(msg_buf, MAX_EXCEPTION_LENGTH, format, args); msg = msg_buf; va_end(args); } Xcept::~Xcept() { } const char *Xcept::what() const throw() { return msg.c_str(); }
355
C++
.cpp
15
20.533333
59
0.651786
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,655
agbplay.cpp
ipatix_agbplay/src/agbplay.cpp
#include <iostream> #include <cstring> #include <cstdio> #include <curses.h> #include <portaudio.h> #include <clocale> #include "SoundData.h" #include "Debug.h" #include "WindowGUI.h" #include "Xcept.h" #include "ConfigManager.h" #include "OS.h" static void usage(); static void help(); int main(int argc, char *argv[]) { OS::CheckTerminal(); if (!Debug::open(nullptr)) { std::cout << "Debug Init failed" << std::endl; return EXIT_FAILURE; } if (argc != 2 && argc != 3) { usage(); return EXIT_FAILURE; } if (!strcmp("--help", argv[1])) { help(); return EXIT_SUCCESS; } unsigned long songTableIndex = 0; if (argc == 3) { try { songTableIndex = std::stoul(argv[2]); } catch (std::exception& e) { usage(); return EXIT_FAILURE; } } try { setlocale(LC_ALL, ""); if (Pa_Initialize() != paNoError) throw Xcept("Couldn't init portaudio"); std::cout << "Loading ROM..." << std::endl; Rom::CreateInstance(argv[1]); std::cout << "Loading Config..." << std::endl; ConfigManager::Instance().Load(); std::cout << "Reading Songtable" << std::endl; std::vector<SongTable> songTables = SongTable::ScanForTables(); std::cout << "Found " << songTables.size() << " Songtable(s)." << std::endl; if (songTableIndex >= songTables.size()) { throw Xcept("Songtable index out of range"); } else if (songTableIndex > 0) { std::ostringstream ss; ss << Rom::Instance().GetROMCode() << ":" << songTableIndex; ConfigManager::Instance().SetGameCode(ss.str()); } else { ConfigManager::Instance().SetGameCode(Rom::Instance().GetROMCode()); } std::cout << "Initialization complete!" << std::endl; WindowGUI wgui(songTables[songTableIndex]); std::chrono::nanoseconds frameTime(1000000000 / 60); auto lastTime = std::chrono::high_resolution_clock::now(); while (wgui.Handle()) { auto newTime = std::chrono::high_resolution_clock::now(); if (lastTime + frameTime > newTime) { std::this_thread::sleep_for(frameTime - (newTime - lastTime)); lastTime = std::chrono::high_resolution_clock::now(); } else { lastTime = newTime; } } } catch (const std::exception& e) { endwin(); std::cerr << e.what() << std::endl; return EXIT_FAILURE; } if (Pa_Terminate() != paNoError) std::cerr << "Error while terminating portaudio" << std::endl; Debug::close(); return 0; } static void usage() { std::cout << "Usage: ./agbplay <ROM.gba> [table number]" << std::endl; } static void help() { usage(); std::cout << "\nControls:\n" " - Arrow Keys or HJKL: Navigate through the program\n" " - Tab: Change between Playlist and Songlist\n" " - A: Add the selected song to the playlist\n" " - D: Delete the selected song from the playlist\n" " - T: Toggle whether the song should be output to a file (see R and E)\n" " - G: Drag the song through the playlist for ordering\n" " - I: Force Song Restart\n" " - O: Song Play/Pause\n" " - P: Force Song Stop\n" " - +=: Double the playback speed\n" " - -: Halve the playback speed\n" " - Enter: Toggle Track Muting\n" " - M: Mute selected Track\n" " - S: Solo selected Track\n" " - U: Unmute all Tracks\n" " - N: Rename the selected song in the playlisy\n" " - E: Export selected songs to individual track files (to \"workdirectory/wav\")\n" " - R: Export selected songs to files (non-split)\n" " - B: Benchmark, Run the export program but don't write to file\n" " - Q or Ctrl-D: Exit Program\n" << std::flush; }
3,990
C++
.cpp
108
29.666667
93
0.572056
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,656
Rom.cpp
ipatix_agbplay/src/Rom.cpp
#include <string> #include <cstdio> #include <cstring> #include <fstream> #include "Rom.h" #include "Xcept.h" #include "Debug.h" #include "Util.h" std::unique_ptr<Rom> Rom::global_instance; /* * public */ Rom::Rom(const std::filesystem::path& filePath) { loadFile(filePath); verify(); } void Rom::CreateInstance(const std::filesystem::path& filePath) { global_instance = std::make_unique<Rom>(filePath); } std::string Rom::ReadString(size_t pos, size_t limit) const { std::string result; for (size_t i = 0; i < limit; i++) { char c = static_cast<char>(data.at(pos + i)); if (c == '\0') break; result += c; } return result; } std::string Rom::GetROMCode() const { return ReadString(0xAC, 4); } /* * private */ void Rom::verify() { // check ROM size if (data.size() > AGB_ROM_SIZE || data.size() < 0x200) throw Xcept("Illegal ROM size"); // Logo data // TODO replace 1 to 1 logo comparison with checksum uint8_t imageBytes[] = { 0x24,0xff,0xae,0x51,0x69,0x9a,0xa2,0x21,0x3d,0x84,0x82,0x0a,0x84,0xe4,0x09,0xad, 0x11,0x24,0x8b,0x98,0xc0,0x81,0x7f,0x21,0xa3,0x52,0xbe,0x19,0x93,0x09,0xce,0x20, 0x10,0x46,0x4a,0x4a,0xf8,0x27,0x31,0xec,0x58,0xc7,0xe8,0x33,0x82,0xe3,0xce,0xbf, 0x85,0xf4,0xdf,0x94,0xce,0x4b,0x09,0xc1,0x94,0x56,0x8a,0xc0,0x13,0x72,0xa7,0xfc, 0x9f,0x84,0x4d,0x73,0xa3,0xca,0x9a,0x61,0x58,0x97,0xa3,0x27,0xfc,0x03,0x98,0x76, 0x23,0x1d,0xc7,0x61,0x03,0x04,0xae,0x56,0xbf,0x38,0x84,0x00,0x40,0xa7,0x0e,0xfd, 0xff,0x52,0xfe,0x03,0x6f,0x95,0x30,0xf1,0x97,0xfb,0xc0,0x85,0x60,0xd6,0x80,0x25, 0xa9,0x63,0xbe,0x03,0x01,0x4e,0x38,0xe2,0xf9,0xa2,0x34,0xff,0xbb,0x3e,0x03,0x44, 0x78,0x00,0x90,0xcb,0x88,0x11,0x3a,0x94,0x65,0xc0,0x7c,0x63,0x87,0xf0,0x3c,0xaf, 0xd6,0x25,0xe4,0x8b,0x38,0x0a,0xac,0x72,0x21,0xd4,0xf8,0x07 }; // check logo for (size_t i = 0; i < sizeof(imageBytes); i++) { if (imageBytes[i] != data.at(i + 0x4)) throw Xcept("ROM verification: Bad Nintendo Logo"); } // check checksum uint8_t checksum = data.at(0xBD); int check = 0; for (size_t i = 0xA0; i < 0xBD; i++) { check -= data.at(i); } check = (check - 0x19) & 0xFF; if (check != checksum) throw Xcept("ROM verification: Bad Header Checksum: %02X - expected %02X", (int)checksum, (int)check); } void Rom::loadFile(const std::filesystem::path& filePath) { std::ifstream is(filePath, std::ios_base::binary); if (!is.is_open()) { throw Xcept("Error while opening ROM: %s", strerror(errno)); } is.seekg(0, std::ios_base::end); std::ifstream::pos_type size = is.tellg(); if (size == -1) { throw Xcept("Error while seeking in input file"); } if (size > AGB_ROM_SIZE) { throw Xcept("Input ROM exceeds 32 MiB file limit"); } is.seekg(0, std::ios_base::beg); data.resize(static_cast<size_t>(size)); // copy file to memory is.read(reinterpret_cast<char *>(data.data()), size); if (is.bad()) throw Xcept("read bad"); if (is.fail()) { throw Xcept("read fail"); } is.close(); }
3,221
C++
.cpp
98
27.918367
110
0.637359
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,657
VUMeterGUI.cpp
ipatix_agbplay/src/VUMeterGUI.cpp
#include <string> #include <cstring> #include <cmath> #include <algorithm> #include "VUMeterGUI.h" #include "ColorDef.h" #include "Util.h" #include "Xcept.h" #include "Debug.h" /* * public VUMeterGUI */ VUMeterGUI::VUMeterGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) : CursesWin(height, width, yPos, xPos) { if (width < 10) throw Xcept("Can't create too narrow VU meters"); meterWidth = int(width - 2); meterRed = meterWidth * 7 / 8; meterYel = meterWidth * 6 / 8; vuLevelLeft = 0.0f; vuLevelRight = 0.0f; update(); } VUMeterGUI::~VUMeterGUI() { } void VUMeterGUI::Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) { CursesWin::Resize(height, width, yPos, xPos); if (width < 10) throw Xcept("Can't create too narrow VU meters"); meterWidth = int(width - 2); meterRed = meterWidth * 7 / 8; meterYel = meterWidth * 6 / 8; update(); } void VUMeterGUI::SetVol(float left, float right) { //vuLevelLeft = left <= 0.0f ? 0.0f : max(log2f(left) * (1.0f / 6.0f) + 1.0f, 0.0f); //vuLevelRight = right <= 0.0f ? 0.0f : max(log2f(left) * (1.0f / 6.0f) + 1.0f, 0.0f); vuLevelLeft = left; vuLevelRight = right; update(); } void VUMeterGUI::update() { char line[(meterWidth + 2) * strlen("\u250f") + 1]; size_t currentLinePos = 0; float levelFactor = std::clamp(0.8f * float(meterWidth), 0.0f, float(meterWidth)); // TOP BORDER CStrAppend(line, &currentLinePos, "\u250f"); for (int i = 0; i < meterWidth; i++) { CStrAppend(line, &currentLinePos, "\u2501"); } CStrAppend(line, &currentLinePos, "\u2513"); line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME))); mvwprintw(winPtr, 0, 0, "%s", line); // FIRST BAR float leftLevel = vuLevelLeft * levelFactor; int bLeftLevel = int(leftLevel); mvwprintw(winPtr, 1, 0, "\u2503"); currentLinePos = 0; for (int i = 0; i < meterYel; i++) { if (i < bLeftLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_LOW))); wprintw(winPtr, "%s", line); currentLinePos = 0; for (int i = meterYel; i < meterRed; i++) { if (i < bLeftLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_MID))); wprintw(winPtr, "%s", line); currentLinePos = 0; for (int i = meterRed; i < meterWidth; i++) { if (i < bLeftLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_HIGH))); wprintw(winPtr, "%s", line); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME))); wprintw(winPtr, "\u2503"); // MIDDLE BORDER currentLinePos = 0; CStrAppend(line, &currentLinePos, "\u2523"); for (int i = 0; i < meterWidth; i++) { CStrAppend(line, &currentLinePos, "\u2501"); } CStrAppend(line, &currentLinePos, "\u252b"); line[currentLinePos] = '\0'; mvwprintw(winPtr, 2, 0, "%s", line); // SECOND BAR float rightLevel = vuLevelRight * levelFactor; int bRightLevel = int(rightLevel); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME))); mvwprintw(winPtr, 3, 0, "\u2503"); currentLinePos = 0; for (int i = 0; i < meterYel; i++) { if (i < bRightLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_LOW))); wprintw(winPtr, "%s", line); currentLinePos = 0; for (int i = meterYel; i < meterRed; i++) { if (i < bRightLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_MID))); wprintw(winPtr, "%s", line); currentLinePos = 0; for (int i = meterRed; i < meterWidth; i++) { if (i < bRightLevel) { CStrAppend(line, &currentLinePos, "\u2588"); } else { CStrAppend(line, &currentLinePos, "\u2591"); } } line[currentLinePos] = '\0'; wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::VU_HIGH))); wprintw(winPtr, "%s", line); wattrset(winPtr, COLOR_PAIR(static_cast<int>(Color::WINDOW_FRAME))); wprintw(winPtr, "\u2503"); // BOTTOM BORDER currentLinePos = 0; CStrAppend(line, &currentLinePos, "\u2523"); for (int i = 0; i < meterWidth; i++) { CStrAppend(line, &currentLinePos, "\u2501"); } CStrAppend(line, &currentLinePos, "\u252b"); line[currentLinePos] = '\0'; mvwprintw(winPtr, 4, 0, "%s", line); wrefresh(winPtr); }
5,351
C++
.cpp
158
28.221519
90
0.604871
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,658
Types.cpp
ipatix_agbplay/src/Types.cpp
#include "Types.h" ReverbType str2rev(const std::string& str) { if (str == "gs1") return ReverbType::GS1; else if (str == "gs2") return ReverbType::GS2; else if (str == "mgat") return ReverbType::MGAT; else if (str == "test") return ReverbType::TEST; else if (str == "none") return ReverbType::NONE; return ReverbType::NORMAL; } std::string rev2str(ReverbType t) { if (t == ReverbType::GS1) return "gs1"; else if (t == ReverbType::GS2) return "gs2"; else if (t == ReverbType::MGAT) return "mgat"; else if (t == ReverbType::TEST) return "test"; else if (t == ReverbType::NONE) return "none"; return "normal"; } ResamplerType str2res(const std::string& str) { if (str == "nearest") return ResamplerType::NEAREST; else if (str == "linear") return ResamplerType::LINEAR; else if (str == "sinc") return ResamplerType::SINC; else if (str == "blep") return ResamplerType::BLEP; else if (str == "blamp") return ResamplerType::BLAMP; return ResamplerType::LINEAR; } std::string res2str(ResamplerType t) { if (t == ResamplerType::NEAREST) return "nearest"; else if (t == ResamplerType::LINEAR) return "linear"; else if (t == ResamplerType::SINC) return "sinc"; else if (t == ResamplerType::BLEP) return "blep"; else if (t == ResamplerType::BLAMP) return "blamp"; return "linear"; } CGBPolyphony str2cgbPoly(const std::string& str) { if (str == "mono-strict") return CGBPolyphony::MONO_STRICT; else if (str == "mono-smooth") return CGBPolyphony::MONO_SMOOTH; else if (str == "poly") return CGBPolyphony::POLY; return CGBPolyphony::MONO_STRICT; } std::string cgbPoly2str(CGBPolyphony t) { if (t == CGBPolyphony::MONO_STRICT) return "mono-strict"; else if (t == CGBPolyphony::MONO_SMOOTH) return "mono-smooth"; else if (t == CGBPolyphony::POLY) return "poly"; return "mono-strict"; } /* * ADSR */ ADSR::ADSR(uint8_t att, uint8_t dec, uint8_t sus, uint8_t rel) { this->att = att; this->dec = dec; this->sus = sus; this->rel = rel; } ADSR::ADSR() { this->att = 0xFF; this->dec = 0x00; this->sus = 0xFF; this->rel = 0x00; } /* * public SampleInfo */ SampleInfo::SampleInfo(const int8_t *samplePtr, float midCfreq, bool loopEnabled, uint32_t loopPos, uint32_t endPos) { this->samplePtr = samplePtr; this->midCfreq = midCfreq; this->loopPos = loopPos; this->endPos = endPos; this->loopEnabled = loopEnabled; } SampleInfo::SampleInfo() { } /* * public EnginePars */ EnginePars::EnginePars(uint8_t vol, uint8_t rev, uint8_t freq) { this->vol = vol; this->rev = rev; this->freq = freq; }
2,887
C++
.cpp
116
20.267241
116
0.620602
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,659
SoundData.cpp
ipatix_agbplay/src/SoundData.cpp
#include <cstring> #include <iostream> #include <cassert> #include <algorithm> #include "AgbTypes.h" #include "SoundData.h" #include "Xcept.h" #include "Debug.h" #include "Util.h" #include "Rom.h" /* * public SoundBank */ void SoundBank::Init(size_t bankPos) { this->bankPos = bankPos; } InstrType SoundBank::GetInstrType(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); size_t pos = instrPos(instrNum, midiKey); switch (rom.ReadU8(pos + 0x0)) { case 0x0: return InstrType::PCM; case 0x1: return InstrType::SQ1; case 0x2: return InstrType::SQ2; case 0x3: return InstrType::WAVE; case 0x4: return InstrType::NOISE; case 0x8: return InstrType::PCM_FIXED; case 0x9: return InstrType::SQ1; case 0xA: return InstrType::SQ2; case 0xB: return InstrType::WAVE; case 0xC: return InstrType::NOISE; default: return InstrType::INVALID; } } uint8_t SoundBank::GetMidiKey(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); if (rom.ReadU8(bankPos + instrNum * 12 + 0) == 0x80) { size_t subBankPos = rom.ReadAgbPtrToPos(bankPos + instrNum * 12 + 0x4); return rom.ReadU8(subBankPos + midiKey * 12 + 1); } else { return midiKey; } } int8_t SoundBank::GetPan(uint8_t instrNum, uint8_t midiKey) { size_t pos = instrPos(instrNum, midiKey); // not strictly correct, pan should only be set for drum table instruments InstrType t = GetInstrType(instrNum, midiKey); if (t != InstrType::PCM && t != InstrType::PCM_FIXED) return 0; uint8_t pan = Rom::Instance().ReadU8(pos + 3); if (pan & 0x80) return static_cast<int8_t>(pan - 0xC0); else return 0; } uint8_t SoundBank::GetSweep(uint8_t instrNum, uint8_t midiKey) { size_t pos = instrPos(instrNum, midiKey); InstrType t = GetInstrType(instrNum, midiKey); if (t != InstrType::SQ1) throw Xcept("SoundBank Error: Invalid use of sweep at non SQ1 instrument: [%08X]", pos); return Rom::Instance().ReadU8(pos + 3); } CGBDef SoundBank::GetCGBDef(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); CGBDef def; size_t pos = instrPos(instrNum, midiKey); InstrType t = GetInstrType(instrNum, midiKey); if (t == InstrType::SQ1 || t == InstrType::SQ2) { uint32_t dutyCycle = rom.ReadU32(pos + 4); switch (dutyCycle) { case 0: def.wd = WaveDuty::D12; break; case 1: def.wd = WaveDuty::D25; break; case 2: def.wd = WaveDuty::D50; break; case 3: def.wd = WaveDuty::D75; break; default: throw Xcept("SoundBank Error: Invalid square wave duty cycle at [%08X+4]=%08X", pos, dutyCycle); } } else if (t == InstrType::WAVE) { def.wavePtr = static_cast<const uint8_t *>(rom.GetPtr(rom.ReadAgbPtrToPos(pos + 4))); } else if (t == InstrType::NOISE) { uint32_t noisePatt = rom.ReadU32(pos + 4); switch (noisePatt) { case 0: def.np = NoisePatt::FINE; break; case 1: def.np = NoisePatt::ROUGH; break; default: throw Xcept("SoundBank Error: Invalid noise pattern at [%08X+4]=%08X", pos, noisePatt); } } else { throw Xcept("SoundBank Error: Cannot get CGB definition of instrument: [%08X]", pos); } return def; } SampleInfo SoundBank::GetSampInfo(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); size_t pos = instrPos(instrNum, midiKey); InstrType t = GetInstrType(instrNum, midiKey); if (t != InstrType::PCM && t != InstrType::PCM_FIXED) throw Xcept("SoundBank Error: Cannot get sample info of non PCM instrument: [%08X]", pos); size_t samplePos = rom.ReadAgbPtrToPos(pos + 4); bool loopEnabled = rom.ReadU8(samplePos + 3) & 0xC0; if (rom.ReadU8(samplePos) != 0) throw Xcept("Sample Error: Unknown/unsupported sample mode: [%08X]=%02X, instrument: [%08X]", samplePos, rom.ReadU8(samplePos), pos); float midCfreq = static_cast<float>(rom.ReadU32(samplePos + 4)) / 1024.0f; uint32_t loopPos = rom.ReadU32(samplePos + 8); uint32_t endPos = rom.ReadU32(samplePos + 12); const int8_t *samplePtr = static_cast<const int8_t *>(rom.GetPtr(samplePos + 16)); return SampleInfo(samplePtr, midCfreq, loopEnabled, loopPos, endPos); } ADSR SoundBank::GetADSR(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); size_t pos = instrPos(instrNum, midiKey); InstrType t = GetInstrType(instrNum, midiKey); if (t == InstrType::INVALID) throw Xcept("SoundBank Error: Cannot get ADSR for unknown instrument type: [%08X]", pos); ADSR adsr; adsr.att = rom.ReadU8(pos + 8); adsr.dec = rom.ReadU8(pos + 9); adsr.sus = rom.ReadU8(pos + 10); adsr.rel = rom.ReadU8(pos + 11); return adsr; } size_t SoundBank::instrPos(uint8_t instrNum, uint8_t midiKey) { Rom& rom = Rom::Instance(); uint8_t type = rom.ReadU8(bankPos + instrNum * 12 + 0x0); if (type == 0x80) { size_t subBankPos = rom.ReadAgbPtrToPos(bankPos + instrNum * 12 + 0x4); return subBankPos + midiKey * 12; } else if (type == 0x40) { size_t subBankPos = rom.ReadAgbPtrToPos(bankPos + instrNum * 12 + 0x4); size_t keyMapPos = rom.ReadAgbPtrToPos(bankPos + instrNum * 12 + 0x8); return subBankPos + rom.ReadU8(keyMapPos + midiKey) * 12; } else { return bankPos + instrNum * 12; } } /* * public Sequence */ Sequence::Sequence(uint8_t trackLimit) : memaccArea(256), trackLimit(trackLimit) { Init(0); } void Sequence::Init(size_t songHeaderPos) { Rom& rom = Rom::Instance(); this->songHeaderPos = songHeaderPos; tracks.clear(); if (songHeaderPos != 0) { // read song header size_t nTracks = std::min<uint8_t>(rom.ReadU8(songHeaderPos + 0), trackLimit); // read track pointers for (size_t i = 0; i < nTracks; i++) tracks.emplace_back(rom.ReadAgbPtrToPos(songHeaderPos + 8 + 4 * i)); } // reset runtime variables bpmStack = 0; bpm = 150; tickCount = 0; } void Sequence::Reset() { Init(songHeaderPos); } size_t Sequence::GetSoundBankPos() { if (songHeaderPos == 0) return 0; Rom& rom = Rom::Instance(); /* Sometimes songs have 0 tracks and will not have a valid * sound bank pointer. Return a dummy result instead since * it should not be accessed anyway */ if (!rom.ValidPointer(rom.ReadU32(songHeaderPos + 4))) return 0; return rom.ReadAgbPtrToPos(songHeaderPos + 4); } uint8_t Sequence::GetReverb() const { if (songHeaderPos == 0) return 0; return Rom::Instance().ReadU8(songHeaderPos + 3); } uint8_t Sequence::GetPriority() const { if (songHeaderPos == 0) return 0; return Rom::Instance().ReadU8(songHeaderPos + 2); } size_t Sequence::GetSongHeaderPos() const { return songHeaderPos; } /* * public * Track */ Track::Track(size_t pos) : pos(pos) { } int16_t Track::GetPitch() { int p = tune + bend * bendr + keyShift * 64; if (modt == MODT::PITCH) p += lfoValue * 4; return static_cast<int16_t>(p); } uint16_t Track::GetVol() { int32_t v = vol << 1; if (modt == MODT::VOL) v = (v * (lfoValue + 128)) >> 7; return static_cast<uint16_t>(v); } int16_t Track::GetPan() { int p = pan << 1; if (modt == MODT::PAN) p += lfoValue; return static_cast<int16_t>(p); } void Track::ResetLfoValue() { lfoValue = 0; lfoPhase = 0; if (modt == MODT::PITCH) updatePitch = true; else updateVolume = true; } /* * public * SongTable */ std::vector<SongTable> SongTable::ScanForTables() { Rom& rom = Rom::Instance(); std::vector<SongTable> tables; for (size_t i = 0x200; i < rom.Size(); i += 4) { bool validEntries = true; size_t location = i; size_t j = 0; for (j = 0; j < MIN_SONG_NUM; j++) { if (!validateTableEntry(i + j * 8)) { i += j * 8; validEntries = false; break; } } if (validEntries) { // before returning, check if reference to song table exists for (size_t k = 0x200; k < rom.Size() - 3; k += 4) { // -3 due to possible alignment issues size_t value = rom.ReadU32(k) - AGB_MAP_ROM; if (value == location) { SongTable songTable(location); j = songTable.GetNumSongs(); tables.push_back(songTable); break; } } i += j * 8; } } if (tables.size() == 0) { throw Xcept("Unable to find songtable"); } return tables; } SongTable::SongTable(size_t songTablePos) : songTablePos(songTablePos) { numSongs = determineNumSongs(); } size_t SongTable::GetSongTablePos() { return songTablePos; } size_t SongTable::GetPosOfSong(uint16_t uid) { return Rom::Instance().ReadAgbPtrToPos(songTablePos + uid * 8); } size_t SongTable::GetNumSongs() { return numSongs; } /* * private */ bool SongTable::validateTableEntry(size_t pos) { Rom& rom = Rom::Instance(); // check if the pointer is actually valid uint32_t songPtr = rom.ReadU32(pos); if (!rom.ValidPointer(songPtr)) return false; // check if the song groups are set appropriately uint8_t g1 = rom.ReadU8(pos + 4); uint8_t z1 = rom.ReadU8(pos + 5); uint8_t g2 = rom.ReadU8(pos + 6); uint8_t z2 = rom.ReadU8(pos + 7); if (z1 != 0 || z2 != 0 || g1 != g2) return false; // now check if the pointer points to a valid song if (!validateSong(rom.ReadAgbPtrToPos(pos))) return false; return true; } bool SongTable::validateSong(size_t songPos) { Rom& rom = Rom::Instance(); uint8_t nTracks = rom.ReadU8(songPos + 0); uint8_t nBlocks = rom.ReadU8(songPos + 1); // these could be anything uint8_t prio = rom.ReadU8(songPos + 2); uint8_t rev = rom.ReadU8(songPos + 3); if ((nTracks | nBlocks | prio | rev) == 0) return true; // verify voicegroup pointer uint32_t voicePtr = rom.ReadU32(songPos + 4); if (!rom.ValidPointer(voicePtr)) return false; // verify track pointers for (uint32_t i = 0; i < nTracks; i++) { uint32_t trackPtr = rom.ReadU32(songPos + 8 + (i * 4)); if (!rom.ValidPointer(trackPtr)) return false; } return true; } size_t SongTable::determineNumSongs() { size_t pos = songTablePos; size_t count = 0; while (true) { if (!validateTableEntry(pos)) break; count++; pos += 8; } return count; }
10,912
C++
.cpp
356
25.160112
108
0.619552
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,660
SoundMixer.cpp
ipatix_agbplay/src/SoundMixer.cpp
#include <algorithm> #include <cmath> #include <cassert> #include "SoundMixer.h" #include "Xcept.h" #include "Debug.h" #include "Util.h" #include "ConfigManager.h" #include "PlayerContext.h" /* * public SoundMixer */ SoundMixer::SoundMixer(PlayerContext& ctx, uint32_t sampleRate, float masterVolume) : ctx(ctx), sampleRate(sampleRate), masterVolume(masterVolume) { } void SoundMixer::Init(uint32_t fixedModeRate, uint8_t reverb, float pcmMasterVolume, ReverbType rtype, uint8_t numTracks) { this->fixedModeRate = fixedModeRate; this->samplesPerBuffer = sampleRate / (AGB_FPS * INTERFRAMES); this->numTracks = numTracks; this->pcmMasterVolume = pcmMasterVolume; GameConfig& gameCfg = ConfigManager::Instance().GetCfg(); revdsps.resize(numTracks); for (size_t i = 0; i < numTracks; i++) { switch (rtype) { case ReverbType::NORMAL: revdsps[i] = std::make_unique<ReverbEffect>( reverb, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS))); break; case ReverbType::NONE: revdsps[i] = std::make_unique<ReverbEffect>( 0, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS))); break; case ReverbType::GS1: revdsps[i] = std::make_unique<ReverbGS1>( reverb, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS))); break; case ReverbType::GS2: revdsps[i] = std::make_unique<ReverbGS2>( reverb, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS)), 0.4140625f, -0.0625f); break; // Mario Power Tennis uses same coefficients as Mario Golf Advance Tour case ReverbType::MGAT: revdsps[i] = std::make_unique<ReverbGS2>( reverb, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS)), 0.25f, -0.046875f); break; case ReverbType::TEST: revdsps[i] = std::make_unique<ReverbTest>( reverb, sampleRate, uint8_t(gameCfg.GetRevBufSize() / (fixedModeRate / AGB_FPS))); break; default: throw Xcept("Invalid Reverb Effect"); } } } void SoundMixer::Process(std::vector<std::vector<sample>>& outputBuffers) { /* 1. match number of output buffers to the number of tracks we have */ if (outputBuffers.size() != numTracks) { outputBuffers.resize(numTracks, std::vector<sample>(samplesPerBuffer)); } /* 2. clear the mixing buffer before processing channels */ for (auto& outputBuffer : outputBuffers) { assert(outputBuffer.size() == samplesPerBuffer); std::fill(outputBuffer.begin(), outputBuffer.end(), sample{0.0f, 0.0f}); } /* 3. prepare arguments for mixing */ MixingArgs margs; margs.vol = pcmMasterVolume; margs.fixedModeRate = fixedModeRate; margs.sampleRateInv = 1.0f / static_cast<float>(sampleRate); margs.samplesPerBufferInv= 1.0f / static_cast<float>(samplesPerBuffer); margs.curInterFrame = ctx.GetCurInterFrame(); /* 4. mix channels which are affected by reverb (PCM only) */ for (auto& chn : ctx.sndChannels) { assert(chn.GetTrackIdx() < numTracks); chn.Process(outputBuffers[chn.GetTrackIdx()].data(), samplesPerBuffer, margs); } /* 5. apply reverb */ assert(revdsps.size() == numTracks); for (size_t i = 0; i < outputBuffers.size(); i++) revdsps[i]->ProcessData(outputBuffers[i].data(), samplesPerBuffer); /* 6. mix channels which are not affected by reverb (CGB) */ for (auto& chn : ctx.sq1Channels) { assert(chn.GetTrackIdx() < numTracks); chn.Process(outputBuffers[chn.GetTrackIdx()].data(), samplesPerBuffer, margs); } for (auto& chn : ctx.sq2Channels) { assert(chn.GetTrackIdx() < numTracks); chn.Process(outputBuffers[chn.GetTrackIdx()].data(), samplesPerBuffer, margs); } for (auto& chn : ctx.waveChannels) { assert(chn.GetTrackIdx() < numTracks); chn.Process(outputBuffers[chn.GetTrackIdx()].data(), samplesPerBuffer, margs); } for (auto& chn : ctx.noiseChannels) { assert(chn.GetTrackIdx() < numTracks); chn.Process(outputBuffers[chn.GetTrackIdx()].data(), samplesPerBuffer, margs); } /* 7. clean up all stopped channels */ ctx.sndChannels.remove_if([](const auto& chn) { return chn.GetState() == EnvState::DEAD; }); ctx.sq1Channels.remove_if([](const auto& chn) { return chn.GetState() == EnvState::DEAD; }); ctx.sq2Channels.remove_if([](const auto& chn) { return chn.GetState() == EnvState::DEAD; }); ctx.waveChannels.remove_if([](const auto& chn) { return chn.GetState() == EnvState::DEAD; }); ctx.noiseChannels.remove_if([](const auto& chn) { return chn.GetState() == EnvState::DEAD; }); /* 8. apply fadeout if active */ float masterFrom = masterVolume; float masterTo = masterVolume; if (fadeMicroframesLeft > 0) { if (fadePos < 0.f) { masterFrom = 0.f; } else { masterFrom *= powf(fadePos, 10.0f / 6.0f); } fadePos += fadeStepPerMicroframe; if (fadePos < 0.f) { masterTo = 0.f; } else { masterTo *= powf(fadePos, 10.0f / 6.0f); } fadeMicroframesLeft--; } for (auto& outputBuffer : outputBuffers) { float masterStep = (masterTo - masterFrom) * margs.samplesPerBufferInv; float masterLevel = masterFrom; for (size_t i = 0; i < samplesPerBuffer; i++) { outputBuffer[i].left *= masterLevel; outputBuffer[i].right *= masterLevel; masterLevel += masterStep; } } } size_t SoundMixer::GetSamplesPerBuffer() const { return samplesPerBuffer; } uint32_t SoundMixer::GetSampleRate() const { return sampleRate; } void SoundMixer::ResetFade() { fadePos = 0.0f; fadeMicroframesLeft = 0; } void SoundMixer::StartFadeOut(float millis) { fadePos = 1.0f; fadeMicroframesLeft = size_t(millis / 1000.0f * float(AGB_FPS * INTERFRAMES)); fadeStepPerMicroframe = -1.0f / float(fadeMicroframesLeft); } void SoundMixer::StartFadeIn(float millis) { fadePos = 0.0f; fadeMicroframesLeft = size_t(millis / 1000.0f * float(AGB_FPS * INTERFRAMES)); fadeStepPerMicroframe = 1.0f / float(fadeMicroframesLeft); } bool SoundMixer::IsFadeDone() const { return fadeMicroframesLeft == 0; }
6,622
C++
.cpp
166
33.036145
121
0.642524
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,661
PlayerContext.cpp
ipatix_agbplay/src/PlayerContext.cpp
#include "PlayerContext.h" #include "ConfigManager.h" PlayerContext::PlayerContext(int8_t maxLoops, uint8_t maxTracks, EnginePars pars) : reader(*this, maxLoops), mixer(*this, STREAM_SAMPLERATE, 1.0f), seq(maxTracks), pars(pars) { } void PlayerContext::Process(std::vector<std::vector<sample>>& trackAudio) { reader.Process(); mixer.Process(trackAudio); curInterFrame++; } void PlayerContext::InitSong(size_t songHeaderPos) { GameConfig& cfg = ConfigManager::Instance().GetCfg(); sndChannels.clear(); sq1Channels.clear(); sq2Channels.clear(); waveChannels.clear(); noiseChannels.clear(); curInterFrame = 0; seq.Init(songHeaderPos); bnk.Init(seq.GetSoundBankPos()); reader.Restart(); mixer.ResetFade(); uint32_t fixedModeRate = reader.freqLut.at(cfg.GetEngineFreq() - 1); uint8_t reverb = 0; if (seq.GetReverb() & 0x80) reverb = seq.GetReverb() & 0x7F; else if (cfg.GetEngineRev() & 0x80) reverb = cfg.GetEngineRev() & 0x7F; float pcmMasterVolume = static_cast<float>(cfg.GetPCMVol() + 1) / 16.0f; auto reverbType = cfg.GetRevType(); uint8_t numTracks = static_cast<uint8_t>(seq.tracks.size()); mixer.Init(fixedModeRate, reverb, pcmMasterVolume, reverbType, numTracks); } bool PlayerContext::HasEnded() const { return reader.EndReached() && mixer.IsFadeDone(); } size_t PlayerContext::GetCurInterFrame() const { return curInterFrame; }
1,460
C++
.cpp
44
29.340909
96
0.710021
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
752,662
Ringbuffer.cpp
ipatix_agbplay/src/Ringbuffer.cpp
#include <algorithm> #include "Ringbuffer.h" /* * public Ringbuffer */ Ringbuffer::Ringbuffer(size_t elementCount) : bufData(elementCount), freeCount(elementCount) { } void Ringbuffer::Put(sample *inData, size_t nElements) { std::unique_lock<std::mutex> lock(countLock); while (freeCount < nElements){ sig.wait(lock); } while (nElements > 0) { size_t count = putChunk(inData, nElements); inData += count; nElements -= count; } } void Ringbuffer::Take(sample *outData, size_t nElements) { if (dataCount < nElements) { // underrun std::fill(outData, outData + nElements, sample{0.0f, 0.0f}); } else { // output std::unique_lock<std::mutex> lock(countLock); while (nElements > 0) { size_t count = takeChunk(outData, nElements); outData += count; nElements -= count; } sig.notify_one(); } } void Ringbuffer::Clear() { std::unique_lock<std::mutex> lock(countLock); std::fill(bufData.begin(), bufData.end(), sample{0.0f, 0.0f}); freePos = 0; dataPos = 0; freeCount = bufData.size(); dataCount = 0; } /* * private Ringbuffer */ size_t Ringbuffer::putChunk(sample *inData, size_t nElements) { bool wrap = nElements >= bufData.size() - freePos; size_t count; size_t newfree; if (wrap) { count = size_t(bufData.size() - freePos); newfree = 0; } else { count = nElements; newfree = freePos + count; } std::copy(inData, inData + count, &bufData[freePos]); freePos = newfree; freeCount -= count; dataCount += count; return count; } size_t Ringbuffer::takeChunk(sample *outData, size_t nElements) { bool wrap = nElements >= bufData.size() - dataPos; size_t count; size_t newdata; if (wrap) { count = size_t(bufData.size() - dataPos); newdata = 0; } else { count = nElements; newdata = dataPos + count; } std::copy(&bufData[dataPos], &bufData[dataPos] + count, outData); dataPos = newdata; freeCount += count; dataCount -= count; return count; }
2,180
C++
.cpp
85
20.541176
69
0.612656
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
752,663
LoudnessCalculator.h
ipatix_agbplay/src/LoudnessCalculator.h
#pragma once #include <cstddef> #include "Types.h" class LoudnessCalculator { public: LoudnessCalculator(const float lowpassFreq); LoudnessCalculator(const LoudnessCalculator&) = delete; LoudnessCalculator(LoudnessCalculator&&) = default; LoudnessCalculator& operator=(const LoudnessCalculator&) = delete; void CalcLoudness(const sample *audio, size_t numSamples); void GetLoudness(float& lVol, float& rVol); void Reset(); private: static float calcAlpha(float lowpassFreq); float lpAlpha; float avgVolLeftSq = 0.0f; float avgVolRightSq = 0.0f; float volLeft = 0.0f; float volRight = 0.0f; };
651
C++
.h
21
27.238095
70
0.746795
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,664
OS.h
ipatix_agbplay/src/OS.h
#pragma once #include <string> #include <filesystem> namespace OS { void LowerThreadPriority(); void CheckTerminal(); const std::filesystem::path GetMusicDirectory(); const std::filesystem::path GetLocalConfigDirectory(); const std::filesystem::path GetGlobalConfigDirectory(); };
303
C++
.h
10
27.1
59
0.75945
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,665
PlayerInterface.h
ipatix_agbplay/src/PlayerInterface.h
#pragma once #include <cstdint> #include <vector> #include <thread> #include <memory> #include <portaudio.h> #include "TrackviewGUI.h" #include "DisplayContainer.h" #include "Constants.h" #include "GameConfig.h" #include "Ringbuffer.h" #include "LoudnessCalculator.h" #include "PlayerContext.h" class PlayerInterface { public: PlayerInterface(TrackviewGUI& trackUI, size_t initSongPos); PlayerInterface(const PlayerInterface&) = delete; PlayerInterface& operator=(const PlayerInterface&) = delete; ~PlayerInterface(); void LoadSong(size_t songPos); void Play(); void Pause(); void Stop(); void SpeedDouble(); void SpeedHalve(); bool IsPlaying(); bool IsPaused() const; void UpdateView(); void ToggleMute(size_t index); void Mute(size_t index, bool mute); size_t GetMaxTracks() { return mutedTracks.size(); } void GetMasterVolLevels(float& left, float& right); SongInfo GetSongInfo() const; private: void initContext(); void threadWorker(); static int audioCallback(const void *inputBuffer, void *outputBuffer, size_t framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData); void setupLoudnessCalcs(); void portaudioOpen(); void portaudioClose(); static const std::vector<PaHostApiTypeId> hostApiPriority; PaStream *audioStream; uint32_t speedFactor = 64; volatile enum class State : int { RESTART, PLAYING, PAUSED, TERMINATED, SHUTDOWN, THREAD_DELETED } playerState = State::THREAD_DELETED; std::unique_ptr<PlayerContext> ctx; TrackviewGUI& trackUI; Ringbuffer rBuf{STREAM_BUF_SIZE}; LoudnessCalculator masterLoudness{10.0f}; std::vector<LoudnessCalculator> trackLoudness; std::vector<bool> mutedTracks; std::unique_ptr<std::thread> playerThread; };
1,891
C++
.h
57
28.894737
97
0.731908
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,666
SongEntry.h
ipatix_agbplay/src/SongEntry.h
#pragma once #include <cstdint> #include <string> class SongEntry { public: SongEntry(const std::string& name, uint16_t uid); const std::string& GetName() const; uint16_t GetUID() const; std::string name; private: uint16_t uid; };
256
C++
.h
13
16.769231
53
0.702929
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,667
SonglistGUI.h
ipatix_agbplay/src/SonglistGUI.h
#pragma once #include <cstdint> #include <string> #include <vector> #include "CursesWin.h" #include "SongEntry.h" class SonglistGUI : public CursesWin { public: SonglistGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos, bool upd); virtual ~SonglistGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; virtual void AddSong(SongEntry song); virtual void RemoveSong(); virtual void ClearSongs(); virtual SongEntry *GetSong(); void Enter(); virtual void Leave(); void ScrollDown(); void ScrollUp(); void PageDown(); void PageUp(); bool IsLast() const; protected: virtual void scrollDownNoUpdate(); virtual void scrollUpNoUpdate(); void update() override; void checkDimensions(uint32_t height, uint32_t width); uint32_t viewPos; uint32_t cursorPos; uint32_t contentHeight; uint32_t contentWidth; bool cursorVisible; private: std::vector<SongEntry> songlist; };
1,020
C++
.h
36
24.555556
89
0.720693
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,668
HotkeybarGUI.h
ipatix_agbplay/src/HotkeybarGUI.h
#pragma once #include "CursesWin.h" class HotkeybarGUI : public CursesWin { public: HotkeybarGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~HotkeybarGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; private: void update() override; };
328
C++
.h
10
29.8
88
0.745223
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,669
ConfigManager.h
ipatix_agbplay/src/ConfigManager.h
#pragma once #include <vector> #include <string> #include <filesystem> #include "GameConfig.h" class ConfigManager { public: static ConfigManager& Instance(); GameConfig& GetCfg(); const GameConfig& GetCfg() const; void SetGameCode(const std::string& gameCode); void Load(); void Save(); const std::filesystem::path& GetWavOutputDir(); CGBPolyphony GetCgbPolyphony() const; void SetCgbPolyphony(CGBPolyphony value); int8_t GetMaxLoopsPlaylist() const; void SetMaxLoopsPlaylist(int8_t value); int8_t GetMaxLoopsExport() const; void SetMaxLoopsExport(int8_t value); double GetPadSecondsStart() const; void SetPadSecondsStart(double value); double GetPadSecondsEnd() const; void SetPadSecondsEnd(double value); private: ConfigManager() = default; ConfigManager(const ConfigManager&) = delete; ConfigManager& operator=(const ConfigManager&) = delete; std::vector<GameConfig> configs; std::filesystem::path confWavOutputDir; CGBPolyphony confCgbPolyphony; int8_t maxLoopsPlaylist; int8_t maxLoopsExport; std::filesystem::path configPath; GameConfig *curCfg = nullptr; double padSecondsStart; double padSecondsEnd; };
1,232
C++
.h
39
27.512821
60
0.746846
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,670
GameConfig.h
ipatix_agbplay/src/GameConfig.h
#pragma once #include <vector> #include <string> #include "SongEntry.h" #include "Types.h" class GameConfig { public: GameConfig(const std::string& gameCode); GameConfig(const std::vector<std::string>& gameCodes); GameConfig(const GameConfig&) = delete; GameConfig(GameConfig&&) = default; GameConfig& operator=(const GameConfig&) = delete; const std::vector<std::string>& GetGameCodes() const; ReverbType GetRevType() const; void SetRevType(ReverbType revType); ResamplerType GetResTypeFixed() const; void SetResTypeFixed(ResamplerType resType); ResamplerType GetResType() const; void SetResType(ResamplerType resType); uint8_t GetPCMVol() const; void SetPCMVol(uint8_t pcmVol); uint8_t GetEngineFreq() const; void SetEngineFreq(uint8_t engineFreq); uint8_t GetEngineRev() const; void SetEngineRev(uint8_t engineRev); uint8_t GetTrackLimit() const; void SetTrackLimit(uint8_t trackLimit); uint16_t GetRevBufSize() const; void SetRevBufSize(uint16_t revBufSize); bool GetAccurateCh3Volume() const; void SetAccurateCh3Volume(bool enabled); bool GetAccurateCh3Quantization() const; void SetAccurateCh3Quantization(bool enabled); bool GetSimulateCGBSustainBug() const; void SetSimulateCGBSustainBug(bool enabled); std::vector<SongEntry>& GetGameEntries(); private: std::vector<std::string> gameCodes; std::vector<SongEntry> gameEntries; ReverbType revType = ReverbType::NORMAL; ResamplerType resTypeFixed = ResamplerType::LINEAR; ResamplerType resType = ResamplerType::LINEAR; uint8_t pcmVol = 0xF; uint8_t engineFreq = 0x4; uint8_t engineRev = 0x0; uint8_t trackLimit = 16; uint16_t revBufSize = 0x630; bool accurateCh3Volume = false; bool accurateCh3Quantization = false; bool simulateCGBSustainBug = false; };
1,884
C++
.h
52
31.884615
58
0.74644
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,671
TrackviewGUI.h
ipatix_agbplay/src/TrackviewGUI.h
#pragma once #include <vector> #include <string> #include "CursesWin.h" #include "SoundData.h" #include "DisplayContainer.h" class TrackviewGUI : public CursesWin { public: TrackviewGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~TrackviewGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; void SetState(const Sequence& seq, const float *vols, int activeChannels, int maxChannels); void SetTitle(const std::string& name); void Enter(); void Leave(); void PageDown(); void PageUp(); void ScrollDown(); void ScrollUp(); void ForceUpdate(); uint32_t GetCursorLoc() const { return cursorPos; } private: void update() override; void scrollDownNoUpdate(); void scrollUpNoUpdate(); DisplayContainer disp; std::string songName; uint32_t cursorPos; int maxChannels; int activeChannels; bool cursorVisible; static const std::vector<const char *> noteNames; };
1,016
C++
.h
33
26.909091
95
0.720859
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,672
SoundMixer.h
ipatix_agbplay/src/SoundMixer.h
#pragma once #include <vector> #include <list> #include <cstdint> #include <bitset> #include <memory> #include "ReverbEffect.h" #include "SoundChannel.h" #include "CGBChannel.h" #include "Constants.h" struct PlayerContext; class SoundMixer { public: SoundMixer(PlayerContext& ctx, uint32_t sampleRate, float masterVolume); SoundMixer(const SoundMixer&) = delete; SoundMixer& operator=(const SoundMixer&) = delete; void Init(uint32_t fixedModeRate, uint8_t reverb, float pcmMasterVolume, ReverbType rtype, uint8_t numTracks); void Process(std::vector<std::vector<sample>>& outputBuffers); size_t GetSamplesPerBuffer() const; uint32_t GetSampleRate() const; void ResetFade(); void StartFadeOut(float millis); void StartFadeIn(float millis); bool IsFadeDone() const; private: PlayerContext& ctx; std::vector<std::unique_ptr<ReverbEffect>> revdsps; uint32_t sampleRate; uint32_t fixedModeRate = 13379; size_t samplesPerBuffer = sampleRate / (AGB_FPS * INTERFRAMES); // volume control related stuff float masterVolume; float pcmMasterVolume = masterVolume; float fadePos = 1.0f; float fadeStepPerMicroframe = 0.0f; size_t fadeMicroframesLeft = 0; uint8_t numTracks = 0; };
1,271
C++
.h
39
28.948718
114
0.743653
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,673
SoundChannel.h
ipatix_agbplay/src/SoundChannel.h
#pragma once #include <cstdint> #include <cstddef> #include <memory> #include "Types.h" #include "Resampler.h" class SoundChannel { private: struct ProcArgs { float lVol; float rVol; float lVolStep; float rVolStep; float interStep; }; public: SoundChannel(SampleInfo sInfo, ADSR env, const Note& note, bool fixed); SoundChannel(const SoundChannel&) = delete; SoundChannel& operator=(const SoundChannel&) = delete; void Process(sample *buffer, size_t numSamples, const MixingArgs& args); uint8_t GetTrackIdx() const; void SetVol(uint16_t vol, int16_t pan); const Note& GetNote() const; void Release(); void Kill(); void SetPitch(int16_t pitch); bool TickNote(); // returns true if note remains active EnvState GetState() const; private: void stepEnvelope(); void updateVolFade(); VolumeFade getVol() const; void processNormal(sample *buffer, size_t numSamples, ProcArgs& cargs); void processModPulse(sample *buffer, size_t numSamples, ProcArgs& cargs, float nBlocksReciprocal); void processSaw(sample *buffer, size_t numSamples, ProcArgs& cargs); void processTri(sample *buffer, size_t numSamples, ProcArgs& cargs); static bool sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); static bool sampleFetchCallbackMPTDecomp(std::vector<float>& fetchBuffer, size_t samplesRequires, void *cbdata); std::unique_ptr<Resampler> rs; uint32_t pos = 0; float interPos = 0.0f; float freq = 0.0f; ADSR env; Note note; SampleInfo sInfo; bool stop = false; bool fixed; bool isGS; // is Golden Sun synth bool isMPTcompressed; // is Mario Power Tennis compressed int16_t levelMPTcompressed; uint8_t shiftMPTcompressed; /* all of these values have pairs of new and old value to allow smooth fades */ EnvState envState = EnvState::INIT; uint8_t envInterStep = 0; uint8_t envLevelCur; uint8_t envLevelPrev; uint8_t leftVolCur = 0; uint8_t leftVolPrev; uint8_t rightVolCur = 0; uint8_t rightVolPrev; };
2,166
C++
.h
63
29.730159
116
0.705293
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,674
Resampler.h
ipatix_agbplay/src/Resampler.h
#pragma once #include <vector> /* * res_data_fetch_cb fetches samplesRequired samples to fetchBuffer * so that the buffer can provide exactly samplesRequired samples * * returns false in case of 'end of stream' */ typedef bool (*res_data_fetch_cb)(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); class Resampler { public: // return value false by Process signals the "end of stream" virtual bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) = 0; virtual void Reset() = 0; virtual ~Resampler(); static bool ResamplerChainSampleFetchCB(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); struct ResamplerChainData { // pointer to access our object Resampler *_this; // parameters for process method float phaseInc; res_data_fetch_cb cbPtr; void *cbdata; }; protected: std::vector<float> fetchBuffer; float phase; }; class NearestResampler : public Resampler { public: NearestResampler(); ~NearestResampler() override; bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) override; void Reset() override; }; class LinearResampler : public Resampler { public: LinearResampler(); ~LinearResampler() override; bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) override; void Reset() override; }; class SincResampler : public Resampler { public: SincResampler(); ~SincResampler() override; bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) override; void Reset() override; private: static float fast_sinf(float t); static float fast_cosf(float t); static float fast_sincf(float t); static float window_func(float t); }; class BlepResampler : public Resampler { public: BlepResampler(); ~BlepResampler() override; bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) override; void Reset() override; private: static float fast_Si(float t); }; class BlampResampler : public Resampler { public: BlampResampler(); ~BlampResampler() override; bool Process(float *outData, size_t numBlocks, float phaseInc, res_data_fetch_cb cbPtr, void *cbdata) override; void Reset() override; private: static float fast_Ti(float t); };
2,509
C++
.h
72
31.041667
118
0.727872
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,675
Ringbuffer.h
ipatix_agbplay/src/Ringbuffer.h
#pragma once #include <mutex> #include <condition_variable> #include <vector> #include <cstddef> #include "Types.h" class Ringbuffer { public: Ringbuffer(size_t elementCount); Ringbuffer(const Ringbuffer&) = delete; Ringbuffer& operator=(const Ringbuffer&) = delete; void Put(sample *inData, size_t nElements); void Take(sample *outData, size_t nElements); void Clear(); private: size_t putChunk(sample *inData, size_t nElements); size_t takeChunk(sample *outData, size_t nElements); std::vector<sample> bufData; std::mutex countLock; std::condition_variable sig; size_t freePos = 0; size_t dataPos = 0; size_t freeCount; size_t dataCount = 0; };
712
C++
.h
26
23.884615
56
0.712188
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,676
CursesWin.h
ipatix_agbplay/src/CursesWin.h
#pragma once #include <curses.h> #include <cstdint> class CursesWin { public: CursesWin(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); CursesWin(const CursesWin&) = delete; CursesWin& operator=(const CursesWin&) = delete; virtual ~CursesWin(); virtual void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); protected: virtual void update(); WINDOW *winPtr; uint32_t height, width; };
457
C++
.h
15
27.133333
87
0.719818
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,677
ConsoleGUI.h
ipatix_agbplay/src/ConsoleGUI.h
#pragma once #define CONSOLE_BORDER_WIDTH 2 #include <vector> #include <string> #include <mutex> #include <boost/lockfree/spsc_queue.hpp> #include "CursesWin.h" class ConsoleGUI : public CursesWin { public: ConsoleGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~ConsoleGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; void Refresh(); private: void update() override; void writeToBuffer(const std::string& str); static void remoteWrite(const std::string& str, void *obj); uint32_t textWidth, textHeight; std::vector<std::string> textBuffer; boost::lockfree::spsc_queue<std::string> msgQueue; std::mutex writeMutex; };
765
C++
.h
24
27.75
63
0.712925
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,678
WindowGUI.h
ipatix_agbplay/src/WindowGUI.h
#pragma once /* window size definition * (h,w) = height and width of stdscr */ #define TITLEBAR_HEIGHT(h,w) 5 #define TITLEBAR_WIDTH(h,w) 33 #define TITLEBAR_YPOS(h,w) 0 #define TITLEBAR_XPOS(h,w) 0 #define VUMETER_HEIGHT(h,w) TITLEBAR_HEIGHT(h,w) #define VUMETER_WIDTH(h,w) (w - TITLEBAR_WIDTH(h,w)) #define VUMETER_YPOS(h,w) 0 #define VUMETER_XPOS(h,w) TITLEBAR_WIDTH(h,w) #define SONGLIST_HEIGHT(h,w) ((h - TITLEBAR_HEIGHT(h,w)) / 2) #define SONGLIST_WIDTH(h,w) 25 #define SONGLIST_YPOS(h,w) (TITLEBAR_HEIGHT(h,w)) #define SONGLIST_XPOS(h,w) 0 #define PLAYLIST_HEIGHT(h,w) ((h - TITLEBAR_HEIGHT(h,w)) / 2 + ((h - TITLEBAR_HEIGHT(h,w)) % 2)) #define PLAYLIST_WIDTH(h,w) SONGLIST_WIDTH(h,w) #define PLAYLIST_YPOS(h,w) (TITLEBAR_HEIGHT(h,w) + ((h - TITLEBAR_HEIGHT(h,w)) / 2)) #define PLAYLIST_XPOS(h,w) 0 #define CONSOLE_HEIGHT(h,w) 6 #define CONSOLE_WIDTH(h,w) (w - SONGLIST_WIDTH(h,w)) #define CONSOLE_YPOS(h,w) (h - CONSOLE_HEIGHT(h,w)) #define CONSOLE_XPOS(h,w) (SONGLIST_WIDTH(h,w)) #define HOTKEYBAR_HEIGHT(h,w) 1 #define HOTKEYBAR_WIDTH(h,w) (w - SONGLIST_WIDTH(h,w)) #define HOTKEYBAR_YPOS(h,w) (h - CONSOLE_HEIGHT(h,w) - HOTKEYBAR_HEIGHT(h,w)) #define HOTKEYBAR_XPOS(h,w) SONGLIST_WIDTH(h,w) #define ROMVIEW_HEIGHT(h,w) (h - TITLEBAR_HEIGHT(h,w) - HOTKEYBAR_HEIGHT(h,w) - CONSOLE_HEIGHT(h,w)) #define ROMVIEW_WIDTH(h,w) 20 #define ROMVIEW_YPOS(h,w) TITLEBAR_HEIGHT(h,w) #define ROMVIEW_XPOS(h,w) (w - ROMVIEW_WIDTH(h,w)) #define TRACKVIEW_HEIGHT(h,w) (h - TITLEBAR_HEIGHT(h,w) - HOTKEYBAR_HEIGHT(h,w) - CONSOLE_HEIGHT(h,w)) #define TRACKVIEW_WIDTH(h,w) (w - SONGLIST_WIDTH(h,w) - ROMVIEW_WIDTH(h,w)) #define TRACKVIEW_YPOS(h,w) TITLEBAR_HEIGHT(h,w) #define TRACKVIEW_XPOS(h,w) SONGLIST_WIDTH(h,w) // various macros #define CONTROL(x) (x & 0x1F) #include "ConsoleGUI.h" #include "HotkeybarGUI.h" #include "SonglistGUI.h" #include "PlaylistGUI.h" #include "TitlebarGUI.h" #include "RomviewGUI.h" #include "TrackviewGUI.h" #include "PlayerInterface.h" #include "VUMeterGUI.h" #include "ConfigManager.h" #include <memory> class WindowGUI { public: WindowGUI(SongTable& songTable); WindowGUI(const WindowGUI&) = delete; WindowGUI& operator=(const WindowGUI&) = delete; ~WindowGUI(); // main GUI handler bool Handle(); private: // sub window control void resizeWindows(); // color definitions void initColors(); // hotkey methods void cycleFocus(); void scrollLeft(); void scrollRight(); void scrollDown(); void scrollUp(); bool isLastSong() const; void pageDown(); void pageUp(); void songInfo(); void enter(); void add(); void del(); void mute(); void solo(); void tutti(); void rename(); void updateWindowSize(); void exportLaunch(bool benchmarkOnly, bool separate); bool exportReady(); // console GUI element std::unique_ptr<ConsoleGUI> conUI; std::unique_ptr<HotkeybarGUI> hotUI; std::unique_ptr<SonglistGUI> songUI; std::unique_ptr<PlaylistGUI> playUI; std::unique_ptr<TitlebarGUI> titleUI; std::unique_ptr<RomviewGUI> romUI; std::unique_ptr<TrackviewGUI> trackUI; std::unique_ptr<VUMeterGUI> meterUI; // resource SongTable& songTable; std::unique_ptr<PlayerInterface> mplay; std::unique_ptr<std::thread> exportThread; std::atomic<bool> exportBusy = false; // ncurses windows WINDOW *containerWin; int width, height; bool play; enum { PLAYLIST, SONGLIST, TRACKS_PLAYLIST, TRACKS_SONGLIST, SETTINGS } cursorl; };
3,553
C++
.h
104
30.942308
102
0.70245
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,679
Rom.h
ipatix_agbplay/src/Rom.h
#pragma once #include <cstdint> #include <string> #include <vector> #include <filesystem> #include <memory> #include "AgbTypes.h" #include "Xcept.h" class Rom { public: Rom(const std::filesystem::path& filePath); Rom(const Rom&) = delete; Rom& operator=(const Rom&) = delete; static void CreateInstance(const std::filesystem::path& filePath); static Rom& Instance() { return *global_instance; } const uint8_t& operator[](size_t pos) const { return data[pos]; } int8_t ReadS8(size_t pos) const { return static_cast<int8_t>(data.at(pos)); } uint8_t ReadU8(size_t pos) const { return data.at(pos); } int16_t ReadS16(size_t pos) const { return static_cast<int16_t>(ReadU16(pos)); } uint16_t ReadU16(size_t pos) const { uint32_t retval = data.at(pos + 1); retval <<= 8; retval |= data[pos]; return static_cast<uint16_t>(retval); } int32_t ReadS32(size_t pos) const { return static_cast<int32_t>(ReadU32(pos)); } uint32_t ReadU32(size_t pos) const { uint32_t retval = data.at(pos + 3); retval <<= 8; retval |= data[pos + 2]; retval <<= 8; retval |= data[pos + 1]; retval <<= 8; retval |= data[pos + 0]; return retval; } size_t ReadAgbPtrToPos(size_t pos) const { uint32_t ptr = ReadU32(pos); if (!ValidPointer(ptr)) throw Xcept("Cannot parse pointer at [%08zX]=%08X", pos, ptr); return ptr - AGB_MAP_ROM; } const void *GetPtr(size_t pos) const { return &data[pos]; } size_t Size() const { return data.size(); } bool ValidPointer(uint32_t ptr) const { if (ptr - AGB_MAP_ROM >= data.size()) return false; if (ptr - AGB_MAP_ROM + 1 >= data.size()) return false; return true; } std::string ReadString(size_t pos, size_t limit) const; std::string GetROMCode() const; private: void verify(); void loadFile(const std::filesystem::path& filePath); std::vector<uint8_t> data; static std::unique_ptr<Rom> global_instance; };
2,207
C++
.h
75
23.12
74
0.593661
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,680
CGBPatterns.h
ipatix_agbplay/src/CGBPatterns.h
#pragma once namespace CGBPatterns { // sample patterns extern const float pat_sq12[]; extern const float pat_sq25[]; extern const float pat_sq50[]; extern const float pat_sq75[]; };
204
C++
.h
9
19.333333
34
0.701031
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,681
Types.h
ipatix_agbplay/src/Types.h
#pragma once #include <cstdint> #include <string> enum class CGBType : int { SQ1 = 0, SQ2, WAVE, NOISE }; enum class EnvState : int { INIT = 0, ATK, DEC, SUS, REL, PSEUDO_ECHO, DIE, DEAD }; enum class WaveDuty : int { D12 = 0, D25, D50, D75 }; enum class NoisePatt : int { FINE = 0, ROUGH }; enum class ReverbType { NORMAL, GS1, GS2, MGAT, TEST, NONE }; enum class ResamplerType { NEAREST, LINEAR, SINC, BLEP, BLAMP }; enum class CGBPolyphony { MONO_STRICT, MONO_SMOOTH, POLY }; ReverbType str2rev(const std::string& str); std::string rev2str(ReverbType t); ResamplerType str2res(const std::string& str); std::string res2str(ResamplerType t); CGBPolyphony str2cgbPoly(const std::string& str); std::string cgbPoly2str(CGBPolyphony t); union CGBDef { const uint8_t *wavePtr; WaveDuty wd; NoisePatt np; }; struct MixingArgs { float vol; uint32_t fixedModeRate; float sampleRateInv; float samplesPerBufferInv; size_t curInterFrame; // <-- for debugging only }; struct VolumeFade { float fromVolLeft; float fromVolRight; float toVolLeft; float toVolRight; }; struct ADSR { ADSR(uint8_t att, uint8_t dec, uint8_t sus, uint8_t rel); ADSR(); uint8_t att; uint8_t dec; uint8_t sus; uint8_t rel; }; struct Note { uint8_t length; uint8_t midiKeyTrackData; uint8_t midiKeyPitch; uint8_t velocity; uint8_t priority; int8_t rhythmPan; uint8_t pseudoEchoVol; uint8_t pseudoEchoLen; uint8_t trackIdx; }; struct SampleInfo { SampleInfo(const int8_t *samplePtr, float midCfreq, bool loopEnabled, uint32_t loopPos, uint32_t endPos); SampleInfo(); const int8_t *samplePtr; float midCfreq; uint32_t loopPos; uint32_t endPos; bool loopEnabled; }; struct EnginePars { EnginePars(uint8_t vol, uint8_t rev, uint8_t freq); uint8_t vol; uint8_t rev; uint8_t freq; }; struct SongInfo { size_t songHeaderPos; size_t voiceTablePos; uint8_t reverb; uint8_t priority; }; struct sample { float left; float right; };
2,074
C++
.h
86
20.918605
109
0.705823
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,682
TitlebarGUI.h
ipatix_agbplay/src/TitlebarGUI.h
#pragma once #include <cstdint> #include "CursesWin.h" class TitlebarGUI : public CursesWin { public: TitlebarGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~TitlebarGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; int GetKey(); private: void update() override; };
372
C++
.h
13
25
79
0.711485
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,683
Util.h
ipatix_agbplay/src/Util.h
#pragma once #include <stdexcept> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define PI_F (float(M_PI)) inline void CStrAppend(char *dest, size_t *index, const char *src) { char ch; const char *copyChar = src; while ((ch = *copyChar++) != '\0') dest[(*index)++] = ch; }
307
C++
.h
13
20.769231
66
0.655172
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,684
PlayerContext.h
ipatix_agbplay/src/PlayerContext.h
#pragma once #include <vector> #include "SequenceReader.h" #include "SoundMixer.h" /* Instead of defining lots of global objects, we define * a context with all the things we need. So anything which * needs anything out of this context only needs a reference * to a PlayerContext */ struct PlayerContext { PlayerContext(int8_t maxLoops, uint8_t maxTracks, EnginePars pars); PlayerContext(const PlayerContext&) = delete; PlayerContext& operator=(const PlayerContext&) = delete; void Process(std::vector<std::vector<sample>>& trackAudio); void InitSong(size_t songPos); bool HasEnded() const; size_t GetCurInterFrame() const; SequenceReader reader; SoundMixer mixer; Sequence seq; SoundBank bnk; EnginePars pars; // sound channels std::list<SoundChannel> sndChannels; std::list<SquareChannel> sq1Channels; std::list<SquareChannel> sq2Channels; std::list<WaveChannel> waveChannels; std::list<NoiseChannel> noiseChannels; size_t curInterFrame = 0; };
1,034
C++
.h
29
31.655172
71
0.744233
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,685
Constants.h
ipatix_agbplay/src/Constants.h
#pragma once #define NUM_NOTES 128 #define PROG_UNDEFINED 0xFF #define MIN_SONG_NUM 4 // lowest seen one is 7 in Tetris World #define BPM_PER_FRAME 150 #define AGB_FPS 60 // for increased quality we process in subframes (including the base frame) #define INTERFRAMES 4 #define STREAM_SAMPLERATE 48000 #define SONG_FADE_OUT_TIME 10000 #define SONG_FINISH_TIME 1000 #define __STRM_BPSM ((STREAM_SAMPLERATE / 24) - 1) #define __STRM_BSA (__STRM_BPSM | (__STRM_BPSM >> 1)) #define __STRM_BSB (__STRM_BSA | (__STRM_BSA >> 2)) #define __STRM_BSC (__STRM_BSB | (__STRM_BSB >> 4)) #define __STRM_BSD (__STRM_BSC | (__STRM_BSC >> 8)) #define __STRM_BSE (__STRM_BSD | (__STRM_BSD >> 16)) #define STREAM_BUF_SIZE (__STRM_BSE+1) #define WINDOW_MIN_WIDTH 80 #define WINDOW_MIN_HEIGHT 24 #define WINDOW_MAX_WIDTH 512 #define WINDOW_MAX_HEIGHT 128
845
C++
.h
22
37.090909
75
0.710784
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,686
SequenceReader.h
ipatix_agbplay/src/SequenceReader.h
#pragma once #include <map> #include <vector> #include "Constants.h" #include "SoundData.h" #include "SoundMixer.h" struct PlayerContext; class SequenceReader { public: SequenceReader(PlayerContext& ctx, int8_t maxLoops); SequenceReader(const SequenceReader&) = delete; SequenceReader& operator=(const SequenceReader&) = delete; void Process(); bool EndReached() const; void Restart(); void SetSpeedFactor(float speedFactor); static const std::vector<uint32_t> freqLut; private: static const std::map<uint8_t, int8_t> delayLut; static const std::map<uint8_t, int8_t> noteLut; PlayerContext& ctx; bool endReached = false; const int8_t maxLoops = 1; uint8_t numLoops = 0; float speedFactor = 1.0f; void processSequenceTick(); int tickTrackNotes(uint8_t track_idx, std::bitset<NUM_NOTES>& activeNotes); void setTrackPV(uint8_t track_idx, uint16_t vol, int16_t pan, int16_t pitch, bool updateVolume, bool updatePitch); void cmdPlayNote(uint8_t cmd, uint8_t trackIdx); void cmdPlayCommand(uint8_t cmd, uint8_t trackIdx); void cmdPlayFine(uint8_t trackIdx); void cmdPlayMemacc(uint8_t trackIdx); void cmdPlayXCmd(uint8_t trackIdx); };
1,233
C++
.h
35
31.257143
118
0.735245
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,687
SoundData.h
ipatix_agbplay/src/SoundData.h
#pragma once #include <vector> #include <bitset> #include "Types.h" #include "Constants.h" enum class InstrType { PCM, PCM_FIXED, SQ1, SQ2, WAVE, NOISE, INVALID }; class SoundBank { public: SoundBank() = default; SoundBank(const SoundBank&) = delete; SoundBank& operator=(const SoundBank&) = delete; void Init(size_t bankPos); InstrType GetInstrType(uint8_t instrNum, uint8_t midiKey); uint8_t GetMidiKey(uint8_t instrNum, uint8_t midiKey); int8_t GetPan(uint8_t instrNum, uint8_t midiKey); uint8_t GetSweep(uint8_t instrNum, uint8_t midiKey); CGBDef GetCGBDef(uint8_t instrNum, uint8_t midiKey); SampleInfo GetSampInfo(uint8_t instrNum, uint8_t midiKey); ADSR GetADSR(uint8_t instrNum, uint8_t midiKey); private: size_t instrPos(uint8_t instrNum, uint8_t midiKey); size_t bankPos = 0; }; enum class MODT : int { PITCH = 0, VOL, PAN }; #define TRACK_CALL_STACK_SIZE 3 struct Track { Track(size_t pos); Track(const Track&) = delete; Track(Track &&) = default; Track& operator=(const Track&) = delete; int16_t GetPitch(); uint16_t GetVol(); int16_t GetPan(); void ResetLfoValue(); std::bitset<NUM_NOTES> activeNotes; size_t pos; size_t returnPos[TRACK_CALL_STACK_SIZE]; uint8_t patternLevel = 0; MODT modt = MODT::PITCH; uint8_t lastCmd = 0; int16_t pitch = 0; uint8_t lastNoteKey = 60, lastNoteVel = 127; uint8_t lastNoteLen = 96; uint8_t reptCount = 0; uint8_t prog = PROG_UNDEFINED, vol = 100, mod = 0, bendr = 2, priority = 0; uint8_t lfos = 22, lfodl = 0, lfodlCount = 0, lfoPhase = 0; int8_t lfoValue = 0; uint8_t pseudoEchoVol = 0, pseudoEchoLen = 0; uint16_t delay = 0; int8_t pan = 0, bend = 0, tune = 0; int8_t keyShift = 0; bool muted = false; bool isRunning = true; bool updateVolume = false; bool updatePitch = false; }; // end Track class Sequence { public: Sequence(uint8_t trackLimit); Sequence(const Sequence&) = delete; Sequence& operator=(const Sequence&) = delete; void Init(size_t songHeaderPos); void Reset(); std::vector<Track> tracks; std::vector<uint8_t> memaccArea; // processing variables uint32_t tickCount = 0; int32_t bpmStack; uint16_t bpm; size_t GetSoundBankPos(); uint8_t GetReverb() const; uint8_t GetPriority() const; size_t GetSongHeaderPos() const; private: size_t songHeaderPos; uint8_t trackLimit; }; // end Sequence class SongTable { public: static std::vector<SongTable> ScanForTables(); SongTable(size_t songTablePos); SongTable(const SongTable&) = default; SongTable& operator=(const SongTable&) = default; size_t GetSongTablePos(); size_t GetPosOfSong(uint16_t uid); size_t GetNumSongs(); private: static bool validateTableEntry(size_t pos); static bool validateSong(size_t songPos); size_t determineNumSongs(); size_t songTablePos; size_t numSongs; };
2,997
C++
.h
97
26.793814
79
0.687825
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,688
PlaylistGUI.h
ipatix_agbplay/src/PlaylistGUI.h
#pragma once #include "SonglistGUI.h" #include "GameConfig.h" class PlaylistGUI : public SonglistGUI { public: PlaylistGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~PlaylistGUI() override; void AddSong(SongEntry) override; void RemoveSong() override; void ClearSongs() override; SongEntry *GetSong() override; std::vector<bool>& GetTicked(); void Leave() override; void Tick(); void Untick(); void ToggleTick(); void ToggleDrag(); void UntickAll(); bool IsDragging(); private: void swapEntry(uint32_t a, uint32_t b); void update() override; void scrollDownNoUpdate() override; void scrollUpNoUpdate() override; std::vector<bool> ticked; bool dragging; };
762
C++
.h
27
24.111111
79
0.703146
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,689
RomviewGUI.h
ipatix_agbplay/src/RomviewGUI.h
#pragma once #include <cstdint> #include <string> #include "CursesWin.h" #include "Rom.h" #include "SoundData.h" class RomviewGUI : public CursesWin { public: RomviewGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos, SongTable& songTable); ~RomviewGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; private: void update() override; std::string gameName; std::string gameCode; size_t songTablePos; size_t numSongs; };
518
C++
.h
18
25.833333
100
0.734406
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,690
ReverbEffect.h
ipatix_agbplay/src/ReverbEffect.h
#pragma once #include <cstdint> #include <cstddef> #include <vector> #include "Types.h" class ReverbEffect { public: ReverbEffect(uint8_t intesity, size_t streamRate, uint8_t numAgbBuffers); virtual ~ReverbEffect(); void ProcessData(sample *buffer, size_t numSamples); protected: virtual size_t processInternal(sample *buffer, size_t numSamples); size_t getBlocksPerBuffer() const; float intensity; //size_t streamRate; std::vector<sample> reverbBuffer; size_t bufferPos; size_t bufferPos2; }; class ReverbGS1 : public ReverbEffect { public: ReverbGS1(uint8_t intensity, size_t streamRate, uint8_t numAgbBuffers); ~ReverbGS1() override; protected: size_t processInternal(sample *buffer, size_t numSamples) override; size_t getBlocksPerGsBuffer() const; std::vector<sample> gsBuffer; }; class ReverbGS2 : public ReverbEffect { public: ReverbGS2(uint8_t intesity, size_t streamRate, uint8_t numAgbBuffers, float rPrimFac, float rSecFac); ~ReverbGS2() override; protected: size_t processInternal(sample *buffer, size_t numSamples) override; std::vector<sample> gs2Buffer; size_t gs2Pos; float rPrimFac, rSecFac; }; class ReverbTest : public ReverbEffect { public: ReverbTest(uint8_t intesity, size_t streamRate, uint8_t numAgbBuffers); ~ReverbTest() override; protected: size_t processInternal(sample *buffer, size_t numSamples) override; };
1,453
C++
.h
50
25.78
77
0.750895
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,691
DisplayContainer.h
ipatix_agbplay/src/DisplayContainer.h
#pragma once #include <bitset> #include <vector> #include "Constants.h" struct DisplayData { uint32_t trackPtr = 0; bool isCalling = false; bool isMuted = false; uint8_t vol = 100; // range 0 to 127 uint8_t mod = 0; // range 0 to 127 uint8_t prog = PROG_UNDEFINED; // range 0 to 127 int8_t pan = 0; // range -64 to 63 int16_t pitch = 0; // range -32768 to 32767 uint8_t envL = 0; // range 0 to 255 uint8_t envR = 0; // range 0 to 255 uint8_t delay = 0; // range 0 to 96 std::bitset<NUM_NOTES> activeNotes; }; struct DisplayContainer { DisplayContainer() = default; DisplayContainer(const DisplayContainer&) = delete; DisplayContainer& operator=(const DisplayContainer&) = delete; std::vector<DisplayData> data; };
884
C++
.h
26
30.269231
66
0.590856
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,692
Xcept.h
ipatix_agbplay/src/Xcept.h
#pragma once #include <exception> #include <string> #define MAX_EXCEPTION_LENGTH 1024 class Xcept : public std::exception { public: Xcept(const char *format, ...); ~Xcept() override; const char *what() const throw() override; private: std::string msg; };
299
C++
.h
12
20.25
50
0.650177
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,693
CGBChannel.h
ipatix_agbplay/src/CGBChannel.h
#pragma once #include <cstdint> #include <cstddef> #include <memory> #include "Types.h" #include "Resampler.h" #define INVALID_TRACK_IDX 0xFF #define NOISE_SAMPLING_FREQ 65536.0f class CGBChannel { public: CGBChannel(ADSR env, Note note, bool useStairstep = false); CGBChannel(const CGBChannel&) = delete; CGBChannel& operator=(const CGBChannel&) = delete; virtual ~CGBChannel() = default; virtual void Process(sample *buffer, size_t numSamples, MixingArgs& args) = 0; uint8_t GetTrackIdx() const; void SetVol(uint16_t vol, int16_t pan); const Note& GetNote() const; void Release(bool fastRelease = false); virtual void SetPitch(int16_t pitch) = 0; bool TickNote(); // returns true if note remains active EnvState GetState() const; bool IsReleasing() const; bool IsFastReleasing() const; protected: virtual bool IsChn3() const; void stepEnvelope(); void updateVolFade(); void applyVol(); VolumeFade getVol() const; uint8_t getPseudoEchoLevel() const; static float timer2freq(float timer); static float freq2timer(float freq); std::unique_ptr<Resampler> rs; enum class Pan { LEFT, CENTER, RIGHT }; uint32_t pos = 0; float freq = 0.0f; ADSR env; Note note; const bool useStairstep; bool stop = false; bool fastRelease = false; uint16_t vol = 0; int16_t pan = 0; bool mp2k_sus_vol_bug_update = false; /* all of these values have pairs of new and old value to allow smooth fades */ EnvState envState = EnvState::INIT; uint8_t envInterStep = 0; uint8_t envLevelCur = 0; uint8_t envPeak = 0; uint8_t envSustain = 0; uint8_t envFrameCount = 0; float envFadeLevel = 0.0f; VolumeFade volFade{0.0f, 0.0f, 0.0f, 0.0f}; Pan panCur = Pan::CENTER; Pan panPrev = Pan::CENTER; }; class SquareChannel : public CGBChannel { public: SquareChannel(WaveDuty wd, ADSR env, Note note, uint8_t sweep); void SetPitch(int16_t pitch) override; void Process(sample *buffer, size_t numSamples, MixingArgs& args) override; private: static bool sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); static bool isSweepEnabled(uint8_t sweep); static bool isSweepAscending(uint8_t sweep); static float sweep2coeff(uint8_t sweep); static float sweep2convergence(uint8_t sweep); static uint8_t sweepTime(uint8_t sweep); const float *pat = nullptr; int16_t sweepStartCount = -1; const uint8_t sweep; const bool sweepEnabled; const float sweepConvergence; const float sweepCoeff; /* sweepTimer is emulated with float instead of hardware int to get sub frame accuracy */ float sweepTimer = 1.0f; }; class WaveChannel : public CGBChannel { public: WaveChannel(const uint8_t *wavePtr, ADSR env, Note note, bool useStairstep); void SetPitch(int16_t pitch) override; void Process(sample *buffer, size_t numSamples, MixingArgs& args) override; private: bool IsChn3() const override; VolumeFade getVol() const; static bool sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); float dcCorrection100; float dcCorrection75; float dcCorrection50; float dcCorrection25; const uint8_t * const wavePtr; }; class NoiseChannel : public CGBChannel { public: NoiseChannel(NoisePatt np, ADSR env, Note note); void SetPitch(int16_t pitch) override; void Process(sample *buffer, size_t numSamples, MixingArgs& args) override; private: static bool sampleFetchCallback(std::vector<float>& fetchBuffer, size_t samplesRequired, void *cbdata); SincResampler srs; uint16_t noiseState; uint16_t noiseLfsrMask; };
3,763
C++
.h
108
30.712963
107
0.723749
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,694
ColorDef.h
ipatix_agbplay/src/ColorDef.h
#pragma once // color sets enum class Color : int { DEF_DEF = 1, // default on default BANNER_TEXT, WINDOW_FRAME, LIST_ENTRY, LIST_SEL, VU_LOW, VU_MID, VU_HIGH, TRK_NUM, TRK_NUM_MUTED, TRK_LOC, TRK_LOC_CALL, TRK_DEL, TRK_NOTE, TRK_VOICE, TRK_PAN, TRK_VOL, TRK_MOD, TRK_PITCH, TRK_LOUDNESS, TRK_LOUDNESS_MUTED, TRK_LOUD_SPLIT, TRK_FGB_BGCW, // C not pressed, C# not pressed TRK_FGC_BGCW, // C not pressed, C# pressed TRK_FGB_BGW, // D not pressed, D# not pressed TRK_FGC_BGW, // D not pressed, D# pressed TRK_FGB_BGC, // D pressed, D# not pressed TRK_FGC_BGC, // D pressed, D# pressed TRK_FGW_BGW, // E not pressed, F not pressed TRK_FGEC_BGW, // E not pressed, F pressed TRK_FGW_BGC, // E pressed, F not pressed TRK_FGEC_BGC, // E pressed, F pressed };
918
C++
.h
36
20.722222
52
0.592677
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,695
AgbTypes.h
ipatix_agbplay/src/AgbTypes.h
#pragma once #define AGB_MAP_ROM 0x08000000 #define AGB_MAP_ROM_END 0x0A000000 #define AGB_ROM_SIZE (AGB_MAP_ROM_END-AGB_MAP_ROM)
132
C++
.h
4
31.5
50
0.793651
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,696
SoundExporter.h
ipatix_agbplay/src/SoundExporter.h
#pragma once #include <sndfile.h> #include <string> #include <vector> #include <cstdint> #include <filesystem> #include "SongEntry.h" #include "GameConfig.h" #include "ConsoleGUI.h" #include "SoundData.h" class SoundExporter { public: SoundExporter(SongTable& songTable, bool benchmarkOnly, bool seperate); SoundExporter(const SoundExporter&) = delete; SoundExporter& operator=(const SoundExporter&) = delete; void Export(const std::vector<SongEntry>& entries); private: static void writeSilence(SNDFILE *ofile, double seconds); size_t exportSong(const std::filesystem::path& fileName, uint16_t uid); SongTable& songTable; bool benchmarkOnly; bool seperate; // seperate tracks to multiple files };
740
C++
.h
24
28.083333
75
0.764789
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,697
Debug.h
ipatix_agbplay/src/Debug.h
#pragma once #include <string> namespace Debug { void print(const char *str, ...); bool open(const char *file); bool close(); void set_callback(void (*cb)(const std::string&, void *), void *obj); }
216
C++
.h
8
23.75
73
0.650485
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,698
VUMeterGUI.h
ipatix_agbplay/src/VUMeterGUI.h
#pragma once #include "CursesWin.h" class VUMeterGUI : public CursesWin { public: VUMeterGUI(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos); ~VUMeterGUI() override; void Resize(uint32_t height, uint32_t width, uint32_t yPos, uint32_t xPos) override; void SetVol(float left, float right); private: void update() override; float vuLevelLeft; float vuLevelRight; int meterWidth; int meterRed; int meterYel; };
467
C++
.h
17
23.882353
88
0.7287
ipatix/agbplay
118
21
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,703
Coder.cpp
Orvid_Champollion/Decompiler/Coder.cpp
#include "Coder.hpp" #include <cassert> /** * @brief Constructor * Builds an coder associated with an output writer. * * @param writer Pointer to the writer managing the output. The ownership is transferred. */ Decompiler::Coder::Coder(Decompiler::OutputWriter *writer) : m_Writer(writer) { assert(writer != nullptr); } /** * @brief Default destructor. */ Decompiler::Coder::~Coder() { } /** * @brief Write a string to the output * @param line String to write. */ void Decompiler::Coder::write(const std::string &line) { m_Writer->writeLine(line); } template<class T> static constexpr bool IsAnOstream = std::is_base_of<std::decay_t<T>, std::ostream>::value; template<class T> static constexpr bool IsAnOStringstream = std::is_base_of<std::decay_t<T>, std::ostringstream>::value; /** * @brief Write the content of a ostringstream. * The ostringstream is passed as an ostream. This is intended * to write output in the form * write(indent(i) << "line data"); * @param stream The stream as an ostream. */ void Decompiler::Coder::write(std::ostream&& stream) { auto& sstream = static_cast<std::ostringstream&>(stream); m_Writer->writeLine(sstream.str()); } /** * @brief Creates an ostringstream and prepare it with identation. * @param i Indentation level to apply. * @return */ std::ostringstream Decompiler::Coder::indent(int i) { std::ostringstream result; for(; i != 0; --i) { result << ' ' << ' '; } return result; }
1,494
C++
.cpp
55
24.818182
120
0.701326
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,704
PscCodeGenerator.cpp
Orvid_Champollion/Decompiler/PscCodeGenerator.cpp
#include "PscCodeGenerator.hpp" #include <cassert> #include "Node/Nodes.hpp" #include "PscCoder.hpp" static bool isTempVar(const Pex::StringTable::Index& var) { auto& name = var.asString(); return name.length() > 6 && name.substr(0, 6) == "::temp" && name.substr(name.length() - 4, 4) != "_var"; } static std::string getVarName(const Pex::StringTable::Index& var) { auto& name = var.asString(); if (name.length() > 6 && name.substr(0, 2) == "::" && name.substr(name.length() - 4, 4) == "_var") { return name.substr(2, name.length() - 6); } return name; } Decompiler::PscCodeGenerator::PscCodeGenerator(Decompiler::PscDecompiler* decompiler) : m_Decompiler(decompiler) { assert(decompiler); } void Decompiler::PscCodeGenerator::newLine() { if (!m_ExperimentalSyntaxWarning.empty()) { m_Result << " " << Decompiler::WARNING_COMMENT_PREFIX << " WARNING: Experimental syntax, may be incorrect: "; for (auto warn: m_ExperimentalSyntaxWarning){ m_Result << warn << " "; } m_ExperimentalSyntaxWarning.clear(); } auto nums = getDebugInfoLineNumbers(minIpForCurrentLine, maxIpForCurrentLine); resetIpsForCurrentLine(); m_Decompiler->push_back(m_Result.str()); m_Decompiler->addLineMapping(m_Decompiler->size() - 1, nums); m_Result = std::ostringstream(); for (auto i = 0; i < m_Level; ++i) { m_Result << ' ' << ' '; } } void Decompiler::PscCodeGenerator::visit(Node::Scope* node) { auto not_first = false; for(auto statement : *node) { if(not_first) { newLine(); } else { not_first = true; } if (statement->getBegin() != -1 && statement->getEnd() != -1) { m_Decompiler->decodeToAsm(m_Level, statement->getBegin(), statement->getEnd()); } statement->visit(this); } if (node->getParent() == nullptr) { newLine(); } } void Decompiler::PscCodeGenerator::visit(Node::BinaryOperator* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool parenOnLeft = node->getPrecedence() < node->getLeft()->getPrecedence(); if (node->getLeft()->is<Node::BinaryOperator>()) { auto l = node->getLeft()->as<Node::BinaryOperator>(); if (l->getLeft()->is<Node::Cast>() || l->getRight()->is<Node::Cast>()) { parenOnLeft = true; } } bool parenOnRight = node->getPrecedence() < node->getRight()->getPrecedence(); if (node->getRight()->is<Node::BinaryOperator>()) { auto r = node->getRight()->as<Node::BinaryOperator>(); if (r->getLeft()->is<Node::Cast>() || r->getRight()->is<Node::Cast>()) { parenOnRight = true; } } if (parenOnLeft) { m_Result << "("; } node->getLeft()->visit(this); if (parenOnLeft) { m_Result << ")"; } m_Result << " " << node->getOperator() << " "; if (parenOnRight) { m_Result << "("; } if (node->getOperator() == "is" && node->getRight()->is<Node::IdentifierString>()) { m_Result << PscCoder::mapType(node->getRight()->as<Node::IdentifierString>()->getIdentifier()); } else { node->getRight()->visit(this); } if (parenOnRight) { m_Result << ")"; } } void Decompiler::PscCodeGenerator::visit(Node::UnaryOperator* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getValue()->getPrecedence(); m_Result << node->getOperator(); if (paren) { m_Result << "("; } node->getValue()->visit(this); if (paren) { m_Result << ")"; } } void Decompiler::PscCodeGenerator::visit(Node::Assign* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); node->getDestination()->visit(this); m_Result << " = "; node->getValue()->visit(this); } void Decompiler::PscCodeGenerator::visit(Node::AssignOperator* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); node->getDestination()->visit(this); m_Result << " " << node->getOperator() << " "; node->getValue()->visit(this); } void Decompiler::PscCodeGenerator::visit(Node::Copy *node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); node->getValue()->visit(this); } void Decompiler::PscCodeGenerator::visit(Node::Cast* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getValue()->getPrecedence() || node->getValue()->is<Node::Cast>(); if (paren) { m_Result << "("; } node->getValue()->visit(this); if (paren) { m_Result << ")"; } m_Result << " as " << PscCoder::mapType(node->getType().asString()); } void Decompiler::PscCodeGenerator::visit(Node::CallMethod* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getObject()->getPrecedence(); if (paren) { m_Result << "("; } if (node->getObject()->is<Node::IdentifierString>()) { m_Result << PscCoder::mapType(node->getObject()->as<Node::IdentifierString>()->getIdentifier()); } else { node->getObject()->visit(this); } if (paren) { m_Result << ")"; } m_Result << "." << node->getMethod() << "("; node->getParameters()->visit(this); m_Result << ")"; if (node->isExperimentalSyntax()) { m_ExperimentalSyntaxWarning.push_back(node->getMethod().asString()); } } void Decompiler::PscCodeGenerator::visit(Node::Params *node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool not_first = false; for (auto param : *node) { if (not_first) { m_Result << ", "; } else { not_first = true; } param->visit(this); } } void Decompiler::PscCodeGenerator::visit(Node::Return* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); m_Result << "Return "; if (node->getValue()) { node->getValue()->visit(this); } } void Decompiler::PscCodeGenerator::visit(Node::PropertyAccess *node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getObject()->getPrecedence(); if (paren) { m_Result << "("; } node->getObject()->visit(this); if (paren) { m_Result << ")"; } m_Result << "." << node->getProperty(); } void Decompiler::PscCodeGenerator::visit(Node::StructCreate* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); m_Result << "new " << PscCoder::mapType(node->getType().asString()); } void Decompiler::PscCodeGenerator::visit(Node::ArrayCreate* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); std::string type = PscCoder::mapType(node->getType().asString()); m_Result << "new " << type.substr(0, type.length() - 2) << "["; node->getIndex()->visit(this); m_Result << "]"; } void Decompiler::PscCodeGenerator::visit(Node::ArrayLength* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getArray()->getPrecedence(); if (paren) { m_Result << "("; } node->getArray()->visit(this); if (paren) { m_Result << ")"; } m_Result << ".Length"; } void Decompiler::PscCodeGenerator::visit(Node::ArrayAccess *node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); bool paren = node->getPrecedence() < node->getArray()->getPrecedence(); if (paren) { m_Result << "("; } node->getArray()->visit(this); if (paren) { m_Result << ")"; } m_Result << "["; node->getIndex()->visit(this); m_Result << "]"; } void Decompiler::PscCodeGenerator::visit(Node::Constant* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); auto& value = node->getConstant(); m_Result << value.toString(); } void Decompiler::PscCodeGenerator::visit(Node::IdentifierString *node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); if (node->getIdentifier() == "self") m_Result << "Self"; else m_Result << node->getIdentifier(); } void Decompiler::PscCodeGenerator::visit(Node::While* node) { m_Result << "While "; node->getCondition()->visit(this); m_Level++; newLine(); node->getBody()->visit(this); m_Level--; newLine(); if (node->getBody()->size() != 0) { m_Decompiler->decodeToAsm(m_Level, node->getBody()->back()->getEnd() + 1, node->getBody()->back()->getEnd() + 1); } // EndWhile does not have valid debug line numbers, reset minIpForCurrentLine and maxIpForCurrentLine resetIpsForCurrentLine(); m_Result << "EndWhile"; } void Decompiler::PscCodeGenerator::visit(Node::IfElse* node) { addIpRangeForCurrentLine(node->getBegin(), node->getEnd()); auto cond = node->getCondition(); m_Result << "If "; node->getCondition()->visit(this); m_Level++; newLine(); node->getBody()->visit(this); m_Level--; newLine(); auto lastBody = node->getBody(); for (auto childNode : *(node->getElseIf())) { m_Decompiler->decodeToAsm(m_Level, childNode->getBegin()-1, childNode->getEnd()); auto elseIf = childNode->as<Node::IfElse>(); m_Result << "ElseIf "; elseIf->getCondition()->visit(this); m_Level++; newLine(); elseIf->getBody()->visit(this); m_Level--; newLine(); lastBody = elseIf->getBody(); } m_Decompiler->decodeToAsm(m_Level, lastBody->getEnd() + 1, lastBody->getEnd() + 1); if (node->getElse()->size() != 0) { m_Result << "Else"; m_Level++; // Else do not have valid debug line numbers, reset minIpForCurrentLine and maxIpForCurrentLine resetIpsForCurrentLine(); newLine(); node->getElse()->visit(this); m_Level--; newLine(); } // Endif does not have valid debug line numbers, reset minIpForCurrentLine and maxIpForCurrentLine resetIpsForCurrentLine(); m_Result << "EndIf"; } void Decompiler::PscCodeGenerator::visit(Node::Declare *node) { addIpRangeForCurrentLine(node->getEnd(), node->getEnd()); m_Result << PscCoder::mapType(node->getType().asString()) << " "; node->getObject()->visit(this); } void Decompiler::PscCodeGenerator::visit(Node::GuardStatement *node) { m_Result << "Guard "; addIpRangeForCurrentLine(node->getBegin(), node->getBegin()); node->getParameters()->visit(this); m_Level++; // TODO: VERIFY: Remove this when syntax is verified m_ExperimentalSyntaxWarning.push_back("Guard"); newLine(); node->getBody()->visit(this); m_Level--; newLine(); m_Result << "EndGuard"; m_ExperimentalSyntaxWarning.push_back("EndGuard"); } void Decompiler::PscCodeGenerator::visit(Node::TryGuard *node) { m_Result << "TryGuard "; addIpRangeForCurrentLine(node->getBegin(), node->getBegin()); node->getParameters()->visit(this); m_Level++; // TODO: VERIFY: Remove this when syntax is verified m_ExperimentalSyntaxWarning.push_back("TryGuard"); newLine(); node->getBody()->visit(this); m_Level--; newLine(); m_Result << "EndGuard"; m_ExperimentalSyntaxWarning.push_back("EndGuard"); } void Decompiler::PscCodeGenerator::visit(Node::EndGuard *node) { // NONE } void Decompiler::PscCodeGenerator::addIpRangeForCurrentLine(int64_t begin, int64_t end) { if (begin <= -1 || end <= -1) { return; } if (minIpForCurrentLine <= -1 || begin < minIpForCurrentLine) { minIpForCurrentLine = begin; } if (maxIpForCurrentLine <= -1 || end > maxIpForCurrentLine) { maxIpForCurrentLine = end; } } void Decompiler::PscCodeGenerator::resetIpsForCurrentLine() { minIpForCurrentLine = -1; maxIpForCurrentLine = -1; } std::vector<uint16_t> Decompiler::PscCodeGenerator::getDebugInfoLineNumbers(int64_t begin, int64_t end) { return m_Decompiler->getDebugInfo().getLineNumbersForIpRange(begin, end); }
12,361
C++
.cpp
391
26.452685
121
0.620649
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,708
main.cpp
Orvid_Champollion/Champollion/main.cpp
#include <iostream> #include <boost/program_options.hpp> namespace options = boost::program_options; #include <fmt/format.h> #include <filesystem> namespace fs = std::filesystem; #include <chrono> #include <future> #include <ctime> #include "Pex/Binary.hpp" #include "Pex/FileReader.hpp" #include "Decompiler/AsmCoder.hpp" #include "Decompiler/PscCoder.hpp" #include "Decompiler/StreamWriter.hpp" #include "Decompiler/Version.hpp" #include "glob.hpp" #include "CaselessCompare.h" struct Params { bool outputAssembly; bool outputComment; bool writeHeader; bool parallel; bool traceDecompilation; bool dumpTree; bool recreateDirStructure; bool decompileDebugFuncs; bool recursive; bool verbose; bool printInfo; bool printCompileTime; bool debugLineComment; fs::path assemblyDir; fs::path papyrusDir; fs::path parentDir{}; std::vector<fs::path> inputs; }; enum OptionsResult{ Invalid = -1, HelpOrVersion, Good }; OptionsResult getProgramOptions(int argc, char* argv[], Params& params) { params.outputAssembly = false; params.outputComment = false; params.writeHeader = false; params.parallel = false; params.traceDecompilation = false; params.dumpTree = true; params.recreateDirStructure = false; params.decompileDebugFuncs = false; params.verbose = false; params.printInfo = false; params.printCompileTime = false; params.debugLineComment = true; params.assemblyDir = fs::current_path(); params.papyrusDir = fs::current_path(); std::string version_string = "Champollion PEX decompiler " + std::string(CHAMPOLLION_VERSION_STRING); options::options_description desc(version_string); desc.add_options() ("help,h", "Display the help message") ("asm,a", options::value<std::string>()->implicit_value(""), "If defined, output assembly file(s) to this directory") ("psc,p", options::value<std::string>(), "Name of the output dir for psc decompilation") ("recursive,r", "Recursively scan directories for pex files") ("recreate-subdirs,s", "Recreates directory structure for script in root of output directory (Fallout 4 only, default false)") ("comment,c", "Output assembly in comments of the decompiled psc file") ("header,e", "Write header to decompiled psc file") ("threaded,t", "Run decompilation in parallel mode") ("trace,g", "Trace the decompilation and output results to rebuild log") ("no-dump-tree", "Do not dump tree for each node during decompilation tracing (requires --trace)") ("debug-funcs,d", "Decompile debug and compiler-generated functions (default false)") ("no-debug-line", "Do not comment with debug info line numbers on script lines (default false)") ("print-info,i", "Print header info from the specified PEX file(s) and exit") ("print-compile-time", "Print the compile time of the script in format of {filename}: {time_integer} and exit") ("verbose,v", "Verbose output") ("version,V", "Output version number") ; options::options_description files; files.add_options() ("input", options::value< std::vector<std::string> >(), "Name of the input file"); options::positional_options_description pdesc; pdesc.add("input", -1); options::variables_map args; try { options::store(options::basic_command_line_parser<char>(argc, argv).options( options::options_description().add(desc).add(files) ).positional(pdesc).run(), args); options::notify(args); } catch (const std::exception& ex) { std::cout << ex.what() << std::endl; std::cout << desc << std::endl; return Invalid; } if (args.count("help")) { std::cout << desc; return HelpOrVersion; } if (args.count("version")) { std::cout << version_string << std::endl; return HelpOrVersion; } params.outputComment = (args.count("comment") != 0); params.writeHeader = (args.count("header") != 0); params.parallel = (args.count("threaded") != 0); params.traceDecompilation = (args.count("trace") != 0); params.dumpTree = params.traceDecompilation && args.count("no-dump-tree") == 0; params.recursive = (args.count("recursive") != 0); params.recreateDirStructure = (args.count("recreate-subdirs") != 0); params.decompileDebugFuncs = (args.count("debug-funcs") != 0); params.printInfo = (args.count("print-info") != 0); params.printCompileTime = (args.count("print-compile-time") != 0); params.debugLineComment = !(args.count("no-debug-line") != 0); params.verbose = (args.count("verbose") != 0); if (!params.printInfo) { try { if (args.count("asm")) { params.outputAssembly = true; auto dir = args["asm"].as<std::string>(); if (!dir.empty()) { params.assemblyDir = fs::path(dir); if (!fs::exists(params.assemblyDir)) { fs::create_directories(params.assemblyDir); } else if (!fs::is_directory(params.assemblyDir)) { std::cout << params.assemblyDir << " is not a directory" << std::endl; return Invalid; } } } if (args.count("psc")) { auto dir = args["psc"].as<std::string>(); params.papyrusDir = fs::path(dir); if (!fs::exists(params.papyrusDir)) { fs::create_directories(params.papyrusDir); } else if (!fs::is_directory(params.papyrusDir)) { std::cout << params.papyrusDir << " is not a directory" << std::endl; return Invalid; } } } catch (const std::exception &ex) { std::cout << ex.what(); return Invalid; } } if(args.count("input")) { auto input_args = args["input"].as<std::vector<std::string>>(); auto globbed_files = glob::rglob(input_args); for (auto in : globbed_files) { fs::path file(in); if (fs::exists(file)) { params.inputs.push_back(file); } else { std::cout << file << " doesn't exists, skipping" << std::endl; } } } if (params.inputs.empty()) { std::cout << "No input file given" << std::endl; return Invalid; } return Good; } struct _ProcessResults{ std::vector<std::string> output; bool isStarfield = false; bool failed = false; }; typedef _ProcessResults ProcessResults; ProcessResults processFile(fs::path file, Params params) { ProcessResults result; Pex::Binary pex; try { Pex::FileReader reader(file.string()); reader.read(pex); pex.sort(); } catch(std::exception& ex) { result.output.push_back(fmt::format("ERROR: {} : {}", file.string(), ex.what())); result.failed = true; return result; } pex.getGameType() == Pex::Binary::StarfieldScript ? result.isStarfield = true : result.isStarfield = false; if (params.printInfo) { std::string gameType; switch(pex.getGameType()) { case Pex::Binary::SkyrimScript: gameType = "Skyrim"; break; case Pex::Binary::Fallout4Script: gameType = "Fallout 4"; break; case Pex::Binary::StarfieldScript: gameType = "Starfield"; break; default: gameType = "Unknown"; break; } result.output.push_back(fmt::format("Script: {}", file.string() )); // print out all the info contained in the header and exit result.output.push_back(fmt::format(" Game: {}", gameType)); auto header = pex.getHeader(); result.output.push_back(fmt::format(" Game Version: {}.{}", header.getMajorVersion(), header.getMinorVersion())); result.output.push_back(fmt::format(" GameID: {}", header.getGameID())); auto time = header.getCompilationTime(); std::string hrtime = ctime(&time); // trim trailing line break hrtime.erase(hrtime.find_last_not_of("\n") + 1); result.output.push_back(fmt::format(" Compilation Time: {} ({}) ", time, hrtime)); result.output.push_back(fmt::format(" Source File: {}", header.getSourceFileName())); result.output.push_back(fmt::format(" User Name: {}", header.getUserName())); result.output.push_back(fmt::format(" Computer Name: {}\n", header.getComputerName())); return result; } if (params.printCompileTime) { auto header = pex.getHeader(); auto time = header.getCompilationTime(); result.output.push_back(fmt::format("{}: {}", file.string(), time)); return result; } if (params.outputAssembly) { fs::path asmFile = params.assemblyDir / file.filename().replace_extension(".pas"); try { std::ofstream asmStream(asmFile.string()); Decompiler::AsmCoder asmCoder(new Decompiler::StreamWriter(asmStream)); asmCoder.code(pex); result.output.push_back(fmt::format("{} dissassembled to {}", file.string(), asmFile.string())); } catch(std::exception& ex) { result.output.push_back(fmt::format("ERROR: {} : {}", file.string(), ex.what())); result.failed = true; fs::remove(asmFile); } } fs::path dir_structure; if (params.recreateDirStructure && (pex.getGameType() == Pex::Binary::Fallout4Script || pex.getGameType() == Pex::Binary::StarfieldScript) && pex.getObjects().size() > 0){ std::string script_path = pex.getObjects()[0].getName().asString(); std::replace(script_path.begin(), script_path.end(), ':', '/'); dir_structure = fs::path(script_path).remove_filename(); } else if (!params.parentDir.empty()) { dir_structure = fs::relative(file, params.parentDir).remove_filename(); } fs::path basedir = !dir_structure.empty() ? (params.papyrusDir / dir_structure) : params.papyrusDir; if (!dir_structure.empty()){ fs::create_directories(basedir); } fs::path fileName = file.filename().replace_extension(".psc"); fs::path pscFile = basedir / fileName; try { std::ofstream pscStream(pscFile); if (pscStream.fail()){ throw std::runtime_error(fmt::format("Failed to open {} for writing", pscFile.string())); } Decompiler::PscCoder pscCoder( new Decompiler::StreamWriter(pscStream), params.outputComment, params.writeHeader, params.traceDecompilation, params.dumpTree, params.decompileDebugFuncs, params.debugLineComment, params.papyrusDir.string()); // using string instead of path here for C++14 compatability for staticlib targets pscCoder.code(pex); result.output.push_back(fmt::format("{} decompiled to {}", file.string(), pscFile.string())); } catch(std::exception& ex) { result.output.push_back(fmt::format("ERROR: {} : {}", file.string() , ex.what())); result.failed = true; fs::remove(pscFile); } return result; } size_t countFiles = 0; size_t failedFiles = 0; bool printStarfieldWarning = false; void processResult(const ProcessResults &result, const Params& params) { countFiles++; if (!printStarfieldWarning && result.isStarfield){ printStarfieldWarning = true; } if (result.failed){ ++failedFiles; for (auto line : result.output) { std::cerr << line << '\n'; } } else if (params.verbose || params.printInfo || params.printCompileTime) { // only output each individual successful result if `verbose` is on for (auto line : result.output) { std::cout << line << '\n'; } } } int main(int argc, char* argv[]) { Params args; auto result = getProgramOptions(argc, argv, args); if (result == Good) { auto start = std::chrono::steady_clock::now(); // ignore parallel if we are printing info if(!args.parallel || args.printInfo || args.printCompileTime) { for (auto path : args.inputs) { if (args.recursive && fs::is_directory(path)){ args.parentDir = path; // recursively get all files in the directory for (auto& entry : fs::recursive_directory_iterator(path)){ if (fs::is_regular_file(entry) && caselessCompare(entry.path().extension().string().c_str(), ".pex") == 0){ processResult(processFile(entry, args), args); } } } else if (fs::is_directory(path)){ args.parentDir = fs::path(); fs::directory_iterator end; fs::directory_iterator entry(path); while(entry != end) { if (caselessCompare(entry->path().extension().string().c_str(), ".pex") == 0) { processResult(processFile(path, args), args); } entry++; } } else { args.parentDir = fs::path(); processResult(processFile(path, args), args); } } } else { std::vector<std::future<ProcessResults>> results; for (auto& path : args.inputs) { if (args.recursive && fs::is_directory(path)){ args.parentDir = path; // recursively get all files in the directory for (auto& entry : fs::recursive_directory_iterator(path)){ if (fs::is_regular_file(entry) && caselessCompare(entry.path().extension().string().c_str(), ".pex") == 0){ results.push_back(std::move(std::async(std::launch::async, processFile, fs::path(entry.path()), args))); } } } else if (fs::is_directory(path)) { args.parentDir = fs::path(); fs::directory_iterator end; fs::directory_iterator entry(path); while(entry != end) { if (caselessCompare(entry->path().extension().string().c_str(), ".pex") == 0) { results.push_back(std::move(std::async(std::launch::async, processFile, fs::path(entry->path()), args))); } entry++; } } else { args.parentDir = fs::path(); results.push_back(std::move(std::async(std::launch::async, processFile, path, args))); } } for (auto& result : results) { auto pResult = result.get(); processResult(pResult, args); } countFiles = results.size(); } auto end = std::chrono::steady_clock::now(); auto diff = end - start; std::cout << countFiles << " files processed in " << std::chrono::duration <double> (diff).count() << " s" << std::endl; if (failedFiles > 0){ std::cout << failedFiles << " files failed to decompile." << std::endl; } if (countFiles > 0 && countFiles != failedFiles){ if (args.outputAssembly){ std::cout << "Disassembled scripts written to " << args.assemblyDir.string() << std::endl; } std::cout << "Decompiled scripts written to " << args.papyrusDir.string() << std::endl << std::endl; } if (printStarfieldWarning){ // TODO: Remove this warning when the CK comes out std::cout << "********************* STARFIELD PRELIMINARY SYNTAX WARNING *********************" << std::endl; std::cout << "The syntax for new features in Starfield (Guard, TryGuard, GetMatchingStructs) is not yet known." << std::endl; std::cout << "Decompiled Starfield scripts use guessed-at syntax for these features." << std::endl; std::cout << "This syntax should be considered as experimental, unstable, and subject to change." << std::endl << std::endl; std::cout << "The proper syntax will only be known when the Creation Kit comes out in early 2024." << std::endl; std::cout << "If you are using decompiled scripts as the basis for mods, please be aware of this," << std::endl; std::cout << "and be prepared to update your scripts when the final syntax is known." << std::endl << std::endl; std::cout << "The lines in the decompiled scripts which contain this guessed-at syntax are" << std::endl; std::cout << "marked with a comment beginning with '" << Decompiler::WARNING_COMMENT_PREFIX << "'." << std::endl; std::cout << "********************* STARFIELD PRELIMINARY SYNTAX WARNING *********************" << std::endl; } return 0; } if (result == HelpOrVersion){ return 0; } return 1; }
17,795
C++
.cpp
430
31.762791
175
0.571255
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,716
Binary.cpp
Orvid_Champollion/Pex/Binary.cpp
#include "Binary.hpp" #include <algorithm> #include <iostream> #include "FileReader.hpp" /** * @brief Default constructor. * * This constructor provides a Binary file with empty elements. */ Pex::Binary::Binary(): m_ScriptType(Unknown) { } /** * @brief Default destructor. * */ Pex::Binary::~Binary() { } /** * @brief Retrieve the Header part of the Binary * * @return a const Header. */ const Pex::Header &Pex::Binary::getHeader() const { return m_Header; } /** * @brief Retrieve the Header part of the Binary * * @return a modifiable Header. */ Pex::Header &Pex::Binary::getHeader() { return m_Header; } /** * @brief Retrieve the StringTable associated with the Binary * * @return a const string table. */ const Pex::StringTable &Pex::Binary::getStringTable() const { return m_StringTable; } /** * @brief Retrieve the StringTable associated with the Binary * * @return a modifiable string table. */ Pex::StringTable &Pex::Binary::getStringTable() { return m_StringTable; } /** * @brief Retrieve the debug info associated with the Binary. * * @return a const DebugInfo */ const Pex::DebugInfo &Pex::Binary::getDebugInfo() const { return m_DebugInfo; } /** * @brief Retrieve the debug info associated with the Binary. * * @return a modifiable DebugInfo */ Pex::DebugInfo &Pex::Binary::getDebugInfo() { return m_DebugInfo; } /** * @brief Retrieve the user flags definition stored in the Binary * * @return a const UserFlags; */ const Pex::UserFlags &Pex::Binary::getUserFlags() const { return m_UserFlags; } /** * @brief Retrieve the user flags definition stored in the Binary * * @return a modifiable UserFlags; */ Pex::UserFlags &Pex::Binary::getUserFlags() { return m_UserFlags; } /** * @brief Retrieve the list of Objects defined in the Binary * * @return a const Objects. */ const Pex::Objects &Pex::Binary::getObjects() const { return m_Objects; } /** * @brief Retrieve the list of Objects defined in the Binary * * @return a modifiable Objects. */ Pex::Objects &Pex::Binary::getObjects() { return m_Objects; } Pex::Binary::ScriptType Pex::Binary::getGameType() const { return m_ScriptType; } void Pex::Binary::setScriptType(Pex::Binary::ScriptType game_type) { m_ScriptType = game_type; } static bool namedLessThan(const Pex::NamedItem& a, const Pex::NamedItem& b) { return a.getName().asString() < b.getName().asString(); } void Pex::Binary::sort() { std::sort(m_Objects.begin(), m_Objects.end(), namedLessThan); std::sort(m_UserFlags.begin(), m_UserFlags.end(), namedLessThan); for (auto& obj : m_Objects) { std::sort(obj.getGuards().begin(), obj.getGuards().end(), namedLessThan); std::sort(obj.getProperties().begin(), obj.getProperties().end(), namedLessThan); std::sort(obj.getStates().begin(), obj.getStates().end(), namedLessThan); std::sort(obj.getStructInfos().begin(), obj.getStructInfos().end(), namedLessThan); std::sort(obj.getVariables().begin(), obj.getVariables().end(), namedLessThan); for (auto& state : obj.getStates()) { std::sort(state.getFunctions().begin(), state.getFunctions().end(), [this, obj, state](const Pex::Function& a, const Pex::Function& b) { auto linesA = this->getDebugInfo().getFunctionInfo(obj.getName(), state.getName(), a.getName()); auto lA = !linesA || linesA->getLineNumbers().empty() ? 0 : linesA->getLineNumbers()[0]; auto linesB = this->getDebugInfo().getFunctionInfo(obj.getName(), state.getName(), b.getName()); auto lB = !linesB || linesB->getLineNumbers().empty() ? 0 : linesB->getLineNumbers()[0]; if (lA == lB) { return a.getName().asString() < b.getName().asString(); } return lA < lB; }); } } }
3,905
C++
.cpp
144
23.701389
148
0.668803
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
752,727
Version.hpp
Orvid_Champollion/Decompiler/Version.hpp
#pragma once #define CHAMPOLLION_VERSION_MAJOR 1 #define CHAMPOLLION_VERSION_MINOR 3 #define CHAMPOLLION_VERSION_PATCH 2 #define MAKE_STR_HELPER(a_str) #a_str #define MAKE_STR(a_str) MAKE_STR_HELPER(a_str) #define CHAMPOLLION_VERSION_STRING "v" MAKE_STR(CHAMPOLLION_VERSION_MAJOR) "." MAKE_STR(CHAMPOLLION_VERSION_MINOR) "." MAKE_STR(CHAMPOLLION_VERSION_PATCH)
364
C++
.h
7
50.571429
154
0.79661
Orvid/Champollion
106
20
11
LGPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false