diff --git a/.github/workflows/package_main.yml b/.github/workflows/package_main.yml index f8dc73a6..282efc73 100644 --- a/.github/workflows/package_main.yml +++ b/.github/workflows/package_main.yml @@ -35,14 +35,15 @@ jobs: esp_idf_version: ${{ env.IDF_VERSION }} target: ${{ env.IDF_TARGET }} path: '.' - # the second command records the esptool version this build used, so + # the updater (ota_1) is built first: the emulator's build adds it to + # flash_args / flasher_args.json. The last command records the esptool version this build used, so # the packaging job packages the same one (its flash arguments follow it) - command: './patches.sh && idf.py build && python -m esptool version | tail -1 > build/esptool_version.txt' + command: './patches.sh && idf.py -C updater build && idf.py build && python -m esptool version | tail -1 > build/esptool_version.txt' - name: Zip up firmware binaries run: | # zip the firmware bin files and flash args - zip -j -r firmware-binaries.zip build/esp-box-emu.bin build/bootloader/bootloader.bin build/partition_table/partition-table.bin build/flash_args build/flasher_args.json build/esptool_version.txt + zip -j -r firmware-binaries.zip build/esp-box-emu.bin build/bootloader/bootloader.bin build/partition_table/partition-table.bin build/ota_data_initial.bin build/updater/esp-box-emu-updater.bin build/flash_args build/flasher_args.json build/esptool_version.txt - name: Upload Build Outputs uses: actions/upload-artifact@v4 @@ -53,6 +54,8 @@ jobs: build/bootloader/bootloader.bin build/partition_table/partition-table.bin build/esp-box-emu.bin + build/ota_data_initial.bin + build/updater/esp-box-emu-updater.bin build/flasher_args.json build/flash_args build/esptool_version.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 739c282c..8bc7c06d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,11 +101,27 @@ set(EMULATOR_COMPONENTS set( COMPONENTS - "main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer ${EMULATOR_COMPONENTS} box-emu gui menu" + "main esptool_py esp_lcd esp_psram task format display display_drivers monitor timer ${EMULATOR_COMPONENTS} box-emu gui menu settings devlink" CACHE STRING "List of components to include" + FORCE ) project(esp-box-emu) set(CMAKE_CXX_STANDARD 20) + +# The updater app (updater/) belongs in ota_1 (see partitions.csv): build it +# first (idf.py -C updater build) and `idf.py flash`, flash_args and +# flasher_args.json (the release package) put it there with the emulator. +set(UPDATER_BIN "${CMAKE_CURRENT_LIST_DIR}/updater/build/esp-box-emu-updater.bin") +if(EXISTS "${UPDATER_BIN}") + # (a copy in the build dir: flash_args lists it next to the others, and a + # rebuilt updater reconfigures this) + configure_file("${UPDATER_BIN}" "${CMAKE_BINARY_DIR}/updater/esp-box-emu-updater.bin" COPYONLY) + partition_table_get_partition_info(updater_offset "--partition-type app --partition-subtype ota_1" "offset") + esptool_py_flash_target_image(flash updater "${updater_offset}" "${CMAKE_BINARY_DIR}/updater/esp-box-emu-updater.bin") +else() + message(WARNING "no updater image (${UPDATER_BIN}): build it with idf.py -C updater build, then reconfigure, " + "or OTA updates and rollback have no updater to boot") +endif() diff --git a/README.md b/README.md index 266d19b5..f36a088e 100644 --- a/README.md +++ b/README.md @@ -211,9 +211,15 @@ git submodule update --init --recursive Then build, flash, and open the serial monitor with [ESP-IDF](https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/get-started/index.html): ```sh +idf.py -C updater build # once: the updater app, which goes in ota_1 idf.py -p PORT flash monitor ``` +The updater (`updater/`) is what over-USB updates (`tools/emulink`) reboot +into, and what a bad update rolls back to, so build it before the first +flash: the emulator's `idf.py flash` then writes both. After that, updates +can go over USB with `emulink ota`. + Replace `PORT` with your board's serial port. To exit the monitor, type `Ctrl-]`. diff --git a/bootloader_components/updater_switch/CMakeLists.txt b/bootloader_components/updater_switch/CMakeLists.txt new file mode 100644 index 00000000..342b6bcf --- /dev/null +++ b/bootloader_components/updater_switch/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "updater_switch.c" + PRIV_REQUIRES bootloader_support esp_hw_support soc spi_flash) diff --git a/bootloader_components/updater_switch/updater_switch.c b/bootloader_components/updater_switch/updater_switch.c new file mode 100644 index 00000000..ec6983ba --- /dev/null +++ b/bootloader_components/updater_switch/updater_switch.c @@ -0,0 +1,85 @@ +// Bootloader hook: boot the updater app (ota_1) once, when the app asked for +// it through an RTC register. +// +// The box's app cannot write its own flash: with the flash and the octal PSRAM +// at 120 MHz its writes report success but do not land (they do at 80 MHz, +// which Sonic 3 cannot afford). The bootloader runs the flash at the image +// header's speed, so it writes the otadata entry instead, before the usual +// boot partition selection reads it. +#include + +#include "bootloader_common.h" +#include "bootloader_flash_priv.h" +#include "esp_flash_partitions.h" +#include "esp_log.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/soc.h" + +// Shared with main/remote_control.hpp (BootSwitch). RTC_CNTL_STORE0 is +// reserved for the application; it survives a software reset. +#define UPDATER_SWITCH_REG RTC_CNTL_STORE0_REG +#define UPDATER_SWITCH_MAGIC 0x55504454u // "UPDT" + +static const char *TAG = "updater_switch"; + +// keep this file in the bootloader link (its hooks are weak symbols) +void bootloader_hooks_include(void) {} + +static bool find_partitions(esp_partition_pos_t *otadata, int *app_slots) { + esp_partition_info_t entry; + bool found = false; + *app_slots = 0; + for (int i = 0; i < ESP_PARTITION_TABLE_MAX_ENTRIES; i++) { + if (bootloader_flash_read(ESP_PARTITION_TABLE_OFFSET + i * sizeof(entry), &entry, sizeof(entry), false) != ESP_OK || + entry.magic != ESP_PARTITION_MAGIC) { + break; + } + if (entry.type == PART_TYPE_DATA && entry.subtype == PART_SUBTYPE_DATA_OTA) { + *otadata = entry.pos; + found = true; + } else if (entry.type == PART_TYPE_APP && (entry.subtype & ~PART_SUBTYPE_OTA_MASK) == PART_SUBTYPE_OTA_FLAG) { + (*app_slots)++; + } + } + return found && *app_slots >= 2; +} + +void bootloader_after_init(void) { + if (REG_READ(UPDATER_SWITCH_REG) != UPDATER_SWITCH_MAGIC) { + return; + } + REG_WRITE(UPDATER_SWITCH_REG, 0); // once: a failed updater boots the app again + esp_partition_pos_t otadata; + int slots; + if (!find_partitions(&otadata, &slots)) { + ESP_LOGE(TAG, "no otadata / ota_1 partition"); + return; + } + const uint32_t sector = 0x1000; + esp_ota_select_entry_t e[2]; + for (int i = 0; i < 2; i++) { + if (bootloader_flash_read(otadata.offset + i * sector, &e[i], sizeof(e[i]), false) != ESP_OK) { + return; + } + } + const bool v0 = bootloader_common_ota_select_valid(&e[0]), v1 = bootloader_common_ota_select_valid(&e[1]); + uint32_t seq = 0; + if (v0 && e[0].ota_seq > seq) seq = e[0].ota_seq; + if (v1 && e[1].ota_seq > seq) seq = e[1].ota_seq; + uint32_t next = seq + 1; + while ((next - 1) % slots != 1) next++; // slot 1: the updater + // overwrite the older (or an invalid) entry, so the current one survives a failure + const int target = !v0 ? 0 : !v1 ? 1 : (e[0].ota_seq <= e[1].ota_seq ? 0 : 1); + esp_ota_select_entry_t entry; + memset(&entry, 0xFF, sizeof(entry)); + entry.ota_seq = next; + entry.ota_state = ESP_OTA_IMG_VALID; + entry.crc = bootloader_common_ota_select_crc(&entry); + const size_t addr = otadata.offset + target * sector; + if (bootloader_flash_erase_sector(addr / sector) != ESP_OK || + bootloader_flash_write(addr, &entry, sizeof(entry), false) != ESP_OK) { + ESP_LOGE(TAG, "could not write otadata"); + return; + } + ESP_LOGI(TAG, "booting the updater (otadata seq %u)", (unsigned)next); +} diff --git a/boxart/adventures-of-batman-and-robin-snes.jpg b/boxart/adventures-of-batman-and-robin-snes.jpg new file mode 100644 index 00000000..55a61048 Binary files /dev/null and b/boxart/adventures-of-batman-and-robin-snes.jpg differ diff --git a/boxart/cattlecrisis-1-pico8.jpg b/boxart/cattlecrisis-1-pico8.jpg new file mode 100644 index 00000000..04f9a465 Binary files /dev/null and b/boxart/cattlecrisis-1-pico8.jpg differ diff --git a/boxart/celeste-pico8.jpg b/boxart/celeste-pico8.jpg new file mode 100644 index 00000000..2d4890d6 Binary files /dev/null and b/boxart/celeste-pico8.jpg differ diff --git a/boxart/just-one-boss-pico8.jpg b/boxart/just-one-boss-pico8.jpg new file mode 100644 index 00000000..79a3e6b8 Binary files /dev/null and b/boxart/just-one-boss-pico8.jpg differ diff --git a/boxart/kalikan_menu-6-pico8.jpg b/boxart/kalikan_menu-6-pico8.jpg new file mode 100644 index 00000000..fe06b39d Binary files /dev/null and b/boxart/kalikan_menu-6-pico8.jpg differ diff --git a/boxart/mgs.jpg b/boxart/mgs.jpg new file mode 100644 index 00000000..1c399735 Binary files /dev/null and b/boxart/mgs.jpg differ diff --git a/boxart/mossmoss-17-pico8.jpg b/boxart/mossmoss-17-pico8.jpg new file mode 100644 index 00000000..4276d8b1 Binary files /dev/null and b/boxart/mossmoss-17-pico8.jpg differ diff --git a/boxart/pico_ball-5-pico8.jpg b/boxart/pico_ball-5-pico8.jpg new file mode 100644 index 00000000..a9759d43 Binary files /dev/null and b/boxart/pico_ball-5-pico8.jpg differ diff --git a/boxart/praxis_fighter_x-2-pico8.jpg b/boxart/praxis_fighter_x-2-pico8.jpg new file mode 100644 index 00000000..43603ad5 Binary files /dev/null and b/boxart/praxis_fighter_x-2-pico8.jpg differ diff --git a/boxart/tony-hawks-pro-skater-2.jpg b/boxart/tony-hawks-pro-skater-2.jpg new file mode 100644 index 00000000..967191b4 Binary files /dev/null and b/boxart/tony-hawks-pro-skater-2.jpg differ diff --git a/components/box-emu/idf_component.yml b/components/box-emu/idf_component.yml index 820818b7..6123c337 100644 --- a/components/box-emu/idf_component.yml +++ b/components/box-emu/idf_component.yml @@ -16,4 +16,9 @@ dependencies: espp/serialization: '>=1.3.4' espp/task: '>=1.3.4' espp/timer: '>=1.3.4' - espp/usb_device: '>=1.3.4' + espp/usb_device: + # TEMP: take_msc_from_ejected_host() (esp-cpp/espp#898, merged as + # 08295c0); back to the registry once it is released + git: https://github.com/esp-cpp/espp.git + path: components/usb_device + version: 08295c0904224f25a42a518093021ee68c755ff2 diff --git a/components/box-emu/include/box-emu.hpp b/components/box-emu/include/box-emu.hpp index 17ed3cfc..c9e2a720 100644 --- a/components/box-emu/include/box-emu.hpp +++ b/components/box-emu/include/box-emu.hpp @@ -2,7 +2,9 @@ #include +#include #include +#include #include #include @@ -211,16 +213,42 @@ class BoxEmu : public espp::BaseComponent { // USB ///////////////////////////////////////////////////////////////////////////// - /// Expose the uSD card to a USB host as a mass storage device. - /// \note The card's volume is unmounted from the application while USB is - /// enabled (the emulator cannot read roms until it is disabled again); - /// the USB-Serial-JTAG console is disconnected as well, since it shares - /// the USB port. - /// \return True if USB mass storage was started. + // The composite USB device on the USB-C port (started at boot): + // - CDC: the console (stdout is routed there, teed to UART0); the + // USB-Serial-JTAG console is gone while it runs (it shares the PHY). + // - vendor (WebUSB): a framed byte stream for the link services (OTA, core + // dump, system, test control): set_vendor_rx() / vendor_write(). + // - MSC: the uSD card as a USB drive, ours (mounted at mount_point) until + // handed to the PC with initialize_usb(). + + /// Start the composite device (after initialize_sdcard()). + bool initialize_usb_device(); + bool is_usb_device_enabled() const { return usb_device_ != nullptr; } + /// Bytes received on the vendor interface (TinyUSB task context: do not + /// block; hand them to a DispatcherWorker). Set before the host talks. + void set_vendor_rx(std::function)> fn) { vendor_rx_ = std::move(fn); } + /// Send one frame on the vendor interface (all or nothing; serialized). + bool vendor_write(std::span frame); + /// Before a reboot into the ROM download mode. + void usb_prepare_for_rom_download(); + /// Hand the uSD card to the USB host as a mass storage device (its volume + /// is unmounted here until deinitialize_usb()). bool initialize_usb(); - /// Stop USB mass storage, reconnect the console and mount the card again. + /// Take the uSD card back from the USB host (mounted at mount_point again). bool deinitialize_usb(); + /// True while the USB host has the uSD card. bool is_usb_enabled() const; + // the names the shared link code uses (tab5-emu's) + bool initialize_usb_msc() { return initialize_usb(); } + void deinitialize_usb_msc() { deinitialize_usb(); } + bool usb_msc_host_has_card() const { return is_usb_enabled(); } + /// Called (under lvgl_mutex()) just before the card goes to the PC, from + /// whichever task hands it over: the USB link closes a file it is writing. + void set_before_sd_handover(std::function fn) { before_sd_handover_ = std::move(fn); } + + /// Buttons held by the USB link's test control (scripted input), merged + /// into gamepad_state() like any other input (GamepadState::buttons bits). + void set_remote_buttons(uint16_t buttons); protected: BoxEmu(); @@ -433,8 +461,11 @@ class BoxEmu : public espp::BaseComponent { std::shared_ptr haptic_motor_{nullptr}; // usb - std::atomic usb_enabled_{false}; std::unique_ptr usb_device_{nullptr}; + std::function before_sd_handover_; + std::function)> vendor_rx_; + std::mutex vendor_tx_mutex_; + uint16_t remote_buttons_{0}; // guarded by gamepad_state_mutex_ // The USB-Serial-JTAG console PHY, re-created after USB mass storage is stopped // so the console comes back (the OTG stack owns the PHY while it runs). usb_phy_handle_t jtag_phy_{nullptr}; diff --git a/components/box-emu/src/box-emu.cpp b/components/box-emu/src/box-emu.cpp index 58ba4ec9..1d3ee845 100644 --- a/components/box-emu/src/box-emu.cpp +++ b/components/box-emu/src/box-emu.cpp @@ -1,5 +1,9 @@ #include "box-emu.hpp" +#include +#include + +#include #include #include #include @@ -295,7 +299,16 @@ bool BoxEmu::initialize_gamepad() { GamepadState BoxEmu::gamepad_state() { std::lock_guard lock(gamepad_state_mutex_); - return gamepad_state_; + GamepadState state = gamepad_state_; + // buttons held by the USB link's test control (scripted input) + state.buttons |= remote_buttons_; + return state; +} + +void BoxEmu::set_remote_buttons(uint16_t buttons) { + std::lock_guard lock(gamepad_state_mutex_); + gamepad_press_latch_ |= (uint16_t)(buttons & ~remote_buttons_); + remote_buttons_ = buttons; } bool BoxEmu::update_gamepad_state() { @@ -330,20 +343,20 @@ bool BoxEmu::update_gamepad_state() { GamepadState BoxEmu::gamepad_state_latched() { std::lock_guard lock(gamepad_state_mutex_); GamepadState state = gamepad_state_; - state.buttons |= gamepad_press_latch_; + state.buttons |= gamepad_press_latch_ | remote_buttons_; gamepad_press_latch_ = 0; return state; } void BoxEmu::keypad_read(bool *up, bool *down, bool *left, bool *right, bool *enter, bool *escape) { - std::lock_guard lock(gamepad_state_mutex_); - *up = gamepad_state_.up; - *down = gamepad_state_.down; - *left = gamepad_state_.left; - *right = gamepad_state_.right; + const GamepadState state = gamepad_state(); + *up = state.up; + *down = state.down; + *left = state.left; + *right = state.right; - *enter = gamepad_state_.a || gamepad_state_.start; - *escape = gamepad_state_.b || gamepad_state_.select; + *enter = state.a || state.start; + *escape = state.b || state.select; } std::shared_ptr BoxEmu::keypad() const { @@ -599,114 +612,147 @@ void BoxEmu::set_haptic_effect(int effect) { // USB ///////////////////////////////////////////////////////////////////////////// -bool BoxEmu::is_usb_enabled() const { - return usb_enabled_; -} - -bool BoxEmu::initialize_usb() { - if (usb_enabled_) { - logger_.error("USB MSC already initialized!"); - return false; +bool BoxEmu::initialize_usb_device() { + if (usb_device_) { + return true; } - - logger_.info("USB MSC initialization"); - - // get the card from the filesystem initialization + logger_.info("USB composite device initialization"); auto card = sdcard(); - if (!card) { - logger_.error("No SD card found, skipping USB MSC initialization"); - return false; - } - - // The card cannot be shared: release the application's FAT volume before - // handing the card to the USB host. std::error_code ec; - if (!sdcard_->unmount(ec)) { - logger_.error("Could not unmount the SD card: {}", ec.message()); + // the MSC function mounts the card for us while we own it: release our mount + if (card && !sdcard_->unmount(ec)) { + logger_.error("Could not unmount the SD card for the drive function: {}", ec.message()); return false; } - // The USB-Serial-JTAG console and USB-OTG share the PHY; release it so the - // USB device stack can take it (it was re-created by deinitialize_usb()). + // USB device stack can take it. if (jtag_phy_) { - logger_.debug("Deleting JTAG PHY"); usb_del_phy(jtag_phy_); jtag_phy_ = nullptr; } - espp::UsbDevice::MscMedium medium; - medium.type = espp::UsbDevice::MscMedium::Type::SdCard; - medium.sd_card = card; - medium.base_path = mount_point; - medium.max_files = sdcard_max_files; - // The host gets the card right away; if the host ejects the drive the card is - // mounted for the application again (at mount_point) until it is re-attached. - medium.initial_owner = espp::UsbDevice::MscOwner::Host; - - espp::UsbDevice::MscFunction msc; - msc.interface_name = "Box-Emu uSD Card"; - msc.media = {medium}; - msc.auto_handover = true; - msc.on_event = [this](size_t lun, espp::UsbDevice::MscEvent event, espp::UsbDevice::MscOwner owner) { - if (event == espp::UsbDevice::MscEvent::OwnerChanged) { - logger_.info("uSD card now owned by the {}", - owner == espp::UsbDevice::MscOwner::App ? "application" : "USB host"); - } else if (event == espp::UsbDevice::MscEvent::FormatRequired) { - logger_.warn("uSD card has no filesystem; format it from the host"); - } - }; - espp::UsbDevice::Config config; - config.vid = 0x303A; // Espressif VID - config.pid = 0x4002; - config.manufacturer = "Finger563"; + // espp::UsbDevice's default (pid.codes) identity, so the stock espp tools + // (espp_ota, espp_coredump, the web consoles) and tools/emulink find it + config.manufacturer = "esp-cpp"; config.product = "ESP-Box-Emu"; - config.serial_number = "123456"; - config.msc = msc; - config.log_level = espp::Logger::Verbosity::INFO; + config.serial_number = "esp-box-emu"; + config.max_power_ma = 500; + config.log_level = espp::Logger::Verbosity::WARN; + // the console: logs on this CDC port (teed to UART0) + espp::UsbDevice::CdcFunction cdc; + cdc.interface_name = "ESP-Box-Emu console"; + cdc.route_console = true; + config.cdc = cdc; + // the framed services (OTA, core dump, system, test control) + espp::UsbDevice::VendorFunction vendor; + vendor.interface_name = "ESP-Box-Emu link"; + vendor.webusb = true; + vendor.landing_page_url = "esp-cpp.github.io/espp/apps/device_hub.html"; + vendor.on_receive = [this](std::span data) { + if (vendor_rx_) vendor_rx_(data); + }; + config.vendor = vendor; + // the uSD card as a USB drive: ours until handed over (initialize_usb()) + if (card) { + espp::UsbDevice::MscMedium medium; + medium.type = espp::UsbDevice::MscMedium::Type::SdCard; + medium.sd_card = card; + medium.base_path = mount_point; + medium.max_files = sdcard_max_files; + medium.initial_owner = espp::UsbDevice::MscOwner::App; + espp::UsbDevice::MscFunction msc; + msc.interface_name = "ESP-Box-Emu uSD Card"; + msc.media = {medium}; + msc.auto_handover = false; // only when asked (settings screen / host request) + msc.on_event = [this](size_t lun, espp::UsbDevice::MscEvent event, espp::UsbDevice::MscOwner owner) { + if (event == espp::UsbDevice::MscEvent::OwnerChanged) { + logger_.info("uSD card now owned by the {}", + owner == espp::UsbDevice::MscOwner::App ? "application" : "USB host"); + } else if (event == espp::UsbDevice::MscEvent::FormatRequired) { + logger_.warn("uSD card has no filesystem; format it from the host"); + } + }; + config.msc = msc; + } auto usb = std::make_unique(config); if (!usb->initialize(ec)) { logger_.error("Failed to initialize the USB device: {}", ec.message()); - // give the card back to the application usb.reset(); - sdcard_->mount(); + if (card) sdcard_->mount(); return false; } usb_device_ = std::move(usb); - usb_enabled_ = true; - logger_.info("USB MSC initialization DONE"); + logger_.info("USB composite device up (console, link{})", card ? ", uSD drive" : ""); + // espp routes only stdout to the CDC console; send stderr (the cores' error + // messages) there too. /dev/usbcons is the console device espp registers. + if (usb_device_->is_console_routed_to_cdc() && freopen("/dev/usbcons", "w", stderr)) { + setvbuf(stderr, nullptr, _IONBF, 0); + } + return true; +} + +bool BoxEmu::vendor_write(std::span frame) { + std::lock_guard lk(vendor_tx_mutex_); + return usb_device_ && usb_device_->write_vendor(frame); +} + +void BoxEmu::usb_prepare_for_rom_download() { + // The S3 has one internal USB PHY; the RTC-domain mux that hands it to the + // OTG controller (TinyUSB) survives the reset, so the ROM's download mode + // would come up on USB-Serial-JTAG with no PHY: detach, then give the PHY + // back to USB-Serial-JTAG (and the mux to the eFuse default). + if (usb_device_) { + usb_device_->disconnect(); + vTaskDelay(pdMS_TO_TICKS(100)); + } + usb_serial_jtag_ll_phy_enable_external(false); + RTCCNTL.usb_conf.sw_usb_phy_sel = 0; + RTCCNTL.usb_conf.sw_hw_usb_phy_sel = 0; +} +bool BoxEmu::initialize_usb() { + if (!usb_device_ || usb_device_->msc_lun_count() == 0) { + logger_.error("No uSD drive function"); + return false; + } + // the launcher reads the card (metadata, boxart) under the LVGL lock: hold + // it so the volume is not unmounted under one of its reads + std::lock_guard lk(lvgl_mutex()); + if (before_sd_handover_) before_sd_handover_(); + std::error_code ec; + if (!usb_device_->set_msc_owner(0, espp::UsbDevice::MscOwner::Host, ec)) { + logger_.error("Could not hand the uSD card to the USB host: {}", ec.message()); + return false; + } return true; } bool BoxEmu::deinitialize_usb() { - if (!usb_enabled_) { - logger_.warn("USB MSC not initialized"); + if (!usb_device_ || usb_device_->msc_lun_count() == 0) { return false; } - logger_.info("USB MSC deinitialization"); - // Stops the USB stack and releases the card (the destructor waits for the - // host's pending writes). - usb_device_.reset(); - usb_enabled_ = false; - - // reconnect the USB-Serial-JTAG console, see: - // https://github.com/espressif/idf-extra-components/pull/229 - usb_phy_config_t phy_conf; - memset(&phy_conf, 0, sizeof(phy_conf)); - phy_conf.controller = USB_PHY_CTRL_SERIAL_JTAG; - usb_new_phy(&phy_conf, &jtag_phy_); - - // mount the card for the application again + std::lock_guard lk(lvgl_mutex()); // see initialize_usb() std::error_code ec; - if (!sdcard_->mount(ec)) { - logger_.error("Could not mount the SD card again: {}", ec.message()); + // The PC stays attached (console, link), so this is taken on trust that it + // ejected the drive first (the settings screen says so; emulink drive off + // ejects it): one that did not may lose writes it had cached, as on an unplug. + if (!usb_device_->take_msc_from_ejected_host(0, ec)) { + logger_.error("Could not take the uSD card back: {}", ec.message()); return false; } return true; } +bool BoxEmu::is_usb_enabled() const { + if (!usb_device_ || usb_device_->msc_lun_count() == 0) { + return false; + } + const auto owner = usb_device_->msc_owner(0); + return owner.has_value() && *owner == espp::UsbDevice::MscOwner::Host; +} + ///////////////////////////////////////////////////////////////////////////// // Static Video Task: ///////////////////////////////////////////////////////////////////////////// diff --git a/components/darkforces/src/darkforces.cpp b/components/darkforces/src/darkforces.cpp index f1ce4495..5be0ee59 100644 --- a/components/darkforces/src/darkforces.cpp +++ b/components/darkforces/src/darkforces.cpp @@ -450,19 +450,7 @@ void init_darkforces(const std::string& gob_filename, uint8_t *romdata, size_t r s_gameDir = (slash == std::string::npos) ? std::string("/sdcard/") : s_gobPath.substr(0, slash + 1); fmt::print("[DarkForces] game directory: {}\n", s_gameDir); logMemory("before init"); -#if CONFIG_HEAP_TRACING_STANDALONE - // Debug: record every allocation that is not freed by deinit_darkforces(). - { - static heap_trace_record_t* records = nullptr; - static constexpr size_t NUM_RECORDS = 6000; - if (!records) - { - records = (heap_trace_record_t*)heap_caps_calloc(NUM_RECORDS, sizeof(heap_trace_record_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (records) { ESP_ERROR_CHECK(heap_trace_init_standalone(records, NUM_RECORDS)); } - } - if (records) { ESP_ERROR_CHECK(heap_trace_start(HEAP_TRACE_LEAKS)); } - } -#endif + // (CONFIG_HEAP_TRACING_STANDALONE: app_main traces each cart's lifetime and lists what it leaves) startHangDetector(); #if CONFIG_ESP_TASK_WDT_EN esp_task_wdt_add(NULL); @@ -887,10 +875,4 @@ void deinit_darkforces() darkforces_free_shared_memory(); TFE_Memory::poolEnd(); logMemory("after deinit"); -#if CONFIG_HEAP_TRACING_STANDALONE - heap_trace_stop(); - fmt::print("[DarkForces] ---- heap trace (allocations not freed) ----\n"); - heap_trace_dump(); - fmt::print("[DarkForces] ---- end heap trace ----\n"); -#endif } diff --git a/components/devlink/CMakeLists.txt b/components/devlink/CMakeLists.txt new file mode 100644 index 00000000..0aee9b96 --- /dev/null +++ b/components/devlink/CMakeLists.txt @@ -0,0 +1,12 @@ +idf_component_register( + INCLUDE_DIRS "include" + SRC_DIRS "src" + PRIV_REQUIRES esp_system + REQUIRES app_update coredump dispatcher monitor system box-emu) +# no OTA service in the emulator: an update goes through the updater app in +# ota_1 (see updater/). Writing the flash from the emulator, which runs its +# code from PSRAM (SPIRAM_FETCH_INSTRUCTIONS), corrupts its PSRAM heap and +# fails the image check. +target_compile_definitions(${COMPONENT_LIB} PUBLIC DEVLINK_HAS_OTA=0) +# keep the last panic's reason across the reset (DevLink::last_panic()) +target_link_options(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=esp_panic_handler" "-Wl,--wrap=panic_abort") diff --git a/components/devlink/idf_component.yml b/components/devlink/idf_component.yml new file mode 100644 index 00000000..e2991559 --- /dev/null +++ b/components/devlink/idf_component.yml @@ -0,0 +1,7 @@ +## IDF Component Manager Manifest File +dependencies: + idf: '>=5.5' + espp/coredump: '>=1.4.2' + espp/dispatcher: '>=1.4.2' + espp/monitor: '>=1.4.2' + espp/system: '>=1.4.2' diff --git a/components/devlink/include/devlink.hpp b/components/devlink/include/devlink.hpp new file mode 100644 index 00000000..064542cd --- /dev/null +++ b/components/devlink/include/devlink.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include +#include + +#include "coredump.hpp" +#include "coredump_service.hpp" +#include "dispatcher_worker.hpp" +#include "monitor_service.hpp" +#include "system_service.hpp" + +#include +#include + +#include "box-emu.hpp" + +/// Check the heap around every flash-touching request (debugging aid). +#ifndef DEVLINK_HEAP_CHECK +#define DEVLINK_HEAP_CHECK 0 +#endif +#if DEVLINK_HAS_OTA +#include "ota.hpp" +#include "ota_service.hpp" +#endif + +/// A module whose requests touch the flash (erase / write / read), run under +/// the launcher's LVGL lock. While the flash is busy the cache is off and only +/// interrupt handlers placed in internal RAM run; the display's SPI "transfer +/// done" interrupt is one and calls into LVGL (flash / PSRAM): a screen update +/// finishing during an OTA erase panics (esp-box-emu). LVGL waits for its +/// transfers before it lets go of the lock, so none is in flight meanwhile. +template class FlashGuarded { +public: + explicit FlashGuarded(Module &module) : module_(module) {} + uint8_t module_id() const { return module_.module_id(); } + espp::DispatcherModuleInfo module_info() const { return module_.module_info(); } + void handle(const espp::stream_frame::Frame &frame) { + std::lock_guard lk(BoxEmu::lvgl_mutex()); +#if DEVLINK_HEAP_CHECK + if (!heap_caps_check_integrity_all(true)) abort_corrupt("before", frame); +#endif + module_.handle(frame); +#if DEVLINK_HEAP_CHECK + if (!heap_caps_check_integrity_all(true)) abort_corrupt("after", frame); +#endif + } + +protected: +#if DEVLINK_HEAP_CHECK + [[noreturn]] static void abort_corrupt(const char *when, const espp::stream_frame::Frame &frame) { + static char msg[80]; + const bool internal_ok = heap_caps_check_integrity(MALLOC_CAP_INTERNAL, false); + const bool psram_ok = heap_caps_check_integrity(MALLOC_CAP_SPIRAM, false); + snprintf(msg, sizeof(msg), "heap corrupt %s request: internal %s, psram %s (frame @%p)", when, + internal_ok ? "ok" : "BAD", psram_ok ? "ok" : "BAD", (const void *)&frame); + esp_system_abort(msg); + } +#endif + Module &module_; +}; + +/// The framed services on the composite USB device's vendor interface, one +/// espp::DispatcherWorker routing them (shared by esp-box-emu and tab5-emu): +/// +/// | module | service | host tool | +/// |--------|-------------------------------------------|--------------------------| +/// | 0 | OTA (DEVLINK_HAS_OTA: a two-slot layout) | espp_ota, emulink ota | +/// | 4 | core dump of the last crash | espp_coredump, emulink | +/// | 7 | system info, reboot, ROM download mode | emulink reboot | +/// | 8 | heap / task monitor | the espp Device Hub | +/// | 0x20 | test control (registered by the app) | emulink | +/// +/// The device answers discovery, so the hosted espp web consoles find them. +class DevLink { +public: + struct Config { + std::string device_name; ///< advertised through discovery + std::string firmware; ///< firmware version, advertised through discovery + }; + + explicit DevLink(const Config &config); + ~DevLink(); + + /// Register an application module (e.g. the test control service). + template void register_module(Module &module) { + worker_->register_module(module); + } + + /// Send one frame to the host (serialized; all or nothing). + static void send(std::span frame); + + /// The running image booted after an update and has not been confirmed + /// yet: confirm it (call once the app is up). No-op otherwise. + static void mark_app_valid(); + + /// After a panic reset: what it was ("reason (detail) at PC on core N"), + /// kept in RTC memory (no core dump needed); "" otherwise. + static std::string last_panic(); + +protected: + std::unique_ptr worker_; + espp::CoreDump core_dump_; + std::unique_ptr core_dump_service_; + std::unique_ptr> core_dump_guarded_; + std::unique_ptr system_service_; + std::unique_ptr monitor_service_; +#if DEVLINK_HAS_OTA + std::unique_ptr ota_; + std::unique_ptr ota_service_; + std::unique_ptr> ota_guarded_; +#endif +}; diff --git a/components/devlink/src/devlink.cpp b/components/devlink/src/devlink.cpp new file mode 100644 index 00000000..933dcec0 --- /dev/null +++ b/components/devlink/src/devlink.cpp @@ -0,0 +1,201 @@ +#include "devlink.hpp" + +#include +#include +#include + +#include +#include +#include +#if CONFIG_IDF_TARGET_ARCH_XTENSA +#include +#include +#endif +#include +#include +#if CONFIG_IDF_TARGET_ESP32S3 +#include +#endif +#include +#include +#include + +#include "box-emu.hpp" + +void DevLink::send(std::span frame) { BoxEmu::get().vendor_write(frame); } + +DevLink::DevLink(const Config &config) { + auto &emu = BoxEmu::get(); + worker_ = std::make_unique(espp::DispatcherWorker::Config{ + .send = &DevLink::send, + .on_overflow = + [this]() { +#if DEVLINK_HAS_OTA + if (ota_service_) ota_service_->on_rx_overflow(); +#endif + }, + // ~3.5 KB used at the high-water mark (file transfers, core dump reads); + // internal RAM, since the core dump service reads the flash + .task_config = {.name = "devlink", .stack_size_bytes = 6144}, + }); + core_dump_service_ = std::make_unique(core_dump_, espp::CoreDumpService::Config{ + .send = &DevLink::send, + }); + system_service_ = std::make_unique(espp::SystemService::Config{ + .send = &DevLink::send, + .on_reboot_request = + [](espp::SystemService::RebootKind kind) { + if (kind == espp::SystemService::RebootKind::Bootloader) { + BoxEmu::get().usb_prepare_for_rom_download(); + } + return true; + }, + }); + monitor_service_ = std::make_unique(espp::MonitorService::Config{ + .send = &DevLink::send, + }); + core_dump_guarded_ = std::make_unique>(*core_dump_service_); + worker_->register_module(*core_dump_guarded_); + worker_->register_module(*system_service_); + worker_->register_module(*monitor_service_); +#if DEVLINK_HAS_OTA + ota_ = std::make_unique(espp::Ota::Config{}); + ota_service_ = std::make_unique(*ota_, espp::OtaService::Config{ + .send = &DevLink::send, + }); + ota_guarded_ = std::make_unique>(*ota_service_); + worker_->register_module(*ota_guarded_); +#endif + worker_->serve_discovery(config.device_name, config.firmware); + emu.set_vendor_rx([this](std::span data) { worker_->push(data); }); +} + +DevLink::~DevLink() { BoxEmu::get().set_vendor_rx(nullptr); } + +void DevLink::mark_app_valid() { + esp_ota_img_states_t state; + const esp_partition_t *running = esp_ota_get_running_partition(); + if (running && esp_ota_get_state_partition(running, &state) == ESP_OK && state == ESP_OTA_IMG_PENDING_VERIFY) { + esp_ota_mark_app_valid_cancel_rollback(); + fmt::print("devlink: the updated firmware is up; marked valid\n"); + } +} + +// The last panic, kept across the reset in RTC memory: a crash in the middle of +// a flash operation (an OTA erase) cannot write its core dump, and the console +// is the USB CDC port, which dies with the chip. The wrappers run in the panic +// path (possibly with the cache off): IRAM, and only plain byte copies. +namespace { +struct LastPanic { + uint32_t magic; + uint32_t addr; + int32_t core; + int32_t exception; + char reason[64]; + char detail[96]; + char task[16]; + uint32_t excvaddr; + uint32_t backtrace[20]; // Xtensa: the abort()'s caller chain +}; +constexpr uint32_t kPanicMagic = 0x50414e43; // "PANC" +RTC_NOINIT_ATTR LastPanic s_last_panic; +DRAM_ATTR volatile bool s_aborting = false; +IRAM_ATTR void copy_str(char *dst, size_t n, const char *src) { + size_t i = 0; + if (src) { + for (; i + 1 < n && src[i]; ++i) dst[i] = src[i]; + } + dst[i] = 0; +} +} // namespace + +extern "C" void __real_esp_panic_handler(panic_info_t *info); +extern "C" IRAM_ATTR void __wrap_esp_panic_handler(panic_info_t *info) { + // an abort() gets here too (panic_abort() traps): keep its message + if (s_aborting) { + __real_esp_panic_handler(info); + return; + } + s_last_panic.magic = kPanicMagic; + s_last_panic.addr = (uint32_t)info->addr; + s_last_panic.core = info->core; + s_last_panic.exception = (int32_t)info->exception; + copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), info->reason); + copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), info->description); + TaskHandle_t t = xTaskGetCurrentTaskHandle(); + copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?"); + std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0); +#if CONFIG_IDF_TARGET_ARCH_XTENSA + // an exception or interrupt (a cache error) has no address of its own: keep + // the interrupted code's PC, the faulting address and its caller chain + if (const auto *f = static_cast(info->frame)) { + if (!s_last_panic.addr) s_last_panic.addr = esp_cpu_process_stack_pc(f->pc); + s_last_panic.excvaddr = f->excvaddr; + if (info->reason && info->reason[0] == 'C' && info->reason[1] == 'a' && info->reason[2] == 'c') { // "Cache error" + // which access the cache refused (another core or a DMA may have made it) + esp_cache_err_info_t err = {}; + esp_cache_err_get_panic_info(&err); + copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), err.err_str ? err.err_str : "cache disabled"); + s_last_panic.excvaddr = err.vaddr; +#if CONFIG_IDF_TARGET_ESP32S3 + // the MMU fault's virtual address and source (code bits 19:16: 1 cpu + // miss, 2 preload, 3 writeback, 6/7 external DMA tx/rx) + s_last_panic.excvaddr = REG_READ(EXTMEM_CACHE_MMU_FAULT_VADDR_REG); + s_last_panic.exception = (int32_t)REG_READ(EXTMEM_CACHE_MMU_FAULT_CONTENT_REG); +#endif + } + esp_backtrace_frame_t frame{.pc = (uint32_t)f->pc, .sp = (uint32_t)f->a1, .next_pc = (uint32_t)f->a0, .exc_frame = f}; + for (int i = 0; i < 20; ++i) { + s_last_panic.backtrace[i] = esp_cpu_process_stack_pc(frame.pc); + if (!frame.next_pc || !esp_backtrace_get_next_frame(&frame)) break; + } + } +#endif + __real_esp_panic_handler(info); +} + +extern "C" void __real_panic_abort(const char *details); +IRAM_ATTR void note_task_and_backtrace() { + TaskHandle_t t = xTaskGetCurrentTaskHandle(); + copy_str(s_last_panic.task, sizeof(s_last_panic.task), t ? pcTaskGetName(t) : "?"); + std::fill(std::begin(s_last_panic.backtrace), std::end(s_last_panic.backtrace), 0); +#if CONFIG_IDF_TARGET_ARCH_XTENSA + esp_backtrace_frame_t frame{}; + esp_backtrace_get_start(&frame.pc, &frame.sp, &frame.next_pc); + for (int i = 0; i < 20; ++i) { + s_last_panic.backtrace[i] = esp_cpu_process_stack_pc(frame.pc); + if (!esp_backtrace_get_next_frame(&frame)) break; + } +#endif +} + +extern "C" IRAM_ATTR void __wrap_panic_abort(const char *details) { + s_aborting = true; + note_task_and_backtrace(); + s_last_panic.magic = kPanicMagic; + s_last_panic.addr = 0; + s_last_panic.excvaddr = 0; + s_last_panic.core = -1; + s_last_panic.exception = -1; + copy_str(s_last_panic.reason, sizeof(s_last_panic.reason), "abort"); + copy_str(s_last_panic.detail, sizeof(s_last_panic.detail), details); + __real_panic_abort(details); +} + +std::string DevLink::last_panic() { + if (esp_reset_reason() != ESP_RST_PANIC || s_last_panic.magic != kPanicMagic) { + return ""; + } + s_last_panic.reason[sizeof(s_last_panic.reason) - 1] = 0; + s_last_panic.detail[sizeof(s_last_panic.detail) - 1] = 0; + s_last_panic.task[sizeof(s_last_panic.task) - 1] = 0; + std::string bt; + for (auto pc : s_last_panic.backtrace) { + if (pc) bt += fmt::format(" {:#010x}", pc); + } + return fmt::format("{} ({}) at {:#010x} on core {} in task '{}', exception {:#x}{}{}{}", s_last_panic.reason, + s_last_panic.detail, s_last_panic.addr, s_last_panic.core, s_last_panic.task, + (uint32_t)s_last_panic.exception, + s_last_panic.excvaddr ? fmt::format(", address {:#010x}", s_last_panic.excvaddr) : "", + bt.empty() ? "" : "; backtrace", bt); +} diff --git a/components/doom/prboom/z_zone.c b/components/doom/prboom/z_zone.c index 680a4170..b3bf4d29 100644 --- a/components/doom/prboom/z_zone.c +++ b/components/doom/prboom/z_zone.c @@ -176,11 +176,22 @@ void Z_Close(void) } #include "pool_allocator.h" +#include +// What Doom leaves of the PSRAM heap for the rest of the firmware (the USB +// link, the menu, the SD card's buffers). +#define ZONE_PSRAM_RESERVE (128 * 1024) + +// The 4 MB pool first, then PSRAM only: a failure makes Z_Malloc() purge its +// PU_CACHE blocks and retry. Falling back to plain malloc() let Doom II's +// precache take the internal RAM too, after which the SD card driver could not +// get its 512 B DMA bounce buffer and a WAD read failed (a crash in +// R_CachePatchNum()). static void* my_malloc(size_t size) { void * ptr = pool_alloc(size); - if (!ptr) ptr = (malloc)(size); + if (!ptr && heap_caps_get_free_size(MALLOC_CAP_SPIRAM) > size + ZONE_PSRAM_RESERVE) + ptr = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); return ptr; } diff --git a/components/doom/src/doom.cpp b/components/doom/src/doom.cpp index bb044015..35c39578 100644 --- a/components/doom/src/doom.cpp +++ b/components/doom/src/doom.cpp @@ -85,6 +85,7 @@ extern "C" { #include #include #include +#include #define AUDIO_SAMPLE_RATE (22050 / 2) @@ -723,9 +724,10 @@ void deinit_doom() { audio_task.reset(); // NOTE: we intentionally do NOT call music_player->shutdown() here. Doing so // left the OPL player unable to restart, so music was silent on every launch - // after the first. The OPL mix_buffer / callback-queue leak it was meant to - // fix is now handled inside OPL_Init() (it frees its old buffers before - // re-allocating), so re-launching keeps music working and doesn't leak. + // after the first. Release just the OPL library's buffers (its ~44 KB mix + // buffer and the callback queue) so they do not stay allocated until the + // next launch; OPL_Init() makes new ones. + OPL_Shutdown(); // End display I_EndDisplay(); // Free memory diff --git a/components/gui/CMakeLists.txt b/components/gui/CMakeLists.txt index 3c5cdab6..7301f08f 100644 --- a/components/gui/CMakeLists.txt +++ b/components/gui/CMakeLists.txt @@ -2,4 +2,4 @@ idf_component_register( INCLUDE_DIRS "include" PRIV_INCLUDE_DIRS "generated" SRC_DIRS "src" "generated" "generated/screens" "generated/components" "generated/images" - REQUIRES lvgl timer display logger jpeg rom_info box-emu) + REQUIRES lvgl timer display logger jpeg rom_info settings box-emu) diff --git a/components/gui/include/console_art.hpp b/components/gui/include/console_art.hpp new file mode 100644 index 00000000..2cb664c7 --- /dev/null +++ b/components/gui/include/console_art.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include + +#include "lvgl.h" + +#include "rom_info.hpp" + +/// Draw a small icon of `info`'s console (a gamepad, a handheld, a disc...) +/// out of plain LVGL objects into a new `h * 8 / 5` x `h` container in +/// `parent`. Generic shapes in the console's accent color; no logos. +lv_obj_t *console_icon_create(lv_obj_t *parent, const ConsoleInfo &info, int h); + +/// A rounded badge in the console's accent color: the icon and the console's +/// name, `h` pixels tall, sized to its content. +lv_obj_t *console_badge_create(lv_obj_t *parent, const ConsoleInfo &info, int h, const lv_font_t *font); + +/// The SD card art for `info`, if there is any: `/boxart/consoles/.jpg`. +std::string console_art_path(const std::string &root, const ConsoleInfo &info); diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp index b5448bee..681e90d6 100644 --- a/components/gui/include/gui.hpp +++ b/components/gui/include/gui.hpp @@ -11,7 +11,9 @@ #include "logger.hpp" #include "box-emu.hpp" +#include "console_art.hpp" #include "rom_info.hpp" +#include "settings.hpp" class Gui { public: @@ -79,6 +81,8 @@ class Gui { void set_video_setting(VideoSetting setting); + void set_resume_last_save(bool on); + void clear_rom_list(); void add_rom(const RomInfo& rom); @@ -114,6 +118,7 @@ class Gui { } haptic_waveform_ = new_waveform; set_waveform_(haptic_waveform_); + AppSettings::get().modify([new_waveform](Settings &st) { st.haptic_waveform = new_waveform; }); update_haptic_waveform_label(); } @@ -128,6 +133,20 @@ class Gui { void update_haptic_waveform_label(); void update_rom_list(); + /// Re-read metadata.csv even if its modification time did not change (FAT + /// times are coarse, and without a set clock they may not move at all). + void reload_rom_list() { + std::lock_guard lk(mutex_); + metadata_last_modified_ = std::filesystem::file_time_type::min(); + update_rom_list(); + } + /// The games in list order (grouped by console). + std::vector rom_infos() const { + std::lock_guard lk(mutex_); + return rom_infos_; + } + /// Select the first game whose name or rom path contains `text` + bool select_rom_matching(std::string_view text); protected: void init_ui(); @@ -148,11 +167,16 @@ class Gui { set_audio_level(box.volume()); set_brightness(box.brightness()); set_video_setting(BoxEmu::get().video_setting()); + set_resume_last_save(AppSettings::get().get_settings().resume_last_save); } VideoSetting get_video_setting(); void on_rom_focused(int index); + /// The roller moved to `row`: select its game, or step past a console + /// header in the direction the roller moved. + void on_roller_row(int row); + void show_console(Console console); void on_mute_button_pressed(const std::vector& data) { set_mute(BoxEmu::get().is_muted()); @@ -180,10 +204,16 @@ class Gui { void update() { if (!paused_) { std::lock_guard lk(mutex_); + sync_usb_drive(); lv_task_handler(); } } + /// Follow a USB drive hand-over made elsewhere (the USB link's test control): + /// the settings label, and the rom list once the card is back. + void sync_usb_drive(); + bool usb_drive_shown_{false}; + static void event_callback(lv_event_t *e) { lv_event_code_t event_code = lv_event_get_code(e); auto user_data = lv_event_get_user_data(e); @@ -220,9 +250,22 @@ class Gui { void on_scroll(lv_event_t *e); // LVLG gui objects - std::vector rom_infos_; + std::vector rom_infos_; ///< grouped by console (Console order) std::atomic focused_rom_{-1}; lv_image_dsc_t focused_boxart_; + // the roller shows a header row before each console's games: the rom + // index of each roller row, -1 for a header + std::vector roller_rows_; + int roller_row_{0}; + + // the selected game's console, in the header: its SD card art or a badge + lv_obj_t *console_area_{nullptr}; + int shown_console_{-1}; + uint8_t *console_art_data_{nullptr}; + lv_image_dsc_t console_art_{}; + + lv_obj_t *resume_button_{nullptr}; + lv_obj_t *resume_label_{nullptr}; // style for buttons lv_style_t button_style_; diff --git a/components/gui/src/console_art.cpp b/components/gui/src/console_art.cpp new file mode 100644 index 00000000..771973c8 --- /dev/null +++ b/components/gui/src/console_art.cpp @@ -0,0 +1,135 @@ +#include "console_art.hpp" + +#include +#include + +namespace { + +lv_obj_t *shape(lv_obj_t *parent, int x, int y, int w, int h, int radius, lv_color_t color) { + auto *o = lv_obj_create(parent); + lv_obj_remove_style_all(o); + lv_obj_remove_flag(o, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(o, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_pos(o, x, y); + lv_obj_set_size(o, w, h); + lv_obj_set_style_radius(o, radius, 0); + lv_obj_set_style_bg_color(o, color, 0); + lv_obj_set_style_bg_opa(o, LV_OPA_COVER, 0); + return o; +} + +// a + shaped d-pad centered at (cx, cy), `s` across +void dpad(lv_obj_t *parent, int cx, int cy, int s, lv_color_t color) { + const int t = std::max(2, s / 3); + shape(parent, cx - s / 2, cy - t / 2, s, t, 1, color); + shape(parent, cx - t / 2, cy - s / 2, t, s, 1, color); +} + +void dot(lv_obj_t *parent, int cx, int cy, int d, lv_color_t color) { + shape(parent, cx - d / 2, cy - d / 2, d, d, LV_RADIUS_CIRCLE, color); +} + +} // namespace + +lv_obj_t *console_icon_create(lv_obj_t *parent, const ConsoleInfo &info, int h) { + const int w = h * 8 / 5; + auto *box = lv_obj_create(parent); + lv_obj_remove_style_all(box); + lv_obj_remove_flag(box, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(box, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_size(box, w, h); + + const lv_color_t body = lv_color_white(); + const lv_color_t accent = lv_color_hex(info.color); + const lv_color_t dark = lv_color_hex(0x202428); + + switch (info.shape) { + case ConsoleShape::GAMEPAD: { + // a wide rounded controller: d-pad left, two buttons right + const int bh = h * 6 / 10, by = (h - bh) / 2; + shape(box, 0, by, w, bh, bh / 2, body); + dpad(box, w * 27 / 100, h / 2, bh * 6 / 10, accent); + dot(box, w * 66 / 100, h / 2 + bh / 8, bh / 4, accent); + dot(box, w * 80 / 100, h / 2 - bh / 8, bh / 4, accent); + break; + } + case ConsoleShape::HANDHELD_TALL: { + // a portrait handheld: screen on top, d-pad and buttons below it + const int bw = h * 66 / 100, bx = (w - bw) / 2; + shape(box, bx, 0, bw, h, bw / 6, body); + shape(box, bx + bw / 8, h / 10, bw * 6 / 8, h * 4 / 10, 2, dark); + dpad(box, bx + bw * 30 / 100, h * 72 / 100, bw * 3 / 10, accent); + dot(box, bx + bw * 68 / 100, h * 76 / 100, bw / 6, accent); + dot(box, bx + bw * 84 / 100, h * 66 / 100, bw / 6, accent); + break; + } + case ConsoleShape::HANDHELD_WIDE: { + // a landscape handheld: screen in the middle, d-pad and buttons beside it + const int bh = h * 7 / 10, by = (h - bh) / 2; + shape(box, 0, by, w, bh, bh * 4 / 10, body); + shape(box, w * 30 / 100, by + bh / 6, w * 40 / 100, bh * 2 / 3, 2, dark); + dpad(box, w * 15 / 100, h / 2, bh * 4 / 10, accent); + dot(box, w * 82 / 100, h / 2 + bh / 10, bh / 5, accent); + dot(box, w * 90 / 100, h / 2 - bh / 10, bh / 5, accent); + break; + } + case ConsoleShape::DISC: { + // a CD: rim, label ring, hole + const int d = h, x = (w - d) / 2; + shape(box, x, 0, d, d, LV_RADIUS_CIRCLE, body); + dot(box, w / 2, h / 2, d * 45 / 100, accent); + dot(box, w / 2, h / 2, d * 15 / 100, body); + break; + } + case ConsoleShape::COMPUTER: { + // a monitor on a stand + const int mw = w * 70 / 100, mh = h * 66 / 100, mx = (w - mw) / 2; + shape(box, mx, 0, mw, mh, 3, body); + shape(box, mx + mw / 12, mh / 8, mw * 10 / 12, mh * 6 / 8, 1, accent); + shape(box, w / 2 - w / 14, mh, w / 7, h / 6, 0, body); + shape(box, w / 2 - w / 5, h - h / 8, w * 2 / 5, h / 8, 2, body); + break; + } + case ConsoleShape::FANTASY: { + // a tiny cartridge-console: a square with a screen of palette dots + const int s = h, x = (w - s) / 2; + shape(box, x, 0, s, s, s / 6, body); + const int sx = x + s / 8, sy = s / 8, ss = s * 6 / 8; + shape(box, sx, sy, ss, ss * 3 / 4, 2, dark); + const uint32_t palette[] = {0xFF004D, 0xFFA300, 0xFFEC27, 0x00E436}; + const int p = std::max(2, ss / 6); + for (int i = 0; i < 4; i++) { + shape(box, sx + ss / 10 + i * (p + p / 3), sy + ss * 3 / 8 - p / 2, p, p, 0, lv_color_hex(palette[i])); + } + break; + } + } + return box; +} + +lv_obj_t *console_badge_create(lv_obj_t *parent, const ConsoleInfo &info, int h, const lv_font_t *font) { + auto *badge = lv_obj_create(parent); + lv_obj_remove_style_all(badge); + lv_obj_remove_flag(badge, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(badge, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_size(badge, LV_SIZE_CONTENT, h); + lv_obj_set_style_radius(badge, h / 2, 0); + lv_obj_set_style_bg_color(badge, lv_color_hex(info.color), 0); + lv_obj_set_style_bg_opa(badge, LV_OPA_COVER, 0); + lv_obj_set_style_pad_hor(badge, h / 3, 0); + lv_obj_set_style_pad_column(badge, h / 4, 0); + lv_obj_set_flex_flow(badge, LV_FLEX_FLOW_ROW); + lv_obj_set_flex_align(badge, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + console_icon_create(badge, info, h * 6 / 10); + auto *label = lv_label_create(badge); + lv_label_set_text(label, info.name); + lv_obj_set_style_text_color(label, lv_color_white(), 0); + if (font) lv_obj_set_style_text_font(label, font, 0); + return badge; +} + +std::string console_art_path(const std::string &root, const ConsoleInfo &info) { + const std::string path = root + "/boxart/consoles/" + info.key + ".jpg"; + std::error_code ec; + return std::filesystem::exists(path, ec) ? path : std::string{}; +} diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp index f5e6a15b..64653a86 100644 --- a/components/gui/src/gui.cpp +++ b/components/gui/src/gui.cpp @@ -8,6 +8,7 @@ extern "C" { void Gui::set_mute(bool muted) { BoxEmu::get().mute(muted); + AppSettings::get().modify([muted](Settings &s) { s.muted = muted; }); if (muted) { lv_obj_add_state(ui_mutebutton, LV_STATE_CHECKED); } else { @@ -19,17 +20,27 @@ void Gui::set_audio_level(int new_audio_level) { new_audio_level = std::clamp(new_audio_level, 0, 100); lv_bar_set_value(ui_volumebar, new_audio_level, LV_ANIM_ON); BoxEmu::get().volume(new_audio_level); + AppSettings::get().modify([new_audio_level](Settings &s) { s.volume = new_audio_level; }); } void Gui::set_brightness(int new_brightness) { new_brightness = std::clamp(new_brightness, 10, 100); lv_bar_set_value(ui_brightnessbar, new_brightness, LV_ANIM_ON); BoxEmu::get().brightness((float)new_brightness); + AppSettings::get().modify([new_brightness](Settings &s) { s.brightness = new_brightness; }); } void Gui::set_video_setting(VideoSetting setting) { BoxEmu::get().video_setting(setting); lv_dropdown_set_selected(ui_videosettingdropdown, (int)setting); + AppSettings::get().modify([setting](Settings &s) { s.video_setting = static_cast(setting); }); +} + +void Gui::set_resume_last_save(bool on) { + AppSettings::get().modify([on](Settings &s) { s.resume_last_save = on; }); + if (resume_label_) { + lv_label_set_text(resume_label_, on ? "On" : "Off"); + } } VideoSetting Gui::get_video_setting() { @@ -42,6 +53,7 @@ void Gui::clear_rom_list() { // empty the options from the rom roller lv_roller_set_options(ui_roms, "", LV_ROLLER_MODE_INFINITE); rom_infos_.clear(); + roller_rows_.clear(); focused_rom_ = -1; } @@ -67,37 +79,95 @@ void Gui::update_rom_list() { // protect since this function is called from another thread context std::lock_guard lk(mutex_); - // // clear the rom list + // keep the selected game selected (its index may change); at boot that is + // the last game played + std::string selected_path = AppSettings::get().get_settings().last_rom; + if (focused_rom_ >= 0 && focused_rom_ < (int)rom_infos_.size()) { + selected_path = rom_infos_[focused_rom_].rom_path; + } clear_rom_list(); - // get the roms from the metadata auto roms = parse_metadata(metadata_filename_); - // iterate through the list and get the rom and index for each - for (const auto& rom : roms) { - add_rom(rom); + // drop duplicates (the same line twice in metadata.csv) + for (const auto &rom : roms) { + if (std::find(rom_infos_.begin(), rom_infos_.end(), rom) == rom_infos_.end()) { + rom_infos_.push_back(rom); + } + } + // grouped by console, in Console order; metadata.csv order within a console + std::stable_sort(rom_infos_.begin(), rom_infos_.end(), [](const RomInfo &a, const RomInfo &b) { + return console_of(a.platform) < console_of(b.platform); + }); + if (rom_infos_.empty()) { + return; + } + // the roller: a header row before each console's games + std::string options; + int selected_row = -1; + for (size_t i = 0; i < rom_infos_.size(); i++) { + const Console console = console_of(rom_infos_[i].platform); + if (i == 0 || console != console_of(rom_infos_[i - 1].platform)) { + options += std::string(LV_SYMBOL_LIST " ") + console_info(console).name + "\n"; + roller_rows_.push_back(-1); + } + if (rom_infos_[i].rom_path == selected_path) { + selected_row = roller_rows_.size(); + } + options += rom_infos_[i].name + "\n"; + roller_rows_.push_back(i); } + if (!options.empty()) options.pop_back(); // (the last '\n') + lv_roller_set_options(ui_roms, options.c_str(), LV_ROLLER_MODE_INFINITE); + if (selected_row < 0) { + selected_row = 1; // the first game, under the first header + } + roller_row_ = selected_row; + lv_roller_set_selected(ui_roms, selected_row, LV_ANIM_OFF); + on_rom_focused(roller_rows_[selected_row]); } -void Gui::add_rom(const RomInfo& rom_info) { - // protect since this function is called from another thread context +bool Gui::select_rom_matching(std::string_view text) { std::lock_guard lk(mutex_); - // ensure we don't already have this rom - if (std::find(rom_infos_.begin(), rom_infos_.end(), rom_info) != rom_infos_.end()) { + // an exact path or name first (one ROM's path can contain another's), then + // the first game containing the text + for (const bool exact : {true, false}) { + for (size_t row = 0; row < roller_rows_.size(); row++) { + const int i = roller_rows_[row]; + if (i < 0) continue; + const auto &rom = rom_infos_[i]; + if (exact ? (rom.rom_path == text || rom.name == text) + : (rom.name.find(text) != std::string::npos || rom.rom_path.find(text) != std::string::npos)) { + roller_row_ = row; + lv_roller_set_selected(ui_roms, row, LV_ANIM_OFF); + on_rom_focused(i); + return true; + } + } + } + return false; +} + +void Gui::on_roller_row(int row) { + std::lock_guard lk(mutex_); + if (row < 0 || row >= (int)roller_rows_.size()) { return; } - // add it to our vector - rom_infos_.push_back(rom_info); - // build the list of roms from the rom_infos - std::string rom_list; - for (const auto& rom : rom_infos_) { - rom_list += rom.name + "\n"; - } - // remove the last newline - rom_list.pop_back(); - // update the rom roller with the new rom list - lv_roller_set_options(ui_roms, rom_list.c_str(), LV_ROLLER_MODE_INFINITE); - if (focused_rom_ == -1) { - // if we don't have a focused rom, then focus this newly added rom! - on_rom_focused(rom_infos_.size() - 1); + if (roller_rows_[row] < 0) { + // a console header: move on to the next game in the direction of travel + // (the roller wraps around, so going up from the first game lands on the + // last one) + const int n = roller_rows_.size(); + // (the shorter way round from where it was; ties go down) + const bool up = (roller_row_ - row + n) % n < (row - roller_row_ + n) % n; + int next = row; + do { + next = (next + (up ? n - 1 : 1)) % n; + } while (roller_rows_[next] < 0 && next != row); + row = next; + lv_roller_set_selected(ui_roms, row, LV_ANIM_ON); + } + roller_row_ = row; + if (roller_rows_[row] != focused_rom_) { + on_rom_focused(roller_rows_[row]); } } @@ -107,12 +177,50 @@ void Gui::on_rom_focused(int index) { if (focused_rom_ < 0 || focused_rom_ >= rom_infos_.size()) { return; } + // the console first: its SD card art shares the JPEG decoder's buffer with + // the boxart, so it is copied out before the boxart is decoded + show_console(console_of(rom_infos_[focused_rom_].platform)); // update the boxart auto boxart_path = rom_infos_[focused_rom_].boxart_path.c_str(); focused_boxart_ = make_boxart(boxart_path); lv_img_set_src(ui_boxart, &focused_boxart_); } +// In the header, between the battery and the play button: the selected +// game's console, as its SD card art (boxart/consoles/.jpg, at most +// about 150x48) if there is one, else the firmware's badge. Only on this +// screen: in a game the screen is the game's. +void Gui::show_console(Console console) { + if (shown_console_ == static_cast(console) || !console_area_) { + return; + } + shown_console_ = static_cast(console); + lv_obj_clean(console_area_); + const auto &info = console_info(console); + if (const auto art = console_art_path(BoxEmu::mount_point, info); !art.empty()) { + decoder_.decode(art.c_str()); + const size_t size = decoder_.get_size(); + if (size > 0) { + if (console_art_data_) heap_caps_free(console_art_data_); + console_art_data_ = (uint8_t *)heap_caps_malloc(size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); + if (console_art_data_) { + memcpy(console_art_data_, decoder_.get_decoded_data(), size); + memset(&console_art_, 0, sizeof(console_art_)); + console_art_.header.cf = LV_COLOR_FORMAT_NATIVE; + console_art_.header.w = decoder_.get_width(); + console_art_.header.h = decoder_.get_height(); + console_art_.data_size = size; + console_art_.data = console_art_data_; + auto *img = lv_image_create(console_area_); + lv_image_set_src(img, &console_art_); + return; + } + } + } + console_badge_create(console_area_, {info.short_name, info.short_name, info.key, info.color, info.shape}, 36, + &lv_font_montserrat_14); +} + void Gui::update_haptic_waveform_label() { auto haptic_label = fmt::format("{}", haptic_waveform_); lv_label_set_text(ui_hapticlabel, haptic_label.c_str()); @@ -179,6 +287,42 @@ void Gui::init_ui() { // usb button lv_obj_add_event_cb(ui_usb_button, &Gui::event_callback, LV_EVENT_PRESSED, static_cast(this)); + // the console of the selected game replaces the title in the header + lv_obj_add_flag(ui_Screen1_Label1, LV_OBJ_FLAG_HIDDEN); + console_area_ = lv_obj_create(ui_header); + lv_obj_remove_style_all(console_area_); + lv_obj_remove_flag(console_area_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(console_area_, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_size(console_area_, 160, 48); + lv_obj_set_align(console_area_, LV_ALIGN_CENTER); + lv_obj_set_x(console_area_, 12); + lv_obj_set_flex_flow(console_area_, LV_FLEX_FLOW_ROW); + lv_obj_set_flex_align(console_area_, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + + // settings: resume the last save state (a row like the USB one, below it) + { + auto *panel = lv_obj_create(ui_settingspanel); + lv_obj_set_height(panel, 50); + lv_obj_set_width(panel, lv_pct(100)); + lv_obj_set_y(panel, 300); + lv_obj_set_align(panel, LV_ALIGN_TOP_MID); + lv_obj_remove_flag(panel, LV_OBJ_FLAG_SCROLLABLE); + auto *label = lv_label_create(panel); + lv_obj_set_align(label, LV_ALIGN_LEFT_MID); + lv_label_set_text(label, "Resume last save"); + resume_button_ = lv_button_create(panel); + lv_obj_set_height(resume_button_, 32); + lv_obj_set_width(resume_button_, LV_SIZE_CONTENT); + lv_obj_set_align(resume_button_, LV_ALIGN_RIGHT_MID); + lv_obj_add_flag(resume_button_, LV_OBJ_FLAG_SCROLL_ON_FOCUS); + lv_obj_remove_flag(resume_button_, LV_OBJ_FLAG_SCROLLABLE); + resume_label_ = lv_label_create(resume_button_); + lv_obj_set_align(resume_label_, LV_ALIGN_CENTER); + lv_label_set_text(resume_label_, AppSettings::get().get_settings().resume_last_save ? "On" : "Off"); + lv_obj_add_event_cb(resume_button_, &Gui::event_callback, LV_EVENT_PRESSED, static_cast(this)); + lv_obj_add_event_cb(resume_button_, &Gui::event_callback, LV_EVENT_KEY, static_cast(this)); + } + // now do the same events for all the same buttons but for the LV_EVENT_KEY lv_obj_add_event_cb(ui_settingsbutton, &Gui::event_callback, LV_EVENT_KEY, static_cast(this)); lv_obj_add_event_cb(ui_playbutton, &Gui::event_callback, LV_EVENT_KEY, static_cast(this)); @@ -209,6 +353,7 @@ void Gui::init_ui() { lv_group_add_obj(settings_screen_group_, ui_hapticupbutton); lv_group_add_obj(settings_screen_group_, ui_hapticplaybutton); lv_group_add_obj(settings_screen_group_, ui_usb_button); + lv_group_add_obj(settings_screen_group_, resume_button_); // set the focused style for all the buttons to have a red border lv_style_init(&button_style_); @@ -228,6 +373,7 @@ void Gui::init_ui() { lv_obj_add_style(ui_hapticplaybutton, &button_style_, LV_STATE_FOCUSED); lv_obj_add_style(ui_videosettingdropdown, &button_style_, LV_STATE_FOCUSED); lv_obj_add_style(ui_usb_button, &button_style_, LV_STATE_FOCUSED); + lv_obj_add_style(resume_button_, &button_style_, LV_STATE_FOCUSED); update_rom_list(); @@ -259,10 +405,7 @@ void Gui::on_value_changed(lv_event_t *e) { } bool is_roms = (target == ui_roms); if (is_roms) { - // get the focused rom - auto focused_rom_index = lv_roller_get_selected(ui_roms); - // focus the rom - on_rom_focused(focused_rom_index); + on_roller_row(lv_roller_get_selected(ui_roms)); return; } } @@ -328,8 +471,11 @@ void Gui::on_pressed(lv_event_t *e) { // or is it the play button? bool is_play_button = (target == ui_playbutton); if (is_play_button) { - ready_to_play_ = true; - freeze_focus(); + // (while the PC has the card the ROM is not there to load) + if (!BoxEmu::get().is_usb_enabled()) { + ready_to_play_ = true; + freeze_focus(); + } return; } bool is_close_button = (target == ui_closebutton); @@ -342,6 +488,10 @@ void Gui::on_pressed(lv_event_t *e) { toggle_usb(); return; } + if (resume_button_ && target == resume_button_) { + set_resume_last_save(!AppSettings::get().get_settings().resume_last_save); + return; + } } void Gui::on_volume(const std::vector& data) { @@ -386,6 +536,18 @@ void Gui::on_battery(const std::vector& data) { } } +void Gui::sync_usb_drive() { + const bool on = BoxEmu::get().is_usb_enabled(); + if (on == usb_drive_shown_) { + return; + } + usb_drive_shown_ = on; + lv_label_set_text(ui_usb_label, on ? "Enabled" : "Disabled"); + if (!on) { + reload_rom_list(); + } +} + void Gui::toggle_usb() { fmt::print("Toggling USB\n"); auto &emu = BoxEmu::get(); @@ -395,6 +557,10 @@ void Gui::toggle_usb() { } else { emu.initialize_usb(); } + // the card is ours again: pick up what the PC copied over + if (!emu.is_usb_enabled()) { + reload_rom_list(); + } // update the label if (emu.is_usb_enabled()) { lv_label_set_text(ui_usb_label, "Enabled"); @@ -444,10 +610,7 @@ void Gui::on_scroll(lv_event_t *e) { lv_obj_t * target = (lv_obj_t*)lv_event_get_target(e); bool is_roms = (target == ui_roms); if (is_roms) { - // get the focused rom - auto focused_rom_index = lv_roller_get_selected(ui_roms); - // focus the rom - on_rom_focused(focused_rom_index); + on_roller_row(lv_roller_get_selected(ui_roms)); } } @@ -481,8 +644,8 @@ void Gui::on_key(lv_event_t *e) { } } else if (key == LV_KEY_ENTER) { if (is_rom_screen) { - // play the focused rom - ready_to_play_ = true; + // play the focused rom (not while the PC has the card) + if (!BoxEmu::get().is_usb_enabled()) ready_to_play_ = true; } else if (is_settings_screen) { // handle some specific things we need to do for the dropdown -.- // They say that in v9 they will have a better way to do this... @@ -503,7 +666,7 @@ void Gui::on_key(lv_event_t *e) { lv_group_focus_next(settings_screen_group_); } } else if (is_rom_screen) { - on_rom_focused(lv_roller_get_selected(ui_roms)); + on_roller_row(lv_roller_get_selected(ui_roms)); } } else if (key == LV_KEY_LEFT || key == LV_KEY_UP) { if (is_settings_screen) { @@ -512,7 +675,7 @@ void Gui::on_key(lv_event_t *e) { lv_group_focus_prev(settings_screen_group_); } } else if (is_rom_screen) { - on_rom_focused(lv_roller_get_selected(ui_roms)); + on_roller_row(lv_roller_get_selected(ui_roms)); } } } diff --git a/components/jpeg/include/jpeg.hpp b/components/jpeg/include/jpeg.hpp index 1c781ba5..c0c75b34 100644 --- a/components/jpeg/include/jpeg.hpp +++ b/components/jpeg/include/jpeg.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include "esp_heap_caps.h" @@ -30,22 +31,44 @@ class Jpeg { } void decode(const char* filename) { + image_size_ = 0; + image_width_ = 0; + image_height_ = 0; + if (!encoded_data_ || !decoded_data_) { + return; + } // open the image int32_t encoded_length = 0; open(filename, &encoded_length); - read(encoded_data_, encoded_length); + if (encoded_length <= 0 || encoded_length > (int32_t)max_encoded_size) { + if (encoded_length > 0) + fmt::print("{}: {} bytes, more than the {} the decoder takes\n", filename, encoded_length, max_encoded_size); + close(); + return; + } + encoded_length = read(encoded_data_, encoded_length); close(); - decoder_.openRAM(encoded_data_, encoded_length, &Jpeg::on_data_decode); + if (!decoder_.openRAM(encoded_data_, encoded_length, &Jpeg::on_data_decode)) { + fmt::print("{}: not a JPEG the decoder can read\n", filename); + return; + } decoder_.setPixelType(RGB565_LITTLE_ENDIAN); - image_width_ = decoder_.getWidth(); - image_height_ = decoder_.getHeight(); - image_size_ = image_height_ * image_width_ * 2; + const int width = decoder_.getWidth(); + const int height = decoder_.getHeight(); + if ((size_t)width * height * 2 > max_decoded_size) { + fmt::print("{}: {}x{} is larger than the decoder's {} byte buffer\n", filename, width, height, max_decoded_size); + decoder_.close(); + return; + } + image_width_ = width; + image_height_ = height; // now actually decode it - if (!decoder_.decode(0, 0, 0)) { - image_size_ = 0; + if (decoder_.decode(0, 0, 0)) { + image_size_ = width * height * 2; + } else { image_width_ = 0; image_height_ = 0; - fmt::print("Couldn't decode!\n"); + fmt::print("{}: couldn't decode ({})\n", filename, decoder_.getLastError()); } decoder_.close(); } @@ -99,19 +122,20 @@ class Jpeg { } static int on_data_decode(JPEGDRAW *pDraw) { - auto width = pDraw->iWidth; - auto height = pDraw->iHeight; - auto xs = pDraw->x; - auto ys = pDraw->y; + // pPixels holds just this block: iWidth x iHeight, placed at (x, y) + const int width = pDraw->iWidth; + const int xs = pDraw->x; + const int ys = pDraw->y; + if (xs < 0 || ys < 0 || xs >= image_width_) { + return 1; + } + const int copy_width = std::min(width, image_width_ - xs); + const int height = std::min(pDraw->iHeight, image_height_ - ys); uint16_t *dst_buffer = reinterpret_cast(decoded_data_); const uint16_t *src_buffer = (const uint16_t*)pDraw->pPixels; - // two bytes per pixel for RGB565 - uint16_t num_bytes_per_row = width * 2; - for (uint16_t i = 0; i < height; i++) { - uint16_t y = ys + i; - uint16_t dst_offset = y * image_width_ + xs; - uint16_t src_offset = i * width + xs; - memcpy(&dst_buffer[dst_offset], &src_buffer[src_offset], num_bytes_per_row); + for (int i = 0; i < height; i++) { + memcpy(&dst_buffer[(size_t)(ys + i) * image_width_ + xs], &src_buffer[(size_t)i * width], + copy_width * 2); } // continue decode return 1; diff --git a/components/menu/include/menu.hpp b/components/menu/include/menu.hpp index cb5cc89b..9617d966 100644 --- a/components/menu/include/menu.hpp +++ b/components/menu/include/menu.hpp @@ -71,6 +71,11 @@ class Menu { update_slot_display(); } + /// Pick the slot without touching the (hidden) menu: no LVGL, and no + /// preview read into frame_buffer0, which the running core may draw in. + /// resume() shows it when the menu next opens. + void set_selected_slot(size_t slot) { selected_slot_ = std::clamp(slot, (size_t)0, MAX_SLOT); } + void next_slot() { selected_slot_++; // if we go too high, cycle around to 0 diff --git a/components/menu/src/menu.cpp b/components/menu/src/menu.cpp index 0d513b4b..58b08bc6 100644 --- a/components/menu/src/menu.cpp +++ b/components/menu/src/menu.cpp @@ -110,6 +110,11 @@ void Menu::init_ui() { void Menu::deinit_ui() { lv_scr_load(previous_screen_); lv_obj_del(ui_Screen1); + // menu_ui_init() also makes an (empty) screen each time + if (ui____menu_initial_actions0) { + lv_obj_del(ui____menu_initial_actions0); + ui____menu_initial_actions0 = nullptr; + } // delete the group lv_group_del(group_); // reset the style(s) diff --git a/components/msx/fmsx/src/fMSX/MSX.c b/components/msx/fmsx/src/fMSX/MSX.c index 800b733a..aef7594b 100644 --- a/components/msx/fmsx/src/fMSX/MSX.c +++ b/components/msx/fmsx/src/fMSX/MSX.c @@ -115,6 +115,7 @@ const char *SndName = "LOG.MID"; /* Sound log file */ /** Emulation state saving ***********************************/ const char *STAName = "DEFAULT.STA";/* State file (autogen-d)*/ +static char *STANameAlloc = 0; /* STAName, when MakeFileName() made it */ /** Fixed font used by fMSX **********************************/ const char *FNTName = "DEFAULT.FNT"; /* Font file for text */ @@ -354,7 +355,8 @@ static void* my_malloc(size_t size) static void my_free(void* p) { - pool_free(p); + /* Chunks also lists WorkDir, which getcwd() took from the libc heap */ + if(pool_contains(p)) pool_free(p); else free(p); } /** GetMemory() **********************************************/ @@ -676,6 +678,9 @@ void TrashMSX(void) /* Free all remaining allocated memory */ FreeAllMemory(); + free(STANameAlloc); + STANameAlloc = 0; + STAName = "DEFAULT.STA"; } /** ResetMSX() ***********************************************/ @@ -2984,11 +2989,12 @@ int FindState(const char *Name) /* No result yet */ J = 0; - /* Remove old state name */ - FreeMemory(STAName); + /* Remove old state name (MakeFileName() takes it from the libc heap, not + GetMemory(), so FreeMemory() would not free it) */ + free(STANameAlloc); /* If STAName gets created... */ - if((STAName=MakeFileName(Name,".sta"))) + if((STAName=STANameAlloc=MakeFileName(Name,".sta"))) { /* Try loading state */ if(Verbose) printf("Loading state from %s...",STAName); @@ -3001,7 +3007,7 @@ int FindState(const char *Name) { I=LoadCHT(P); if(I&&Verbose) printf("Loaded %d cheats from %s\n",I,P); - FreeMemory(P); + free(P); } /* Generate .MCF cheat file name and try loading it */ @@ -3009,7 +3015,7 @@ int FindState(const char *Name) { I=LoadMCF(P); if(I&&Verbose) printf("Loaded %d cheat entries from %s\n",I,P); - FreeMemory(P); + free(P); } /* Generate palette file name and try loading it */ @@ -3017,7 +3023,7 @@ int FindState(const char *Name) { I=LoadPAL(P); if(I&&Verbose) printf("Loaded palette from %s\n",P); - FreeMemory(P); + free(P); } /* Done */ diff --git a/components/nes/include/nes.hpp b/components/nes/include/nes.hpp index 952739a9..2f1e5149 100644 --- a/components/nes/include/nes.hpp +++ b/components/nes/include/nes.hpp @@ -7,7 +7,7 @@ void reset_nes(); void init_nes(const std::string& rom_filename, uint8_t *romdata, size_t rom_data_size); -void load_nes(std::string_view save_path); +bool load_nes(std::string_view save_path); void save_nes(std::string_view save_path); void run_nes_rom(); void deinit_nes(); diff --git a/components/nes/nofrendo/bitmap.c b/components/nes/nofrendo/bitmap.c index c6748706..eb8ef741 100644 --- a/components/nes/nofrendo/bitmap.c +++ b/components/nes/nofrendo/bitmap.c @@ -79,7 +79,9 @@ static bitmap_t *_make_bitmap(uint8 *data_addr, bool hw, int width, /* Allocate and initialize a bitmap structure */ #define FRAME_BUFFER_LENGTH ((256 + (2 * 8)) * 240) -static uint8 *frameBuffer = NULL; +/* esp-box-emu: the PPU draws into the unused upper part of the emulator's + * frame buffer (see video_audio.cpp) instead of a 65 KB buffer of its own */ +extern uint8 *osd_render_buffer(size_t length); bitmap_t *bmp_create(int width, int height, int overdraw) { printf("bmp_create: width=%d, height=%d, overdraw=%d\n", width, height, overdraw); @@ -88,10 +90,7 @@ bitmap_t *bmp_create(int width, int height, int overdraw) int pitch; pitch = width + (overdraw * 2); /* left and right */ - if (frameBuffer == NULL) { - frameBuffer = (uint8*)heap_caps_malloc(FRAME_BUFFER_LENGTH, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); - } - addr = frameBuffer; + addr = osd_render_buffer(FRAME_BUFFER_LENGTH); return _make_bitmap(addr, false, width, height, width, overdraw); } diff --git a/components/nes/src/nes.cpp b/components/nes/src/nes.cpp index 64dc2223..3a661435 100644 --- a/components/nes/src/nes.cpp +++ b/components/nes/src/nes.cpp @@ -5,6 +5,7 @@ static nes_t* console_nes; +#include #include #include "box-emu.hpp" @@ -76,9 +77,14 @@ void run_nes_rom() { } } -void load_nes(std::string_view save_path) { +bool load_nes(std::string_view save_path) { + // (the state is loaded at the next frame: check now that there is one) + FILE *f = fopen(std::string(save_path).c_str(), "rb"); + if (!f) return false; + fclose(f); save_path_to_load = save_path; load_save = true; + return true; } void save_nes(std::string_view save_path) { @@ -102,8 +108,12 @@ std::span get_nes_video_buffer() { return frame; } +extern "C" void osd_shutdown(); + void deinit_nes() { nes_poweroff(); + // free the audio frame (osd_init() makes a new one each launch) + osd_shutdown(); BoxEmu::get().audio_sample_rate(48000); nes_free_shared_memory(); } diff --git a/components/nes/src/video_audio.cpp b/components/nes/src/video_audio.cpp index 88cc7df6..c07e84b8 100644 --- a/components/nes/src/video_audio.cpp +++ b/components/nes/src/video_audio.cpp @@ -59,6 +59,9 @@ extern "C" void osd_setsound(void (*playfunc)(void *buffer, int length)) static void osd_stopsound(void) { free(audio_frame); + // osd_init_sound() allocates only when this is null: without it the next + // NES launch would play into the freed buffer + audio_frame = nullptr; audio_callback = NULL; } @@ -181,6 +184,18 @@ static void free_write(int num_dirties, rect_t *dirty_rects) bmp_destroy(&myBitmap); } +// Where nofrendo's PPU draws (bmp_create()): frame_buffer0 holds the 8 bit +// frame pushed to the display at its start (256 x 224 = 56 KB), so the PPU's +// 272 x 240 buffer goes 64 KB in, clear of it (frame_buffer0 is 320 x 240 x 2) +extern "C" uint8_t *osd_render_buffer(size_t length) { + constexpr size_t offset = 64 * 1024; + static_assert(offset >= 256 * NES_VISIBLE_HEIGHT, "the render buffer overlaps the pushed frame"); + if (offset + length > 320 * 240 * 2) { + return nullptr; + } + return BoxEmu::get().frame_buffer0() + offset; +} + static void custom_blit(const bitmap_t *bmp, int num_dirties, rect_t *dirty_rects) { uint8_t *lcdfb = BoxEmu::get().frame_buffer0(); if (bmp->line[0] != NULL) diff --git a/components/pico8/CMakeLists.txt b/components/pico8/CMakeLists.txt index ed84e30c..e0976cce 100644 --- a/components/pico8/CMakeLists.txt +++ b/components/pico8/CMakeLists.txt @@ -16,6 +16,9 @@ idf_component_register( # Where carts keep their cartdata() saves (femto8 defaults to a relative "cdata") target_compile_definitions(${COMPONENT_LIB} PRIVATE FEMTO8_ESPBOX=1 + # the cart file buffers (256 KB) only while a cart is parsed: the box's PSRAM + # is short, and its Lua heap needs them more + FEMTO8_FREE_LOAD_BUFFERS=1 # PICO8_PROFILE=1: report Lua instructions/s, GC share and the cycle count of # every API function with the fps line (see src/pico8.cpp) # PICO8_PROFILE=1 diff --git a/components/pico8/femto8 b/components/pico8/femto8 index 3c5fc452..b5e40e4e 160000 --- a/components/pico8/femto8 +++ b/components/pico8/femto8 @@ -1 +1 @@ -Subproject commit 3c5fc452ee542a99de80b3962927a665f886cc69 +Subproject commit b5e40e4e8fe25c85d6a91419cbd8917a142c0976 diff --git a/components/rom_info/include/rom_info.hpp b/components/rom_info/include/rom_info.hpp index 28b8c6e2..9b18a40b 100644 --- a/components/rom_info/include/rom_info.hpp +++ b/components/rom_info/include/rom_info.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -28,6 +29,27 @@ struct RomInfo { std::vector parse_metadata(const std::string& metadata_path); +/// The console a game is played as, in the order the game list shows them +/// (several emulators can share one, e.g. Genesis / Mega Drive; the PC ports +/// count as PC). +enum class Console : uint8_t { NES, SNES, GAME_BOY, GAME_BOY_COLOR, MASTER_SYSTEM, GAME_GEAR, GENESIS, MSX, PC, PICO8, UNKNOWN }; + +/// The shape the firmware draws for a console that has no art on the SD card. +enum class ConsoleShape : uint8_t { GAMEPAD, HANDHELD_TALL, HANDHELD_WIDE, DISC, COMPUTER, FANTASY }; + +struct ConsoleInfo { + const char *name; ///< shown in the list header + const char *short_name; ///< shown in the badge + const char *key; ///< art on the SD card: boxart/consoles/.jpg + uint32_t color; ///< badge accent (0xRRGGBB) + ConsoleShape shape; +}; + +/// The console `platform` games are grouped under. +Console console_of(Emulator platform); +/// Name, art key and colors of `console`. +const ConsoleInfo &console_info(Console console); + // for easy printing of Emulator using libfmt template <> struct fmt::formatter { diff --git a/components/rom_info/src/rom_info.cpp b/components/rom_info/src/rom_info.cpp index 54444260..462b9911 100644 --- a/components/rom_info/src/rom_info.cpp +++ b/components/rom_info/src/rom_info.cpp @@ -15,32 +15,16 @@ std::vector parse_metadata(const std::string& metadata_path) { while (std::getline(metadata, line)) { // get the fields from each line std::string rom_path, boxart_path, name; - char *str = line.data(); - char *token = strtok(str, ","); - int num_tokens = 0; - while (token != NULL && num_tokens < 3) { - switch (num_tokens) { - case 0: - // rom path - rom_path = token; - rom_path = trim(rom_path); - break; - case 1: - // boxart path - boxart_path = token; - boxart_path = trim(boxart_path); - break; - case 2: - // name - name = token; - name = trim(name); - break; - default: - // DANGER WILL ROBINSON - break; - } - token = strtok(NULL, ","); - num_tokens++; + // (split at the first two commas only: the rest, commas and all, is the name) + const auto first = line.find(','); + if (first == std::string::npos) { + continue; + } + const auto second = line.find(',', first + 1); + rom_path = trim(line.substr(0, first)); + boxart_path = trim(line.substr(first + 1, second == std::string::npos ? std::string::npos : second - first - 1)); + if (second != std::string::npos) { + name = trim(line.substr(second + 1)); } Emulator platform = Emulator::UNKNOWN; if (endsWith(rom_path, ".nes")) { // nes @@ -105,3 +89,50 @@ std::vector parse_metadata(const std::string& metadata_path) { return infos; } + +Console console_of(Emulator platform) { + switch (platform) { + case Emulator::NES: + return Console::NES; + case Emulator::SNES: + return Console::SNES; + case Emulator::GAMEBOY: + return Console::GAME_BOY; + case Emulator::GAMEBOY_COLOR: + return Console::GAME_BOY_COLOR; + case Emulator::SEGA_MASTER_SYSTEM: + return Console::MASTER_SYSTEM; + case Emulator::SEGA_GAME_GEAR: + return Console::GAME_GEAR; + case Emulator::SEGA_GENESIS: + case Emulator::SEGA_MEGA_DRIVE: + return Console::GENESIS; + case Emulator::MSX: + return Console::MSX; + case Emulator::DOOM: + case Emulator::DARK_FORCES: + return Console::PC; + case Emulator::PICO8: + return Console::PICO8; + default: + return Console::UNKNOWN; + } +} + +const ConsoleInfo &console_info(Console console) { + static const ConsoleInfo infos[] = { + {"NES", "NES", "nes", 0xB22222, ConsoleShape::GAMEPAD}, + {"Super Nintendo", "SNES", "snes", 0x6A5ACD, ConsoleShape::GAMEPAD}, + {"Game Boy", "Game Boy", "gb", 0x5B7F3A, ConsoleShape::HANDHELD_TALL}, + {"Game Boy Color", "GB Color", "gbc", 0x8E44AD, ConsoleShape::HANDHELD_TALL}, + {"Master System", "SMS", "sms", 0x1F5FAF, ConsoleShape::GAMEPAD}, + {"Game Gear", "Game Gear", "gg", 0x2F3B4C, ConsoleShape::HANDHELD_WIDE}, + {"Sega Genesis", "Genesis", "genesis", 0xC8102E, ConsoleShape::GAMEPAD}, + {"MSX", "MSX", "msx", 0x3A7D7D, ConsoleShape::COMPUTER}, + {"PC", "PC", "pc", 0x5A6B7B, ConsoleShape::COMPUTER}, + {"PICO-8", "PICO-8", "pico8", 0xFF004D, ConsoleShape::FANTASY}, + {"Other", "Other", "other", 0x606060, ConsoleShape::GAMEPAD}, + }; + const auto i = static_cast(console); + return infos[i < std::size(infos) ? i : std::size(infos) - 1]; +} diff --git a/components/settings/CMakeLists.txt b/components/settings/CMakeLists.txt new file mode 100644 index 00000000..fdde4946 --- /dev/null +++ b/components/settings/CMakeLists.txt @@ -0,0 +1,4 @@ +idf_component_register( + INCLUDE_DIRS "include" + SRC_DIRS "src" + REQUIRES format persistent_data) diff --git a/components/settings/idf_component.yml b/components/settings/idf_component.yml new file mode 100644 index 00000000..72398aba --- /dev/null +++ b/components/settings/idf_component.yml @@ -0,0 +1,5 @@ +## IDF Component Manager Manifest File +dependencies: + idf: '>=5.5' + # versioned settings file with forward migration + espp/persistent_data: '>=1.4.2' diff --git a/components/settings/include/settings.hpp b/components/settings/include/settings.hpp new file mode 100644 index 00000000..8f4bad37 --- /dev/null +++ b/components/settings/include/settings.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "persistent_data.hpp" + +/// The launcher settings that survive a power cycle, version 1. Kept in +/// settings.bin at the root of the SD card by espp::PersistentData: a new +/// field means a new version struct (with a migrate() from this one) in +/// front of the type list in AppSettings, never a change to this one. +struct SettingsV1 { + static constexpr uint32_t VERSION = 1; + uint8_t volume{60}; ///< 0..100 + bool muted{false}; + uint8_t brightness{80}; ///< 0..100 + uint8_t video_setting{1}; ///< VideoSetting (0 original, 1 fit, 2 fill) + bool resume_last_save{true}; ///< starting a game loads the slot it was last saved to / loaded from + std::string last_rom; ///< rom_path of the last game started (selected again at boot) + std::map last_slot; ///< rom_path -> the save slot last saved to / loaded from + uint8_t haptic_waveform{12}; ///< DRV2605 effect played when a game starts +}; + +/// The current settings version. +using Settings = SettingsV1; + +/// The settings file and an in-RAM copy of it. Changes are made in RAM +/// (modify()) and written when save() is called; the launcher calls save() +/// a moment after the last change, so dragging a slider is one write. +/// Thread-safe. +class AppSettings { +public: + static AppSettings &get() { + static AppSettings instance; + return instance; + } + + /// Load the file, or create it from `defaults` when there is none. A file + /// that cannot be read (corrupt, or written by newer firmware) is reported + /// and replaced by `defaults` in RAM; the file itself is only overwritten by + /// the next save(). + bool init(const std::string &file_path, const Settings &defaults); + + /// A copy of the current settings. + Settings get_settings() const; + + /// Change the settings in RAM (written by the next save()). + template void modify(Fn &&fn) { + std::lock_guard lk(mutex_); + Settings s = data_ ? data_->get() : fallback_; + const Settings before = s; + fn(s); + if (!same(before, s)) { + if (data_) + data_->set(s); + else + fallback_ = s; + dirty_ = true; + last_change_ = std::chrono::steady_clock::now(); + } + } + + /// Write the settings if they changed since the last save. + bool save(); + + /// save(), but only once `quiet` has passed since the last change (call it + /// periodically: a burst of changes is written once, after it ends). + bool save_if_idle(std::chrono::milliseconds quiet = std::chrono::milliseconds(1500)); + + /// The save slot last used for `rom_path`, if any. + std::optional last_slot(const std::string &rom_path) const; + /// Remember `slot` as the last one used for `rom_path`. + void set_last_slot(const std::string &rom_path, int slot); + +protected: + AppSettings() = default; + static bool same(const Settings &a, const Settings &b); + + using Store = espp::PersistentData; + mutable std::mutex mutex_; + std::unique_ptr data_; + Settings fallback_{}; ///< used when init() was not called (no SD card) + bool dirty_{false}; + std::chrono::steady_clock::time_point last_change_{}; +}; diff --git a/components/settings/src/settings.cpp b/components/settings/src/settings.cpp new file mode 100644 index 00000000..5f28274c --- /dev/null +++ b/components/settings/src/settings.cpp @@ -0,0 +1,68 @@ +#include "settings.hpp" + +#include + +#include "format.hpp" + +bool AppSettings::same(const Settings &a, const Settings &b) { + return std::tie(a.volume, a.muted, a.brightness, a.video_setting, a.resume_last_save, a.last_rom, a.last_slot, + a.haptic_waveform) == + std::tie(b.volume, b.muted, b.brightness, b.video_setting, b.resume_last_save, b.last_rom, b.last_slot, + b.haptic_waveform); +} + +bool AppSettings::init(const std::string &file_path, const Settings &defaults) { + std::lock_guard lk(mutex_); + data_ = std::make_unique(Store::Config{.file_path = file_path, .auto_load = false}); + std::error_code ec; + if (data_->load_or_create(defaults, ec)) { + dirty_ = false; + return true; + } + fmt::print("settings: cannot load {} ({}); using defaults\n", file_path, ec.message()); + data_->set(defaults); + dirty_ = false; + return false; +} + +Settings AppSettings::get_settings() const { + std::lock_guard lk(mutex_); + return data_ ? data_->get() : fallback_; +} + +bool AppSettings::save() { + std::lock_guard lk(mutex_); + if (!dirty_ || !data_) { + return true; + } + std::error_code ec; + if (!data_->save(ec)) { + fmt::print("settings: save failed: {}\n", ec.message()); + return false; + } + dirty_ = false; + return true; +} + +bool AppSettings::save_if_idle(std::chrono::milliseconds quiet) { + { + std::lock_guard lk(mutex_); + if (!dirty_ || std::chrono::steady_clock::now() - last_change_ < quiet) { + return true; + } + } + return save(); +} + +std::optional AppSettings::last_slot(const std::string &rom_path) const { + std::lock_guard lk(mutex_); + const Settings s = data_ ? data_->get() : fallback_; + if (auto it = s.last_slot.find(rom_path); it != s.last_slot.end()) { + return it->second; + } + return std::nullopt; +} + +void AppSettings::set_last_slot(const std::string &rom_path, int slot) { + modify([&](Settings &s) { s.last_slot[rom_path] = static_cast(slot); }); +} diff --git a/components/sms/include/sms.hpp b/components/sms/include/sms.hpp index 74ec40d3..7d3e4a62 100644 --- a/components/sms/include/sms.hpp +++ b/components/sms/include/sms.hpp @@ -10,8 +10,8 @@ void reset_sms(); void init_sms(uint8_t *romdata, size_t rom_data_size); void init_gg(uint8_t *romdata, size_t rom_data_size); -void load_sms(std::string_view save_path); -void save_sms(std::string_view save_path); +bool load_sms(std::string_view save_path); +bool save_sms(std::string_view save_path); void run_sms_rom(); void deinit_sms(); std::span get_sms_video_buffer(); diff --git a/components/sms/smsplus/sound/sound.c b/components/sms/smsplus/sound/sound.c index eaa415d0..7506dd0b 100644 --- a/components/sms/smsplus/sound/sound.c +++ b/components/sms/smsplus/sound/sound.c @@ -182,6 +182,10 @@ void sound_shutdown(void) } #endif + /* Free the sample buffer position table (sound_init() makes a new one) */ + free(smptab); + smptab = NULL; + /* Shut down SN76489 emulation */ SN76489_Shutdown(); diff --git a/components/sms/src/sms.cpp b/components/sms/src/sms.cpp index de497c45..03861391 100644 --- a/components/sms/src/sms.cpp +++ b/components/sms/src/sms.cpp @@ -6,6 +6,8 @@ extern "C" { #include +#include + #include "box-emu.hpp" #include "statistics.hpp" @@ -220,37 +222,47 @@ void run_sms_rom() { } } -void load_sms(std::string_view save_path) { - if (save_path.size()) { - auto f = fopen(save_path.data(), "rb"); - if (!f) return; - system_load_state(f); - fclose(f); - } +bool load_sms(std::string_view save_path) { + if (save_path.empty()) return false; + auto f = fopen(save_path.data(), "rb"); + if (!f) return false; + system_load_state(f); + fclose(f); + return true; } -void save_sms(std::string_view save_path) { +bool save_sms(std::string_view save_path) { // open the save path as a file descriptor auto f = fopen(save_path.data(), "wb"); - if (!f) return; + if (!f) return false; system_save_state(f); - fclose(f); + // (a write that fails shows up as the stream's error, or at the close) + const bool ok = !ferror(f); + return fclose(f) == 0 && ok; } +// the RGB565 copy get_sms_video_buffer() returns (PSRAM, made on first use) +static uint8_t *rgb_frame = nullptr; + std::span get_sms_video_buffer() { int height = is_gg ? GG_VISIBLE_HEIGHT : SMS_VISIBLE_HEIGHT; int width = is_gg ? GG_SCREEN_WIDTH : SMS_SCREEN_WIDTH; int pitch = SMS_SCREEN_WIDTH; - uint8_t *span_ptr = !frame_buffer_index - ? (uint8_t*)BoxEmu::get().frame_buffer1() - : (uint8_t*)BoxEmu::get().frame_buffer0(); - - std::span frame(span_ptr, width * height * 2); + // Converted into a buffer of its own: both frame buffers belong to the + // video task (the last pushed frame may still be queued or being drawn as + // palette indices), and the screen must not see RGB565 in them. + if (!rgb_frame) { + rgb_frame = (uint8_t *)heap_caps_malloc(SMS_SCREEN_WIDTH * SMS_VISIBLE_HEIGHT * 2, MALLOC_CAP_SPIRAM); + if (!rgb_frame) return {}; + } + std::span frame(rgb_frame, width * height * 2); - // the frame data for the SMS is stored in bitmap.data as a 8 bit index into - // the palette we need to convert this to a 16 bit RGB565 value - const uint8_t *frame_buffer = bitmap.data + frame_buffer_offset; + // the last frame drawn is the one pushed (bitmap.data has moved on to the + // other buffer): 8 bit indices into the palette, converted to RGB565 + const uint8_t *frame_buffer = (!frame_buffer_index + ? (uint8_t*)BoxEmu::get().frame_buffer1() + : (uint8_t*)BoxEmu::get().frame_buffer0()) + frame_buffer_offset; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint8_t index = frame_buffer[y * pitch + x]; @@ -263,5 +275,11 @@ std::span get_sms_video_buffer() { } void deinit_sms() { + // the sound streams and output buffers are malloc'ed (sound_init()), and + // their pointers live in the shared memory cleared below: free them first, + // or every SMS / Game Gear launch leaks ~10 KB of PSRAM + sound_shutdown(); + heap_caps_free(rgb_frame); + rgb_frame = nullptr; shared_mem_clear(); } diff --git a/main/cart.hpp b/main/cart.hpp index 810aa1c3..5bbf9a30 100644 --- a/main/cart.hpp +++ b/main/cart.hpp @@ -18,6 +18,7 @@ #include "box-emu.hpp" #include "rom_info.hpp" #include "menu.hpp" +#include "settings.hpp" /// This class is the base class for all carts. /// It provides the following functionality: @@ -91,6 +92,7 @@ class Cart { virtual void load() { logger_.info("Base loading..."); + state_done_ = true; // (an override that fails does not get here) // move the screenshot to the pause image auto screenshot_path = get_screenshot_path(true); auto paused_image_path = get_paused_image_path(); @@ -109,6 +111,7 @@ class Cart { virtual void save() { logger_.info("Base saving..."); + state_done_ = true; // move the pause image to the screenshot auto paused_image_path = get_paused_image_path(); auto screenshot_path = get_screenshot_path(true); @@ -169,11 +172,95 @@ class Cart { return running_; } + /// Start from the save state in `slot` (the one this game was last saved + /// to / loaded from), if the cart supports that and the slot holds a + /// state. The load is done the way the pause menu does it, on the first + /// frame for which resume_after_frames() has passed. + void resume_from_slot(int slot) { + if (!supports_resume()) { + return; + } + menu_->set_selected_slot(slot); + if (get_save_path().empty()) { + logger_.info("resume: no state in slot {}", slot); + return; + } + resume_pending_ = true; + } + + /// Save the state to `slot` (with its screenshot) the way the pause menu's + /// Save does, without showing the menu; for the USB link's test control. + /// Call from the task that runs the cart (between run() calls). + bool save_from_host(int slot) { + menu_->set_selected_slot(slot); + pre_menu(); + screenshot(get_paused_image_path()); + state_done_ = false; + save(); + if (state_done_) + remember_slot(); + if (running_) + post_menu(); + return state_done_; + } + + /// Load the state in `slot` the way the pause menu's Load does; false if + /// the slot is empty. Same rules as save_from_host(). + bool load_from_host(int slot) { + menu_->set_selected_slot(slot); + if (get_save_path().empty()) { + return false; + } + pre_menu(); + state_done_ = false; + load(); + if (state_done_) + remember_slot(); + if (running_) + post_menu(); + return state_done_; + } + + const RomInfo &rom_info() const { return info_; } + /// Frames the game has drawn so far (for the USB link's status: frame-rate + /// tests); 0 where the cart does not count them. + virtual uint32_t game_frames() const { return 0; } + + /// The frame a screenshot captures: its size and its RGB565 pixels (for + /// the USB link's screenshot, which copies it without going through a file) + std::pair frame_size() const { return get_video_size(); } + std::span frame_pixels() const { return get_video_buffer(); } + /// Hold the game still (true) while the USB link reads a screenshot + /// straight from its frame buffer, and let it go on (false). The main loop + /// is held meanwhile, which is enough for a core that runs in run(); a core + /// with its own tasks pauses them, as for the pause menu. + virtual void capture_hold(bool hold) {} + + /// The game reads other files from its ROM's folder while it runs (a PC + /// port's data files): the USB link then leaves that folder alone + virtual bool uses_rom_folder() const { return false; } + + /// Quit the game at the next run() call, as the pause menu's Quit does + /// (for the USB link's test control; any task). + void request_quit() { quit_requested_ = true; } + virtual bool run() { + if (quit_requested_) { + pre_menu(); + running_ = false; + return false; + } running_ = true; #if CONFIG_ESP_TASK_WDT_EN esp_task_wdt_reset(); // diagnostic: main task alive once per frame #endif + if (resume_pending_ && ++frames_run_ > resume_after_frames()) { + resume_pending_ = false; + logger_.info("resume: loading slot {}", get_selected_save_slot()); + pre_menu(); + load(); + post_menu(); + } // handle touchpad so we can know if the user presses the menu auto touch = BoxEmu::Bsp::get().touchpad_data(); bool btn_state = touch.btn_state; @@ -233,16 +320,33 @@ class Cart { menu_->pause(); break; case Menu::Action::SAVE: - save(); - break; case Menu::Action::LOAD: - load(); + // (the slot becomes the resume slot only if the core took it) + state_done_ = false; + action == Menu::Action::SAVE ? save() : load(); + if (state_done_) + remember_slot(); break; default: break; } } + /// Whether resume_from_slot() may load a state right after the game + /// started. The emulator cores say yes; the native ports keep their own + /// saves and are started fresh. + virtual bool supports_resume() const { return false; } + /// Frames to run before the resume load (a core that needs its game to + /// get going first, e.g. a PICO-8 cart's _init, says how long). + virtual int resume_after_frames() const { return 0; } + + /// The slot just saved to / loaded from becomes the one resume uses. + void remember_slot() const { + auto &settings = AppSettings::get(); + settings.set_last_slot(get_rom_filename(), get_selected_save_slot()); + settings.save(); + } + virtual std::string get_save_extension() const { return ".sav"; } @@ -329,7 +433,12 @@ class Cart { return ""; } + // set by the base save() / load(), which a failing override does not call + bool state_done_{false}; std::atomic running_{false}; + bool resume_pending_{false}; + std::atomic quit_requested_{false}; + int frames_run_{0}; size_t rom_size_bytes_{0}; uint8_t* romdata_{nullptr}; RomInfo info_; diff --git a/main/darkforces_cart.hpp b/main/darkforces_cart.hpp index 818c7e5e..de474658 100644 --- a/main/darkforces_cart.hpp +++ b/main/darkforces_cart.hpp @@ -71,6 +71,19 @@ class DarkForcesCart : public Cart { static constexpr size_t DF_WIDTH = 320; static constexpr size_t DF_HEIGHT = 200; + // (the GOBs and LFDs are read as the game goes) + bool uses_rom_folder() const override { return true; } + + void capture_hold(bool hold) override { +#if defined(ENABLE_DARKFORCES) + if (hold) { + pause_darkforces_tasks(); + } else { + resume_darkforces_tasks(); + } +#endif + } + // cppcheck-suppress uselessOverride virtual void pre_menu() override { Cart::pre_menu(); diff --git a/main/doom_cart.hpp b/main/doom_cart.hpp index 71ef824c..2983beba 100644 --- a/main/doom_cart.hpp +++ b/main/doom_cart.hpp @@ -66,6 +66,19 @@ class DoomCart : public Cart { static constexpr size_t DOOM_WIDTH = 320; static constexpr size_t DOOM_HEIGHT = 240; + // (the WAD is read as the game goes) + bool uses_rom_folder() const override { return true; } + + void capture_hold(bool hold) override { +#if defined(ENABLE_DOOM) + if (hold) { + pause_doom_tasks(); + } else { + resume_doom_tasks(); + } +#endif + } + // cppcheck-suppress uselessOverride virtual void pre_menu() override { Cart::pre_menu(); diff --git a/main/gbc_cart.hpp b/main/gbc_cart.hpp index 1739bfc3..7dddf7f0 100644 --- a/main/gbc_cart.hpp +++ b/main/gbc_cart.hpp @@ -7,6 +7,8 @@ class GbcCart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } explicit GbcCart(const Cart::Config& config) : Cart(config) { diff --git a/main/genesis_cart.hpp b/main/genesis_cart.hpp index 0dc8027e..6074ea67 100644 --- a/main/genesis_cart.hpp +++ b/main/genesis_cart.hpp @@ -7,6 +7,8 @@ class GenesisCart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } explicit GenesisCart(const Cart::Config& config) : Cart(config) { diff --git a/main/main.cpp b/main/main.cpp index 417970c6..766cc1b1 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -15,12 +15,23 @@ #include "box-emu.hpp" #include "carts.hpp" +#include "devlink.hpp" #include "gui.hpp" +#include "remote_control.hpp" +#include "settings.hpp" #include "memory_census.hpp" #include "rom_info.hpp" #include "statistics.hpp" #include "system_info.hpp" +#if CONFIG_HEAP_TRACING_STANDALONE +// Leak hunting (a local sdkconfig with CONFIG_HEAP_TRACING_STANDALONE=y): every +// allocation a cart's lifetime leaves behind, with its callers, is dumped after +// the quit census. The records live in PSRAM, allocated once at boot. +#include +static constexpr size_t kHeapTraceRecords = 1000; +#endif + using namespace std::chrono_literals; extern "C" void app_main(void) { @@ -52,6 +63,13 @@ extern "C" void app_main(void) { logger.warn("Failed to initialize SD card!"); logger.warn("This may happen if the SD card is not inserted."); } + // the composite USB device on the USB-C port: the console moves to its CDC + // port, the link services get its vendor interface, the uSD card its drive + // function (the card stays ours until handed over) + if (!emu.initialize_usb_device()) { + logger.warn("USB composite device not available (console stays on USB-Serial-JTAG)"); + } + if (!emu.initialize_memory()) { logger.error("Failed to initialize memory!"); @@ -78,6 +96,27 @@ extern "C" void app_main(void) { logger.warn("This may happen if the gamepad is not connected."); } + // the settings kept on the SD card (volume, brightness, video scaling, + // haptics, the last game and its save slots); the first boot writes the + // defaults + { + Settings defaults; + defaults.volume = static_cast(emu.volume()); + defaults.muted = emu.is_muted(); + defaults.brightness = static_cast(emu.brightness()); + defaults.video_setting = static_cast(emu.video_setting()); + auto &settings = AppSettings::get(); + settings.init(std::string(BoxEmu::mount_point) + "/settings.bin", defaults); + const Settings s = settings.get_settings(); + emu.volume(s.volume); + emu.mute(s.muted); + emu.brightness(std::max(10, s.brightness)); + emu.video_setting(static_cast(std::min(s.video_setting, 2))); + logger.info("settings: volume {}{}, brightness {}, video {}, resume {}, haptic {}, last game '{}'", s.volume, + s.muted ? " (muted)" : "", s.brightness, s.video_setting, s.resume_last_save, s.haptic_waveform, + s.last_rom); + } + logger.info("initializing gui..."); auto display = BoxEmu::Bsp::get().display(); @@ -89,8 +128,32 @@ extern "C" void app_main(void) { .log_level = espp::Logger::Verbosity::WARN }); + // the USB link's services (OTA, core dump, system, monitor) and the test + // control (see tools/emulink); its requests for the launcher / the game run + // here, on the main loop, through main_queue + MainQueue main_queue; + RemoteControl control(gui, main_queue); + DevLink devlink({.device_name = "ESP-Box-Emu", .firmware = esp_app_get_description()->version}); + devlink.register_module(control); + // up and running: an update that got this far is good (else the bootloader + // rolls back to the previous firmware on the next reset) + DevLink::mark_app_valid(); + + { + // (the GUI's LVGL task is already running: this sets a label) + std::lock_guard lk(BoxEmu::lvgl_mutex()); + gui.set_haptic_waveform(AppSettings::get().get_settings().haptic_waveform); + } + AppSettings::get().save(); // set_haptic_waveform() above marks it changed + print_mem_census("boot"); print_mem_blocks("boot", 2048); +#if CONFIG_HEAP_TRACING_STANDALONE + if (auto *records = static_cast( + heap_caps_calloc(kHeapTraceRecords, sizeof(heap_trace_record_t), MALLOC_CAP_SPIRAM))) { + heap_trace_init_standalone(records, kHeapTraceRecords); + } +#endif // set the task priority (for main) to high vTaskPrioritySet(nullptr, 20); @@ -101,6 +164,13 @@ extern "C" void app_main(void) { gui.ready_to_play(false); while (!gui.ready_to_play()) { std::this_thread::sleep_for(50ms); + // settings changed in the GUI are written once the changes stop (not + // while the PC has the card; the GUI hands it over under this lock) + { + std::lock_guard lk(BoxEmu::lvgl_mutex()); + if (!emu.usb_msc_host_has_card()) AppSettings::get().save_if_idle(); + } + main_queue.poll(); #if CONFIG_ESP_TASK_WDT_EN esp_task_wdt_reset(); #endif @@ -116,6 +186,8 @@ extern "C" void app_main(void) { if (maybe_selected_rom.has_value()) { auto selected_rom = maybe_selected_rom.value(); logger.info("Selected rom:\n\t{}", selected_rom); + AppSettings::get().modify([&](Settings &s) { s.last_rom = selected_rom.rom_path; }); + AppSettings::get().save(); // Memory census around the cart's lifetime: "menu" is the baseline, // "launch" shows what the core took (and where its big buffers landed, @@ -123,14 +195,26 @@ extern "C" void app_main(void) { // baseline so a leak or fragmentation across a play cycle shows up as a // non-zero delta. const MemSnapshot menu_mem = print_mem_census("menu"); +#if CONFIG_HEAP_TRACING_STANDALONE + heap_trace_start(HEAP_TRACE_LEAKS); +#endif // Cart handles platform specific code, state management, etc. { std::unique_ptr cart(make_cart(selected_rom, display)); if (cart) { + control.set_cart(cart.get()); + // start from the save state this game was last saved to / loaded from + if (AppSettings::get().get_settings().resume_last_save) { + if (const auto slot = AppSettings::get().last_slot(selected_rom.rom_path)) { + cart->resume_from_slot(*slot); + } + } print_mem_census("launch", &menu_mem); print_mem_blocks("launch", 4096); - while (cart->run()); + while (cart->run()) + main_queue.poll(); + control.set_cart(nullptr); } else { logger.error("Failed to create cart!"); } @@ -140,11 +224,41 @@ extern "C" void app_main(void) { // The census goes last so its `[mem] delta phase=quit` line marks the // end of a run for tools/serial_capture.py --until. print_mem_blocks("quit", SIZE_MAX); +#if CONFIG_HEAP_TRACING_STANDALONE + heap_trace_stop(); + { + // (heap_trace_dump() prints to the UART only) + size_t leaked = 0; + const size_t count = heap_trace_get_count(); + for (size_t i = 0; i < count; i++) { + heap_trace_record_t r; + if (heap_trace_get(i, &r) != ESP_OK || !r.address) continue; + leaked += r.size; + std::string callers; + for (auto *pc : r.alloced_by) { + if (pc) callers += fmt::format(" {}", pc); + } + fmt::print("[leak] {} B at {}{}:{}\n", r.size, r.address, + esp_ptr_external_ram(r.address) ? " (PSRAM)" : "", callers); + } + fmt::print("[leak] total {} B in {} blocks\n", leaked, count); + } +#endif print_mem_census("quit", &menu_mem); } else { logger.error("Invalid rom selected!"); } + // volume / brightness / video scaling may have changed in the pause menu + // or with the volume buttons + AppSettings::get().modify([&](Settings &s) { + s.volume = static_cast(emu.volume()); + s.muted = emu.is_muted(); + s.brightness = static_cast(emu.brightness()); + s.video_setting = static_cast(emu.video_setting()); + }); + AppSettings::get().save(); + // print the frame statistics from the previous run print_statistics(); diff --git a/main/msx_cart.hpp b/main/msx_cart.hpp index a7a3947a..b27db95f 100644 --- a/main/msx_cart.hpp +++ b/main/msx_cart.hpp @@ -7,6 +7,8 @@ class MsxCart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } explicit MsxCart(const Cart::Config& config) : Cart(config) { diff --git a/main/nes_cart.hpp b/main/nes_cart.hpp index 37926f55..d9785c18 100644 --- a/main/nes_cart.hpp +++ b/main/nes_cart.hpp @@ -7,6 +7,8 @@ class NesCart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } explicit NesCart(const Cart::Config& config) : Cart(config) { @@ -28,9 +30,11 @@ class NesCart : public Cart { // cppcheck-suppress uselessOverride virtual void load() override { - Cart::load(); #if defined(ENABLE_NES) - load_nes(get_save_path()); + // (only a state the core took counts as loaded) + if (load_nes(get_save_path())) Cart::load(); +#else + Cart::load(); #endif } diff --git a/main/pico8_cart.hpp b/main/pico8_cart.hpp index db7ba617..2650dd5c 100644 --- a/main/pico8_cart.hpp +++ b/main/pico8_cart.hpp @@ -8,6 +8,10 @@ // PICO-8 carts (.p8 / .p8.png) through femto8. class Pico8Cart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } + // the cart's _init has to have run before its Lua state can be replaced + virtual int resume_after_frames() const override { return 60; } explicit Pico8Cart(const Cart::Config& config) : Cart(config) { handle_video_setting(); @@ -70,6 +74,16 @@ class Pico8Cart : public Cart { static constexpr size_t P8_WIDTH = 128; static constexpr size_t P8_HEIGHT = 128; + void capture_hold(bool hold) override { +#if defined(ENABLE_PICO8) + if (hold) { + pause_pico8_tasks(); + } else { + resume_pico8_tasks(); + } +#endif + } + // cppcheck-suppress uselessOverride virtual void pre_menu() override { Cart::pre_menu(); diff --git a/main/remote_control.hpp b/main/remote_control.hpp new file mode 100644 index 00000000..00c3bf66 --- /dev/null +++ b/main/remote_control.hpp @@ -0,0 +1,816 @@ +#pragma once + +// Test control over the USB link (dispatcher module 0x20, protocol +// "emu.control"): what a test script needs to drive the emulator -- list and +// launch games, quit, hold buttons, save / load states, take screenshots, move +// files to and from the SD card (with the device running), hand the card to +// the PC as a USB drive and reboot into the updater. tools/emulink is the +// host side. +// +// Every request is answered with a reply frame of the same type whose +// payload is one status byte (0 = ok, 1 = error) and then the body: JSON text +// (an error's message as {"error": ...}), or the raw bytes for FILE_READ and +// SCREENSHOT_READ. +// Requests that touch the launcher or the running game are handed to the main +// loop (MainQueue) and answered once it ran them. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "bootloader_common.h" +#include "esp_flash_partitions.h" +#if CONFIG_IDF_TARGET_ESP32S3 +#include "soc/rtc_cntl_reg.h" +#endif + +#include "dispatcher.hpp" +#include "format.hpp" +#include "stream_frame.hpp" + +#include "cart.hpp" +#include "devlink.hpp" +#include "gui.hpp" +#include "settings.hpp" + +/// Work for the main loop (the task that owns the launcher and the running +/// cart), posted from other tasks; run() waits for it to be done. +class MainQueue { +public: + /// Run `fn` on the main loop and wait for it. If the main loop does not + /// get to it within `timeout` it is dropped (never run later) and run() + /// returns false; once started it is always waited for. + bool run(std::function fn, std::chrono::milliseconds timeout) { + auto item = std::make_shared(); + item->fn = std::move(fn); + std::unique_lock lk(mutex_); + queue_.push_back(item); + if (!cv_.wait_for(lk, timeout, [&] { return item->state != Item::QUEUED; })) { + item->state = Item::CANCELLED; + return false; + } + cv_.wait(lk, [&] { return item->state == Item::DONE; }); + return true; + } + /// Run `fn` on the main loop without waiting for it. + void post(std::function fn) { + auto item = std::make_shared(); + item->fn = std::move(fn); + std::lock_guard lk(mutex_); + queue_.push_back(item); + } + /// Called by the main loop: run what was posted. + void poll() { + std::unique_lock lk(mutex_); + while (!queue_.empty()) { + auto item = queue_.front(); + queue_.pop_front(); + if (item->state == Item::CANCELLED) continue; + item->state = Item::RUNNING; + cv_.notify_all(); + lk.unlock(); + item->fn(); + lk.lock(); + item->state = Item::DONE; + cv_.notify_all(); + } + } + +protected: + struct Item { + enum State { QUEUED, RUNNING, DONE, CANCELLED } state{QUEUED}; + std::function fn; + }; + std::mutex mutex_; + std::condition_variable cv_; + std::deque> queue_; +}; + +class RemoteControl { +public: + static constexpr uint8_t kModule = 0x20; + static constexpr const char *kProtocol = "emu.control"; + static constexpr uint16_t kProtocolVersion = 2; // 2: in-memory screenshots + + enum class Type : uint8_t { + STATUS = 0x01, ///< () -> {state, rom, platform, console, heap, uptime, ...} + LIST_ROMS = 0x02, ///< (offset: text) -> {total, roms: [{name, path, platform, console}]} + LAUNCH = 0x03, ///< (rom path or part of a name / path) -> {rom} + QUIT = 0x04, ///< () + BUTTONS = 0x05, ///< (u16 buttons, u16 hold ms; 0 = until the next BUTTONS) + SAVE = 0x06, ///< (u8 slot) + LOAD = 0x07, ///< (u8 slot) + /// (path: text, optional). With a path: saved there on the card as + /// [u16be w][u16be h][RGB565] -> {path}. Without: -> {width, height, size, + /// format: rgb565le}, and the game holds still (its frame buffer with it) + /// while SCREENSHOT_READ reads the pixels, until the last of them is read. + SCREENSHOT = 0x08, + USB_DRIVE = 0x09, ///< (u8 1 = the PC gets the SD card, 0 = the device takes it back) + RELOAD_ROMS = 0x0A, ///< () re-read metadata.csv + ENTER_UPDATER = 0x0B, ///< () reboot into the updater app (ota_1) for an update + SCREENSHOT_READ = 0x0C, ///< (u32 offset, u16 length) -> raw bytes of the held SCREENSHOT (short at the end) + FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?} + FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end) + FILE_WRITE = 0x12, ///< (u32 offset, path_len u16, path, data); offset 0 truncates + FILE_DELETE = 0x13, ///< (path: text) + MKDIR = 0x14, ///< (path: text) (with parents) + FILE_STAT = 0x15, ///< (path: text) -> {size, dir} + FILE_CLOSE = 0x16, ///< () flush and close the file being written + }; + + /// Where the main loop is, for STATUS. + enum class State { MENU, GAME }; + + RemoteControl(Gui &gui, MainQueue &main_queue) + : gui_(gui) + , main_(main_queue) { + // the launcher's drive switch can hand the card over between two FILE_WRITEs + BoxEmu::get().set_before_sd_handover([this] { close_file(); }); + } + ~RemoteControl() { BoxEmu::get().set_before_sd_handover(nullptr); } + + uint8_t module_id() const { return kModule; } + espp::DispatcherModuleInfo module_info() const { + return {.name = "Emulator control", + .app = "", + .description = "Launch games, input, save states, screenshots, SD card files", + .protocol = kProtocol, + .protocol_version = kProtocolVersion}; + } + + /// The main loop tells us what is running (nullptr: the launcher). + void set_cart(Cart *cart) { + std::lock_guard lk(state_mutex_); + cart_ = cart; + // what the game reads while it runs (see in_use_by_game()) + game_rom_ = cart ? normal_path(cart->rom_info().rom_path) : std::string(); + game_folder_ = cart && cart->uses_rom_folder() + ? normal_path(std::filesystem::path(cart->rom_info().rom_path).parent_path().string()) + : std::string(); + } + + void handle(const espp::stream_frame::Frame &frame) { + if (frame.is_reply() || frame.module != kModule) { + return; + } + std::vector body; + bool ok = true; + const std::string_view text(reinterpret_cast(frame.payload.data()), frame.payload.size()); + // the first error is the one reported + auto fail = [&](std::string_view message) { + if (!ok) return; + ok = false; + const auto j = fmt::format("{{\"error\":{}}}", quote(message)); + body.assign(j.begin(), j.end()); + }; + auto json = [&](const std::string &j) { + if (ok) body.assign(j.begin(), j.end()); + }; + // the main loop does not take work while it waits in the pause menu + auto on_main = [&](std::function fn, std::chrono::milliseconds timeout) { + if (main_.run(std::move(fn), timeout)) return true; + fail("the device is busy (is the pause menu open?)"); + return false; + }; + const auto &p = frame.payload; + // Held for the card's file requests: the card is handed over (by USB_DRIVE + // or the launcher's drive switch) under this lock, so it is not unmounted + // during one, and while the PC has it they are refused. + std::unique_lock card_lock(BoxEmu::lvgl_mutex(), std::defer_lock); + switch (static_cast(frame.type)) { + case Type::FILE_LIST: + case Type::FILE_READ: + case Type::FILE_WRITE: + case Type::FILE_DELETE: + case Type::MKDIR: + case Type::FILE_STAT: + case Type::FILE_CLOSE: + card_lock.lock(); + if (BoxEmu::get().usb_msc_host_has_card()) { + fail("the PC has the SD card (emulink drive off)"); + reply(frame, ok, body); + return; + } + break; + default: + break; + } + switch (static_cast(frame.type)) { + case Type::STATUS: + json(status()); + break; + case Type::LIST_ROMS: { + const auto roms = gui_.rom_infos(); + size_t offset = 0; + if (!text.empty()) offset = std::strtoul(std::string(text).c_str(), nullptr, 10); + std::string j = fmt::format("{{\"total\":{},\"offset\":{},\"roms\":[", roms.size(), offset); + size_t i = offset; + for (; i < roms.size(); i++) { + const auto &r = roms[i]; + auto e = fmt::format("{}{{\"name\":{},\"path\":{},\"platform\":\"{}\",\"console\":{}}}", + i > offset ? "," : "", quote(r.name), quote(r.rom_path), r.platform, + quote(console_info(console_of(r.platform)).name)); + // (room for the trailer, `],"next":N}`, and reply()'s status byte) + if (j.size() + e.size() + 24 > espp::stream_frame::kMaxPayloadSize) break; // the host asks for the rest + j += e; + } + j += fmt::format("],\"next\":{}}}", i); + json(j); + break; + } + case Type::LAUNCH: { + if (current_cart()) { + fail("a game is running; QUIT first"); + break; + } + const std::string match(text); + bool found = false, drive = false; + on_main([&] { + // (the PC has the card: the ROM is not there to load) + if ((drive = BoxEmu::get().usb_msc_host_has_card())) return; + found = select(match) && (gui_.ready_to_play(true), true); + }, std::chrono::seconds(2)); + if (drive) fail("the PC has the SD card (emulink drive off)"); + else if (!found) fail(fmt::format("no game matches '{}'", match)); + else json(fmt::format("{{\"rom\":{}}}", quote(gui_.get_selected_rom()->rom_path))); + break; + } + case Type::QUIT: { + bool quit = false; + on_main([&] { + if (auto *cart = current_cart()) { + cart->request_quit(); + quit = true; + } + }, std::chrono::seconds(5)); + if (!quit) fail("no game is running"); + break; + } + case Type::BUTTONS: { + if (p.size() < 4) { + fail("payload: u16 buttons, u16 hold_ms"); + break; + } + const uint16_t buttons = p[0] | (p[1] << 8); + const uint16_t hold_ms = p[2] | (p[3] << 8); + BoxEmu::get().set_remote_buttons(buttons); + if (hold_ms) { + // held for hold_ms, then released (this task answers afterwards) + std::this_thread::sleep_for(std::chrono::milliseconds(hold_ms)); + BoxEmu::get().set_remote_buttons(0); + } + break; + } + case Type::SAVE: + case Type::LOAD: { + if (p.empty()) { + fail("payload: u8 slot"); + break; + } + const int slot = p[0]; + // (the menu wraps an out-of-range slot round to 0) + if (slot > (int)Menu::MAX_SLOT) { + fail(fmt::format("slot {} out of range (0-{})", slot, Menu::MAX_SLOT)); + break; + } + const bool save = static_cast(frame.type) == Type::SAVE; + bool done = false, has_cart = false; + on_main([&] { + if (auto *cart = current_cart()) { + has_cart = true; + done = save ? cart->save_from_host(slot) : cart->load_from_host(slot); + } + }, std::chrono::seconds(30)); + if (!has_cart) fail("no game is running"); + else if (!done) fail(save ? fmt::format("saving to slot {} failed", slot) + : fmt::format("slot {} has no state, or the game could not load it", slot)); + break; + } + case Type::SCREENSHOT: { + std::string path(text); + if (!path.empty()) { + bool done = false, has_cart = false; + // the old way: a file on the card + on_main([&] { + if (auto *cart = current_cart()) { + has_cart = true; + std::error_code ec; + std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); + // (cores on their own tasks keep drawing: hold them, as below) + cart->capture_hold(true); + done = cart->screenshot(path); + cart->capture_hold(false); + } + }, std::chrono::seconds(10)); + if (!has_cart) fail("no game is running"); + else if (!done) fail("screenshot failed"); + else json(fmt::format("{{\"path\":{}}}", quote(path))); + break; + } + // The frame is read where the game drew it (for most cores one of the + // BSP's two frame buffers): the main loop takes the pointer between two + // frames and then holds, so the game draws nothing over it, until the + // last SCREENSHOT_READ (or a pause in the reading) lets it go on. + release_shot(); + size_t width = 0, height = 0; + { + std::unique_lock lk(shot_mutex_); + shot_state_ = ShotState::CAPTURING; + } + main_.post([this] { + std::unique_lock lk(shot_mutex_); + if (shot_state_ != ShotState::CAPTURING) return; // the request gave up + auto *cart = current_cart(); + if (cart) { + cart->capture_hold(true); + auto [w, h] = cart->frame_size(); + const auto pixels = cart->frame_pixels(); + // a core may report more lines than its frame buffer holds (the + // box's NES: 240 for a 224-line frame): keep what is there + if (w) h = std::min(h, pixels.size() / (w * 2)); + shot_width_ = w; + shot_height_ = h; + shot_pixels_ = pixels.data(); + shot_size_ = w * h * 2; + } + shot_state_ = (cart && shot_size_) ? ShotState::HELD : ShotState::IDLE; + has_shot_cart_ = cart != nullptr; + shot_cv_.notify_all(); + // hold the game while the frame is read + shot_deadline_ = std::chrono::steady_clock::now() + kShotIdle; + while (shot_state_ == ShotState::HELD && std::chrono::steady_clock::now() < shot_deadline_) { + shot_cv_.wait_until(lk, shot_deadline_); + } + shot_state_ = ShotState::IDLE; + shot_pixels_ = nullptr; + shot_cv_.notify_all(); + lk.unlock(); + if (cart) cart->capture_hold(false); + }); + std::unique_lock lk(shot_mutex_); + if (!shot_cv_.wait_for(lk, std::chrono::seconds(10), [&] { return shot_state_ != ShotState::CAPTURING; })) { + shot_state_ = ShotState::IDLE; // the posted job skips it + fail("the device is busy (is the pause menu open?)"); + break; + } + if (!has_shot_cart_) { + fail("no game is running"); + break; + } + if (shot_state_ != ShotState::HELD) { + fail("this game has no frame to capture"); + break; + } + width = shot_width_; + height = shot_height_; + json(fmt::format("{{\"width\":{},\"height\":{},\"size\":{},\"format\":\"{}\"}}", width, height, + shot_size_, kFrameFormat)); + break; + } + case Type::SCREENSHOT_READ: { + if (p.size() < 6) { + fail("payload: u32 offset, u16 length"); + break; + } + const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); + const size_t length = std::min(p[4] | (p[5] << 8), espp::stream_frame::kMaxPayloadSize - 1); + std::lock_guard lk(shot_mutex_); + if (shot_state_ != ShotState::HELD || !shot_pixels_) { + fail("no screenshot is being read (SCREENSHOT first)"); + break; + } + if (offset < shot_size_) { + const size_t n = std::min(length, shot_size_ - offset); + body.assign(shot_pixels_ + offset, shot_pixels_ + offset + n); + } + if (offset + length >= shot_size_) { + shot_state_ = ShotState::RELEASED; // all read: the game goes on + } else { + shot_deadline_ = std::chrono::steady_clock::now() + kShotIdle; + } + shot_cv_.notify_all(); + break; + } + case Type::USB_DRIVE: { + const bool host = !p.empty() && p[0]; + const bool closed = close_file(); + bool done = false; + on_main([&] { + if (current_cart() && host) return; // a running game uses the card + if (host) { + done = BoxEmu::get().initialize_usb_msc(); + } else { + BoxEmu::get().deinitialize_usb_msc(); + done = !BoxEmu::get().usb_msc_host_has_card(); + if (done) gui_.reload_rom_list(); + } + }, std::chrono::seconds(10)); + if (!closed) fail("the file being written could not be closed (card full?)"); + if (!done) fail(host ? "could not hand the SD card over (a game running?)" : "could not take the SD card back"); + break; + } + case Type::RELOAD_ROMS: + close_file(); + on_main([&] { gui_.reload_rom_list(); }, std::chrono::seconds(5)); + json(fmt::format("{{\"total\":{}}}", gui_.rom_infos().size())); + break; + case Type::ENTER_UPDATER: { +#if DEVLINK_HAS_OTA + fail("this device updates in place (the OTA service, module 0)"); + break; +#else + if (!boot_updater_next()) { + fail("no updater app (ota_1), or otadata could not be written"); + break; + } + close_file(); + // answer first, then restart + reply(frame, true, body); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + esp_restart(); + return; +#endif + } + case Type::FILE_LIST: { + // path, optionally followed by '\0' and the index to start at (the "next" of a truncated + // reply) + std::string_view path = text; + size_t offset = 0; + if (const auto nul = text.find('\0'); nul != std::string_view::npos) { + path = text.substr(0, nul); + offset = std::strtoul(std::string(text.substr(nul + 1)).c_str(), nullptr, 10); + } + std::error_code ec; + std::string j = "{\"entries\":["; + size_t i = 0; + for (const auto &e : std::filesystem::directory_iterator(std::string(path), ec)) { + if (i < offset) { + i++; + continue; + } + std::error_code ec2; + const bool dir = e.is_directory(ec2); + const uintmax_t size = dir ? 0 : e.file_size(ec2); + auto item = fmt::format("{}{{\"name\":{},\"dir\":{},\"size\":{}}}", i > offset ? "," : "", + quote(e.path().filename().string()), dir, size); + if (j.size() + item.size() + 48 > espp::stream_frame::kMaxPayloadSize) { + j += fmt::format("],\"truncated\":true,\"next\":{}}}", i); + json(j); + goto done; + } + j += item; + i++; + } + if (ec) { + fail(fmt::format("{}: {}", path, ec.message())); + break; + } + j += "]}"; + json(j); + done: + break; + } + case Type::FILE_READ: { + if (p.size() < 7) { + fail("payload: u32 offset, u16 length, path"); + break; + } + const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); + const size_t length = std::min(p[4] | (p[5] << 8), espp::stream_frame::kMaxPayloadSize - 1); + const std::string path(reinterpret_cast(p.data() + 6), p.size() - 6); + close_file(path); + FILE *f = fopen(path.c_str(), "rb"); + if (!f) { + fail(fmt::format("cannot open {}", path)); + break; + } + if (fseek(f, offset, SEEK_SET) != 0) { + fclose(f); + fail(fmt::format("cannot seek {} to {}", path, offset)); + break; + } + body.resize(length); + body.resize(fread(body.data(), 1, length, f)); + if (ferror(f)) fail(fmt::format("read error in {} at {}", path, offset)); + fclose(f); + break; + } + case Type::FILE_WRITE: { + if (p.size() < 6) { + fail("payload: u32 offset, u16 path_len, path, data"); + break; + } + const uint32_t offset = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24); + const size_t path_len = p[4] | (p[5] << 8); + if (p.size() < 6 + path_len) { + fail("path_len past the end"); + break; + } + const std::string path(reinterpret_cast(p.data() + 6), path_len); + const uint8_t *data = p.data() + 6 + path_len; + const size_t n = p.size() - 6 - path_len; + if (in_use_by_game(path)) { + fail(fmt::format("{} is in use by the running game (quit it first)", path)); + break; + } + if (!open_for_write(path, offset)) { + fail(fmt::format("cannot write {} at {}", path, offset)); + break; + } + if (fwrite(data, 1, n, write_file_) != n) { + close_file(); + fail(fmt::format("write to {} failed (card full?)", path)); + break; + } + write_pos_ = offset + n; + break; + } + case Type::FILE_CLOSE: + // (a buffered write that fails shows up here) + if (!close_file()) fail("closing the file failed (card full?)"); + break; + case Type::FILE_DELETE: { + const std::string path(text); + close_file(path); + struct stat st; + if (stat(path.c_str(), &st) != 0) { + fail(fmt::format("{} does not exist", path)); + } else if (in_use_by_game(path)) { + fail(fmt::format("{} is in use by the running game (quit it first)", path)); + } else if (S_ISDIR(st.st_mode)) { + std::error_code ec; + std::filesystem::remove_all(path, ec); + if (ec) fail(fmt::format("cannot delete {}: {}", path, ec.message())); + } else if (unlink(path.c_str()) != 0) { + fail(fmt::format("cannot delete {}: {}", path, strerror(errno))); + } + break; + } + case Type::MKDIR: { + std::error_code ec; + std::filesystem::create_directories(std::string(text), ec); + if (ec) fail(fmt::format("{}: {}", text, ec.message())); + break; + } + case Type::FILE_STAT: { + struct stat st; + if (stat(std::string(text).c_str(), &st) != 0) { + fail(fmt::format("{} does not exist", text)); + break; + } + json(fmt::format("{{\"size\":{},\"dir\":{}}}", (uintmax_t)st.st_size, S_ISDIR(st.st_mode))); + break; + } + default: + fail(fmt::format("unknown request type {:#x}", frame.type)); + break; + } + if (card_lock.owns_lock()) card_lock.unlock(); + reply(frame, ok, body); + } + +protected: + static std::string quote(std::string_view s) { + std::string out = "\""; + for (char c : s) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if ((unsigned char)c < 0x20) out += fmt::format("\\u{:04x}", (unsigned char)c); + else out += c; + } + } + return out + "\""; + } + + static void reply(const espp::stream_frame::Frame &request, bool ok, const std::vector &body) { + std::vector payload; + payload.reserve(body.size() + 1); + payload.push_back(ok ? 0 : 1); + payload.insert(payload.end(), body.begin(), body.end()); + const auto frame = espp::stream_frame::build_frame(true, kModule, request.type, payload, request.correlation); + DevLink::send(frame); + } + + Cart *current_cart() { + std::lock_guard lk(state_mutex_); + return cart_; + } + + /// A path as compared for in_use_by_game(): normalized, no trailing '/', + /// lower case (the card is FAT) + static std::string normal_path(const std::string &path) { + std::string s = std::filesystem::path(path).lexically_normal().string(); + while (s.size() > 1 && s.back() == '/') s.pop_back(); + std::transform(s.begin(), s.end(), s.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return s; + } + + /// Whether writing / deleting this path would change files the running + /// game reads while it runs: its ROM (which some cores page in as they go), + /// a folder holding it, or the data folder of a PC port (Doom's WADs, Dark + /// Forces' GOBs) + bool in_use_by_game(const std::string &path) { + const auto within = [](const std::string &p, const std::string &dir) { + return p == dir || (p.size() > dir.size() && p.compare(0, dir.size(), dir) == 0 && + (dir == "/" || p[dir.size()] == '/')); + }; + const std::string target = normal_path(path); + std::lock_guard lk(state_mutex_); + if (game_rom_.empty()) return false; + return within(game_rom_, target) || (!game_folder_.empty() && within(target, game_folder_)); + } + + bool select(const std::string &match) { + // an exact path first, then a part of a name / path + const auto roms = gui_.rom_infos(); + const std::string on_card = std::string(BoxEmu::mount_point) + "/" + match; + const auto exact = std::find_if(roms.begin(), roms.end(), [&](const auto &r) { + return r.rom_path == match || r.rom_path == on_card; + }); + return gui_.select_rom_matching(exact != roms.end() ? exact->rom_path : match); + } + + std::string status() { + std::string rom, platform, console; + bool in_game = false; + uint32_t frames = 0; + { + std::lock_guard lk(state_mutex_); + if (cart_) { + in_game = true; + const auto &info = cart_->rom_info(); + rom = info.rom_path; + platform = fmt::format("{}", info.platform); + console = console_info(console_of(info.platform)).name; + frames = cart_->game_frames(); + } + } + const auto *app = esp_app_get_description(); + const auto *running = esp_ota_get_running_partition(); + return fmt::format("{{\"state\":\"{}\",\"rom\":{},\"platform\":\"{}\",\"console\":{},\"game_frames\":{}," + "\"frames_presented\":{},\"frames_dropped\":{},\"usb_drive\":{}," + "\"uptime_ms\":{},\"internal_free\":{},\"internal_largest\":{},\"internal_min_free\":{}," + "\"psram_free\":{},\"psram_largest\":{},\"psram_min_free\":{},\"dma_free\":{}," + "\"dma_largest\":{},\"firmware\":{},\"built\":{}," + "\"partition\":{},\"elf_sha256\":{},\"reset_reason\":{},\"last_panic\":{}}}", + in_game ? "game" : "menu", quote(rom), platform, quote(console), frames, + BoxEmu::get().frames_blitted(), BoxEmu::get().frames_dropped(), + BoxEmu::get().usb_msc_host_has_card(), esp_timer_get_time() / 1000, + heap_caps_get_free_size(MALLOC_CAP_INTERNAL), + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), + heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL), + heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM), + heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM), + heap_caps_get_free_size(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL), + heap_caps_get_largest_free_block(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL), quote(app->version), + quote(fmt::format("{} {}", app->date, app->time)), quote(running ? running->label : ""), + quote(elf_sha256()), (int)esp_reset_reason(), quote(DevLink::last_panic())); + } + + /// Make the bootloader start the updater (ota_1) next. esp_ota_set_boot_partition() + /// first verifies the image through a flash mapping, which is unreliable in an + /// app that runs its code from PSRAM (esp-box-emu: the mapping can land on the + /// PSRAM heap's addresses), so the otadata entry is written here directly, with + /// plain SPI flash reads / writes: the same entry esp_ota_ops would write + /// (boot slot = (seq - 1) % slots). The updater, which has no PSRAM, verifies + /// and sets the boot partition the usual way. + static bool boot_updater_next() { + const esp_partition_t *updater = + esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, nullptr); + const esp_partition_t *otadata = + esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, nullptr); + if (!updater || !otadata) return false; + const uint32_t slots = esp_ota_get_app_partition_count(); + const uint32_t sector = otadata->erase_size; + esp_ota_select_entry_t e[2]; + for (int i = 0; i < 2; i++) { + if (esp_partition_read(otadata, i * sector, &e[i], sizeof(e[i])) != ESP_OK) return false; + } + const bool v0 = bootloader_common_ota_select_valid(&e[0]), v1 = bootloader_common_ota_select_valid(&e[1]); + const uint32_t seq = std::max(v0 ? e[0].ota_seq : 0, v1 ? e[1].ota_seq : 0); + uint32_t next = seq + 1; + while ((next - 1) % slots != 1) next++; // slot 1: the updater + // overwrite the older (or an invalid) entry, so the current one survives a failure + const int target = !v0 ? 0 : !v1 ? 1 : (e[0].ota_seq <= e[1].ota_seq ? 0 : 1); + esp_ota_select_entry_t entry; + memset(&entry, 0xFF, sizeof(entry)); + entry.ota_seq = next; + entry.ota_state = ESP_OTA_IMG_VALID; + entry.crc = bootloader_common_ota_select_crc(&entry); + esp_ota_select_entry_t check; + if (esp_partition_erase_range(otadata, target * sector, sector) == ESP_OK && + esp_partition_write(otadata, target * sector, &entry, sizeof(entry)) == ESP_OK && + esp_partition_read(otadata, target * sector, &check, sizeof(check)) == ESP_OK && + memcmp(&check, &entry, sizeof(entry)) == 0) { + return true; + } +#if CONFIG_IDF_TARGET_ESP32S3 + // esp-box-emu: with the flash and PSRAM at 120 MHz the app's flash writes + // do not land; the bootloader (bootloader_components/updater_switch) + // writes the entry when it finds this, at the next reset + REG_WRITE(RTC_CNTL_STORE0_REG, 0x55504454u); // "UPDT" + return true; +#else + return false; +#endif + } + + static std::string elf_sha256() { + char sha[17] = {}; + esp_app_get_elf_sha256(sha, sizeof(sha)); + return sha; + } + + // FILE_WRITE keeps the file open between chunks + bool open_for_write(const std::string &path, uint32_t offset) { + if (write_file_ && path == write_path_ && offset == write_pos_) { + return true; + } + if (!close_file()) return false; // (the previous file's last data did not land) + if (offset == 0) { + std::error_code ec; + std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); + write_file_ = fopen(path.c_str(), "wb"); + } else { + write_file_ = fopen(path.c_str(), "r+b"); + if (write_file_ && fseek(write_file_, offset, SEEK_SET) != 0) { + close_file(); + } + } + if (!write_file_) return false; + write_path_ = path; + write_pos_ = offset; + return true; + } + /// false: the file's buffered data could not be written + bool close_file(const std::string &only_if_path = "") { + // (the handover hook calls this from the task that hands the card over) + std::lock_guard lk(BoxEmu::lvgl_mutex()); + if (write_file_ && (only_if_path.empty() || only_if_path == write_path_)) { + const bool ok = fclose(write_file_) == 0; + write_file_ = nullptr; + write_path_.clear(); + return ok; + } + return true; + } + + // the pixels' byte order in the cores' frame buffers (both devices) + static constexpr const char *kFrameFormat = "rgb565le"; + // how long the game is held for a screenshot without a SCREENSHOT_READ + static constexpr std::chrono::milliseconds kShotIdle{2000}; + enum class ShotState { IDLE, CAPTURING, HELD, RELEASED }; + + /// Let the game go on if a screenshot is held (a new one replaces it). + void release_shot() { + std::unique_lock lk(shot_mutex_); + if (shot_state_ == ShotState::HELD) shot_state_ = ShotState::RELEASED; + shot_cv_.notify_all(); + shot_cv_.wait_for(lk, std::chrono::seconds(1), [&] { return shot_state_ == ShotState::IDLE; }); + } + + Gui &gui_; + MainQueue &main_; + std::mutex state_mutex_; + Cart *cart_{nullptr}; + std::string game_rom_; ///< the running game's ROM (normal_path()) + std::string game_folder_; ///< the folder it reads as it runs, if any + // the screenshot being read: the held game's frame buffer + std::mutex shot_mutex_; + std::condition_variable shot_cv_; + ShotState shot_state_{ShotState::IDLE}; + std::chrono::steady_clock::time_point shot_deadline_; + const uint8_t *shot_pixels_{nullptr}; + size_t shot_width_{0}, shot_height_{0}, shot_size_{0}; + bool has_shot_cart_{false}; + FILE *write_file_{nullptr}; + std::string write_path_; + uint32_t write_pos_{0}; +}; diff --git a/main/sms_cart.hpp b/main/sms_cart.hpp index 3b622018..2579f2df 100644 --- a/main/sms_cart.hpp +++ b/main/sms_cart.hpp @@ -7,6 +7,8 @@ class SmsCart : public Cart { public: + // an emulator core: a state loads right after the game starts + virtual bool supports_resume() const override { return true; } explicit SmsCart(const Cart::Config& config) : Cart(config) { @@ -29,17 +31,21 @@ class SmsCart : public Cart { // cppcheck-suppress uselessOverride virtual void load() override { - Cart::load(); #if defined(ENABLE_SMS) - load_sms(get_save_path()); + // (only a state the core took counts as loaded) + if (load_sms(get_save_path())) Cart::load(); +#else + Cart::load(); #endif } // cppcheck-suppress uselessOverride virtual void save() override { - Cart::save(); #if defined(ENABLE_SMS) - save_sms(get_save_path(true)); + // (only a state that reached the card counts as saved) + if (save_sms(get_save_path(true))) Cart::save(); +#else + Cart::save(); #endif } diff --git a/partitions.csv b/partitions.csv index b8a6dbe0..8dda7baa 100644 --- a/partitions.csv +++ b/partitions.csv @@ -1,4 +1,14 @@ -# Name, Type, SubType, Offset, Size -nvs, data, nvs, 0x9000, 0x6000 -phy_init, data, phy, 0xf000, 0x1000 -factory, app, factory, 0x10000, 6M +# Name, Type, SubType, Offset, Size +# ota_0: the emulator (where `idf.py flash` writes it). ota_1: the small +# updater app (updater/), which an update reboots into: it takes the new +# emulator image over USB, writes ota_0 and boots it. The emulator cannot +# write its own flash: it runs its code from PSRAM (SPIRAM_FETCH_INSTRUCTIONS), +# and a flash write then corrupts its PSRAM heap. With rollback on, an +# emulator image that resets before marking itself valid falls back to the +# updater. +nvs, data, nvs, 0x9000, 0x6000 +phy_init, data, phy, 0xf000, 0x1000 +otadata, data, ota, 0x10000, 0x2000 +ota_0, app, ota_0, 0x20000, 12M +ota_1, app, ota_1, , 2M +coredump, data, coredump, , 64K diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 9dab3c39..8ab3c7f6 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -79,6 +79,23 @@ CONFIG_FATFS_USE_FASTSEEK=y # USB config # CONFIG_TINYUSB_MSC_ENABLED=y +# eight sectors per SD transaction: with the 512 B default the PC reads the +# drive so slowly that macOS gives up mounting a 32 GB card (its FAT is 4 MB) +CONFIG_TINYUSB_MSC_BUFSIZE=4096 +# the composite USB device: the console on CDC, the link services on a +# vendor interface (frames up to 4 KiB + header each way); OTA with rollback +# and core dumps for the link +CONFIG_TINYUSB_CDC_ENABLED=y +CONFIG_TINYUSB_CDC_COUNT=1 +CONFIG_TINYUSB_CDC_RX_BUFSIZE=512 +CONFIG_TINYUSB_CDC_TX_BUFSIZE=4096 +CONFIG_TINYUSB_VENDOR_COUNT=1 +CONFIG_TINYUSB_VENDOR_RX_BUFSIZE=8192 +CONFIG_TINYUSB_VENDOR_TX_BUFSIZE=8192 +CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y +CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=y +CONFIG_ESP_COREDUMP_DATA_FORMAT_ELF=y +CONFIG_ESP_COREDUMP_CHECKSUM_CRC32=y # ESP32-specific # @@ -120,4 +137,10 @@ CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=n CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y -CONFIG_SPI_FLASH_ROM_IMPL=y +# not the ROM's flash driver: its spi_flash_mmap() picks virtual pages from its +# own table, which counts the PSRAM heap's pages as free, so the first flash +# mapping (core dump init reading the partition table) took a heap page and its +# unmap left that page unmapped (Dark Forces crashed loading its first level: +# "Cache error (MMU entry fault)"). The IDF driver maps through esp_mm. Costs +# ~8 KB of internal RAM. +# CONFIG_SPI_FLASH_ROM_IMPL is not set diff --git a/tools/emulink/emulink/__init__.py b/tools/emulink/emulink/__init__.py new file mode 100644 index 00000000..c12cea3f --- /dev/null +++ b/tools/emulink/emulink/__init__.py @@ -0,0 +1,12 @@ +"""emulink: drive esp-box-emu / tab5-emu over their composite USB device. + +The device's vendor (WebUSB) interface carries espp `stream_frame` frames +routed by module: OTA (0, esp-box-emu), core dump (4), system (7), monitor (8) +and the emulator's test control (0x20). The CDC interface carries the console +and the MSC interface is the SD card (when handed to the PC). +""" + +from .link import Link, LinkError # noqa: F401 +from .control import Control, ControlError, Buttons # noqa: F401 + +__version__ = "0.1.0" diff --git a/tools/emulink/emulink/__main__.py b/tools/emulink/emulink/__main__.py new file mode 100644 index 00000000..dd8a8c90 --- /dev/null +++ b/tools/emulink/emulink/__main__.py @@ -0,0 +1,5 @@ +import sys + +from .cli import main + +sys.exit(main()) diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py new file mode 100644 index 00000000..de264287 --- /dev/null +++ b/tools/emulink/emulink/cli.py @@ -0,0 +1,525 @@ +"""emulink command line: python -m emulink ...""" + +from __future__ import annotations + +import argparse +import json +import os +import struct +import sys +import time +import zlib +from typing import Optional + +from . import espp_tools +from .control import Buttons, Control, ControlError +from .link import Link, LinkError, find_console_port, find_devices + + +def _progress(label: str): + start = time.monotonic() + + def cb(done: int, total: int) -> None: + if not sys.stderr.isatty(): + return + pct = 100 * done // total if total else 100 + rate = done / max(time.monotonic() - start, 1e-3) / 1024 + sys.stderr.write(f"\r{label}: {pct:3d}% {done}/{total} bytes ({rate:.0f} KiB/s)") + if done >= total: + sys.stderr.write("\n") + sys.stderr.flush() + + return cb + + +def _png(width: int, height: int, rgb: bytes) -> bytes: + raw = b"".join(b"\x00" + rgb[y * width * 3:(y + 1) * width * 3] for y in range(height)) + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")) + + +def frame_to_png(frame, big_endian: bool) -> bytes: + return _png(frame.width, frame.height, frame.rgb(big_endian)) + + +def _open(args, timeout_s: float = 0.0) -> Link: + return Link(args.serial).open(timeout_s) + + +def cmd_devices(args) -> int: + for d in find_devices(): + print(f"{d['serial']:12s} {d['product']:20s} bus {d['bus']} address {d['address']} " + f"console {find_console_port(d['serial']) or '-'}") + return 0 + + +def cmd_status(args) -> int: + with _open(args) as link: + print(json.dumps(Control(link).status(), indent=2)) + return 0 + + +def cmd_info(args) -> int: + with _open(args) as link: + print(json.dumps(Control(link).info(), indent=2)) + return 0 + + +def cmd_roms(args) -> int: + with _open(args) as link: + roms = Control(link).roms() + if args.json: + print(json.dumps(roms, indent=2)) + return 0 + console = None + for r in roms: + if r["console"] != console: + console = r["console"] + print(f"== {console}") + print(f" {r['name']} ({r['path']})") + return 0 + + +def cmd_launch(args) -> int: + with _open(args) as link: + rom = Control(link).launch(args.match, wait=not args.no_wait, timeout_s=args.timeout) + print(rom) + return 0 + + +def cmd_quit(args) -> int: + with _open(args) as link: + Control(link).quit(wait=not args.no_wait) + return 0 + + +def cmd_press(args) -> int: + with _open(args) as link: + c = Control(link) + for _ in range(args.repeat): + c.press(args.buttons, hold_ms=args.hold, gap_ms=args.gap) + return 0 + + +def cmd_hold(args) -> int: + with _open(args) as link: + Control(link).buttons(Buttons.parse(args.buttons), 0) + return 0 + + +def cmd_save(args) -> int: + with _open(args) as link: + Control(link).save(args.slot) + return 0 + + +def cmd_load(args) -> int: + with _open(args) as link: + Control(link).load(args.slot) + return 0 + + +def cmd_screenshot(args) -> int: + with _open(args) as link: + frame = Control(link).frame(progress=_progress("screenshot")) + if args.byteswap is not None: + big_endian = args.byteswap + else: # every core so far renders little-endian RGB565 + big_endian = frame.format == "rgb565be" + out = args.output or time.strftime("screenshot-%Y%m%d-%H%M%S.png") + with open(out, "wb") as f: + if out.endswith(".png"): + f.write(frame_to_png(frame, big_endian)) + else: # the device's own screenshot file format + f.write(struct.pack(">HH", frame.width, frame.height) + frame.data) + print(out) + return 0 + + +def cmd_ls(args) -> int: + with _open(args) as link: + for e in Control(link).ls(args.path): + print(f"{'d' if e['dir'] else '-'} {e['size']:>10} {e['name']}") + return 0 + + +def cmd_push(args) -> int: + with _open(args) as link: + for f in Control(link).push(args.local, args.remote, _progress(os.path.basename(args.local))): + print(f) + return 0 + + +def cmd_pull(args) -> int: + with _open(args) as link: + data = Control(link).read_file(args.remote, _progress(os.path.basename(args.remote))) + out = args.local or os.path.basename(args.remote) + with open(out, "wb") as f: + f.write(data) + print(out) + return 0 + + +def cmd_rm(args) -> int: + with _open(args) as link: + Control(link).rm(args.path) + return 0 + + +def cmd_mkdir(args) -> int: + with _open(args) as link: + Control(link).mkdir(args.path) + return 0 + + +def cmd_add_rom(args) -> int: + """Copy a game (and its boxart) to the card, list it in metadata.csv, reload.""" + with _open(args) as link: + c = Control(link) + rom_remote = f"{args.dir.strip('/')}/{os.path.basename(args.rom)}" + c.push(args.rom, rom_remote, _progress(os.path.basename(args.rom))) + boxart = "" + if args.boxart: + boxart = f"boxart/{os.path.basename(args.boxart)}" + c.push(args.boxart, boxart, _progress(os.path.basename(args.boxart))) + name = args.name or os.path.splitext(os.path.basename(args.rom))[0] + total = c.add_rom(rom_remote, name, boxart) + print(f"{rom_remote}: listed as {name!r} ({total} games)") + return 0 + + +def cmd_remove_rom(args) -> int: + with _open(args) as link: + c = Control(link) + total = c.add_rom(args.rom, "", remove=True) + if args.delete: + c.rm(args.rom) + print(f"{total} games") + return 0 + + +def cmd_reload(args) -> int: + with _open(args) as link: + print(Control(link).reload_roms()) + return 0 + + +def _msc_disk(product: str) -> Optional[str]: + """macOS: the BSD disk (e.g. disk20) of the emulator's SD card drive.""" + import re + import subprocess + + try: + out = subprocess.run(["ioreg", "-p", "IOService", "-l", "-w0", "-r", "-n", product], + capture_output=True, text=True, timeout=10).stdout + except (OSError, subprocess.TimeoutExpired): + return None + m = re.search(r'"BSD Name" = "(disk\d+)"', out) + return m.group(1) if m else None + + +def _msc_mount(product: str) -> Optional[str]: + """macOS: where the emulator's SD card is mounted, once it is.""" + import plistlib + import subprocess + + disk = _msc_disk(product) + if not disk: + return None + try: + out = subprocess.run(["diskutil", "info", "-plist", f"{disk}s1"], capture_output=True, timeout=10).stdout + mount = plistlib.loads(out).get("MountPoint") if out else None + except (OSError, subprocess.TimeoutExpired, plistlib.InvalidFileException): + return None + return mount or None + + +def cmd_drive(args) -> int: + """Hand the SD card to the PC (it mounts it), or take it back: on macOS the + volume is ejected first, which the device needs before it can have it.""" + with _open(args) as link: + serial = link.serial # (check this device again, not the first one found) + c = Control(link) + if args.state == "on": + c.usb_drive(True) + if sys.platform == "darwin": + deadline = time.monotonic() + 60 + mount = None + while time.monotonic() < deadline and not mount: + time.sleep(0.5) + mount = _msc_mount(link.product) + print(f"the PC has the SD card ({mount or 'not mounted yet'})") + return 0 + if sys.platform == "darwin": + disk = _msc_disk(link.product) + if disk: + import subprocess + + # Spotlight (mdsync) indexing a freshly mounted volume refuses + # the unmount for a while: retry + deadline = time.monotonic() + 60 + while True: + r = subprocess.run(["diskutil", "eject", disk], capture_output=True, text=True, timeout=60) + if r.returncode == 0 or time.monotonic() >= deadline: + break + time.sleep(2) + if r.returncode != 0: + print(f"emulink: could not eject {disk}: {r.stderr.strip() or r.stdout.strip()}", + file=sys.stderr) + return 1 + try: + c.usb_drive(False) + except LinkError: + pass # the device may drop off the bus for a moment to take the card back + # (re)connect and check + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + try: + with Link(serial).open(5) as link: + if not Control(link).status()["usb_drive"]: + print("the device has the SD card again") + return 0 + except (LinkError, ControlError): + pass + time.sleep(0.5) + print("emulink: the device did not take the SD card back", file=sys.stderr) + return 1 + + +def cmd_reboot(args) -> int: + with _open(args) as link: + try: + Control(link).reboot(bootloader=args.bootloader) + except LinkError: + pass # the device may drop off the bus before its reply gets out + if args.bootloader: + # the ROM's download mode shows up as the chip's USB-Serial-JTAG port + from serial.tools import list_ports + + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + for p in list_ports.comports(): + if p.vid == 0x303A and p.pid == 0x1001: + print(p.device) + return 0 + time.sleep(0.5) + print("emulink: no download-mode port showed up", file=sys.stderr) + return 1 + return 0 + + +def cmd_log(args) -> int: + """Follow the console; across a reboot (the port goes away and comes back) + it reconnects, so a log can span a reset.""" + import serial + + out = open(args.output, "ab") if args.output else None + write = out.write if out else sys.stdout.buffer.write + end = time.monotonic() + args.duration if args.duration else None + until = args.until.encode() if args.until else None + tail = b"" # (the text can straddle two reads) + first_wait = time.monotonic() + args.wait + while end is None or time.monotonic() < end: + port = find_console_port(args.serial) + if not port: + if time.monotonic() > first_wait and out is None and args.duration == 0 and not args.follow: + print("no emulator console port found", file=sys.stderr) + return 1 + time.sleep(0.2) + continue + try: + with serial.Serial(port, 115200, timeout=0.2) as s: + while end is None or time.monotonic() < end: + data = s.read(4096) + if data: + write(data) + (out or sys.stdout.buffer).flush() + if until: + if until in tail + data: + return 0 + tail = (tail + data)[-len(until):] + except (serial.SerialException, OSError): + time.sleep(0.2) # the device went away (reset): wait for it to come back + return 0 + + +def cmd_coredump(args) -> int: + cd = espp_tools.load("espp_coredump", "coredump") + from espp_coredump.client import CoreDumpClient # type: ignore + + with _open(args) as link: + client = CoreDumpClient(link) + size = client.size() + if not size: + print("no core dump on the device") + return 0 + print(client.summary()) + if args.output: + image = client.read_image() + with open(args.output, "wb") as f: + f.write(image) + print(f"{args.output}: {len(image)} bytes (decode: esp-coredump info_corefile -t raw -c {args.output} " + f"build/.elf)") + if args.erase: + client.erase() + print("erased") + return 0 + + +def cmd_ota(args) -> int: + """Flash a new app over USB. On the Tab5 (no second emulator slot) the + emulator reboots into the updater app first, which takes the image.""" + espp_tools.load("espp_ota", "ota") + from espp_ota.client import OtaClient # type: ignore + + image = open(args.binary, "rb").read() + link = _open(args) + serial = link.serial # (the updater and the new firmware are this same device) + try: + if "updater" not in link.product.lower(): + print("rebooting into the updater ...") + Control(link).enter_updater() + link.close() + time.sleep(2) + link = Link(serial) + deadline = time.monotonic() + 30 + while True: + try: + link.open(5) + if "updater" in link.product.lower(): + break + link.close() + except LinkError: + pass + if time.monotonic() > deadline: + raise LinkError("the updater did not show up") + time.sleep(1) + print(f"flashing {args.binary} ({len(image)} bytes) via {link.product} ...") + OtaClient(link, progress=_progress("ota")).flash(image, image_size=len(image)) + print("done: the device restarts into the new firmware") + finally: + link.close() + if args.wait: + link = Link(serial) + last_error = None + deadline = time.monotonic() + args.wait + while time.monotonic() < deadline: + try: + link.open(5) + if "updater" not in link.product.lower(): + st = Control(link).status() + print(f"up: {st['firmware']} ({st['built']}, elf {st.get('elf_sha256', '?')}) on {st['partition']}") + link.close() + return 0 + link.close() + except (LinkError, ControlError) as e: + last_error = e + link.close() + time.sleep(1) + print(f"the new firmware did not come up ({last_error})", file=sys.stderr) + return 1 + return 0 + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="emulink", description=__doc__) + p.add_argument("--serial", help="USB serial number (tab5-emu / esp-box-emu); default: the first one found") + sub = p.add_subparsers(dest="cmd", required=True) + + sub.add_parser("devices", help="list the emulators on USB").set_defaults(fn=cmd_devices) + sub.add_parser("status", help="state, running game, memory, firmware").set_defaults(fn=cmd_status) + sub.add_parser("info", help="chip, firmware, partitions, last reset reason (system service)").set_defaults(fn=cmd_info) + s = sub.add_parser("roms", help="the game list") + s.add_argument("--json", action="store_true") + s.set_defaults(fn=cmd_roms) + s = sub.add_parser("launch", help="start a game (rom path, or part of a name / path)") + s.add_argument("match") + s.add_argument("--no-wait", action="store_true") + s.add_argument("--timeout", type=float, default=60) + s.set_defaults(fn=cmd_launch) + s = sub.add_parser("quit", help="quit the running game") + s.add_argument("--no-wait", action="store_true") + s.set_defaults(fn=cmd_quit) + s = sub.add_parser("press", help="press buttons (a b x y select start up down left right l r l2 r2; a+b = together)") + s.add_argument("buttons", nargs="+") + s.add_argument("--hold", type=int, default=100, help="ms each press is held") + s.add_argument("--gap", type=int, default=100, help="ms after each press") + s.add_argument("--repeat", type=int, default=1) + s.set_defaults(fn=cmd_press) + s = sub.add_parser("hold", help="hold buttons until the next press/hold (hold with none releases)") + s.add_argument("buttons", nargs="*") + s.set_defaults(fn=cmd_hold) + for name, fn in (("save", cmd_save), ("load", cmd_load)): + s = sub.add_parser(name, help=f"{name} a save state") + s.add_argument("slot", type=int) + s.set_defaults(fn=fn) + s = sub.add_parser("screenshot", help="the running game's frame as a PNG") + s.add_argument("-o", "--output") + s.add_argument("--byteswap", action=argparse.BooleanOptionalAction, default=None, + help="RGB565 big-endian (default: the byte order the device reports)") + s.set_defaults(fn=cmd_screenshot) + s = sub.add_parser("ls", help="list a directory on the SD card") + s.add_argument("path", nargs="?", default="") + s.set_defaults(fn=cmd_ls) + s = sub.add_parser("push", help="copy a file / directory to the SD card (relative paths are from its root)") + s.add_argument("local") + s.add_argument("remote") + s.set_defaults(fn=cmd_push) + s = sub.add_parser("pull", help="copy a file from the SD card") + s.add_argument("remote") + s.add_argument("local", nargs="?") + s.set_defaults(fn=cmd_pull) + s = sub.add_parser("rm", help="delete a file / directory on the SD card") + s.add_argument("path") + s.set_defaults(fn=cmd_rm) + s = sub.add_parser("mkdir") + s.add_argument("path") + s.set_defaults(fn=cmd_mkdir) + s = sub.add_parser("add-rom", help="copy a game to the card and list it in metadata.csv") + s.add_argument("rom") + s.add_argument("--dir", required=True, help="directory on the card, e.g. genesis") + s.add_argument("--name") + s.add_argument("--boxart", help="a JPEG, copied to boxart/") + s.set_defaults(fn=cmd_add_rom) + s = sub.add_parser("remove-rom", help="take a game out of metadata.csv") + s.add_argument("rom", help="its path on the card, as in metadata.csv") + s.add_argument("--delete", action="store_true", help="also delete the file") + s.set_defaults(fn=cmd_remove_rom) + sub.add_parser("reload", help="re-read metadata.csv").set_defaults(fn=cmd_reload) + s = sub.add_parser("drive", help="hand the SD card to the PC as a USB drive (on) or take it back (off)") + s.add_argument("state", choices=("on", "off")) + s.set_defaults(fn=cmd_drive) + s = sub.add_parser("reboot") + s.add_argument("--bootloader", action="store_true", help="into the ROM download mode (for idf.py flash)") + s.set_defaults(fn=cmd_reboot) + s = sub.add_parser("log", help="print (or save) the console") + s.add_argument("-o", "--output") + s.add_argument("--duration", type=float, default=0, help="seconds (0 = until ^C)") + s.add_argument("--until", help="stop once this text is seen") + s.add_argument("--follow", action="store_true", help="keep waiting for the port to (re)appear") + s.add_argument("--wait", type=float, default=10, help="seconds to wait for the port") + s.set_defaults(fn=cmd_log) + s = sub.add_parser("coredump", help="the last crash: summary, image, erase") + s.add_argument("-o", "--output", help="save the raw core dump") + s.add_argument("--erase", action="store_true") + s.set_defaults(fn=cmd_coredump) + s = sub.add_parser("ota", help="flash a new app (build/.bin) over USB") + s.add_argument("binary") + s.add_argument("--wait", type=float, default=90, help="seconds to wait for it to come up (0 = do not)") + s.set_defaults(fn=cmd_ota) + return p + + +def main(argv: Optional[list] = None) -> int: + args = build_parser().parse_args(argv) + try: + return args.fn(args) + except (LinkError, ControlError, ValueError) as e: + print(f"emulink: {e}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + return 130 diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py new file mode 100644 index 00000000..abe2c6b8 --- /dev/null +++ b/tools/emulink/emulink/control.py @@ -0,0 +1,347 @@ +"""The emulator's test control (dispatcher module 0x20, "emu.control") and the +espp system service (module 7), on top of a Link.""" + +from __future__ import annotations + +import json +import os +import struct +import sys +import time +from typing import Iterable, List, Optional + +from .link import Link, LinkError + +MODULE = 0x20 +SYSTEM_MODULE = 7 + +STATUS, LIST_ROMS, LAUNCH, QUIT, BUTTONS, SAVE, LOAD, SCREENSHOT, USB_DRIVE, RELOAD_ROMS, ENTER_UPDATER = range(1, 12) +SCREENSHOT_READ = 0x0C +FILE_LIST, FILE_READ, FILE_WRITE, FILE_DELETE, MKDIR, FILE_STAT, FILE_CLOSE = range(0x10, 0x17) + +#: one FILE_WRITE: the frame payload is at most 4096 bytes, of which 6 + the path are the header +CHUNK = 3584 + + +class ControlError(RuntimeError): + pass + + +class Frame: + """A game's frame: RGB565 pixels, row by row. ``format`` is "rgb565le" / + "rgb565be" (None: not reported by the device).""" + + def __init__(self, width: int, height: int, format: Optional[str], data: bytes) -> None: + self.width, self.height, self.format, self.data = width, height, format, data + + def rgb(self, big_endian: bool) -> bytes: + """The pixels as 8-bit RGB.""" + from array import array + px = array("H") + px.frombytes(self.data) + if big_endian != (sys.byteorder == "big"): + px.byteswap() + return b"".join(map(_rgb565_table().__getitem__, px)) + + +_RGB565 = None + + +def _rgb565_table(): + global _RGB565 + if _RGB565 is None: + def entry(v): + r, g, b = (v >> 11) & 0x1F, (v >> 5) & 0x3F, v & 0x1F + return bytes(((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2))) + _RGB565 = [entry(v) for v in range(65536)] + return _RGB565 + + +class Buttons: + """GamepadState::buttons bits.""" + + A, B, X, Y, SELECT, START, UP, DOWN, LEFT, RIGHT, L, R, L2, R2 = (1 << i for i in range(14)) + NAMES = {"a": A, "b": B, "x": X, "y": Y, "select": SELECT, "start": START, "up": UP, "down": DOWN, + "left": LEFT, "right": RIGHT, "l": L, "r": R, "l2": L2, "r2": R2} + + @classmethod + def parse(cls, names: Iterable[str]) -> int: + mask = 0 + for n in names: + for part in n.replace("+", ",").split(","): + part = part.strip().lower() + if not part: + continue + if part not in cls.NAMES: + raise ValueError(f"unknown button {part!r} (one of {', '.join(cls.NAMES)})") + mask |= cls.NAMES[part] + return mask + + +class Control: + def __init__(self, link: Link) -> None: + self.link = link + + # -- plumbing -------------------------------------------------------------- + def _call(self, type_: int, payload: bytes = b"", timeout_s: float = 15.0, raw: bool = False): + fr = self.link.request(MODULE, type_, payload, timeout_s=timeout_s) + if not fr.payload: + raise ControlError("empty reply") + status, body = fr.payload[0], fr.payload[1:] + if status != 0: + try: + msg = json.loads(body.decode()).get("error", body.decode()) + except Exception: + msg = body.decode(errors="replace") + raise ControlError(msg) + if raw: + return body + return json.loads(body.decode()) if body else {} + + @property + def root(self) -> str: + return "/sdcard" + + def remote(self, path: str) -> str: + """A path on the SD card: absolute, or relative to the card's root.""" + if path in ("", "/", "."): + return self.root + if path.startswith(self.root): + return path + return f"{self.root}/{path.lstrip('/')}" + + # -- the emulator ---------------------------------------------------------- + def status(self) -> dict: + return self._call(STATUS) + + def roms(self) -> List[dict]: + out: List[dict] = [] + offset = 0 + while True: + r = self._call(LIST_ROMS, str(offset).encode()) + out += r["roms"] + offset = r["next"] + if offset >= r["total"] or not r["roms"]: + return out + + def launch(self, match: str, wait: bool = True, timeout_s: float = 60.0) -> str: + rom = self._call(LAUNCH, match.encode())["rom"] + if wait: + self.wait_state("game", timeout_s) + return rom + + def quit(self, wait: bool = True, timeout_s: float = 30.0) -> None: + self._call(QUIT) + if wait: + self.wait_state("menu", timeout_s) + + def wait_state(self, state: str, timeout_s: float = 60.0) -> dict: + deadline = time.monotonic() + timeout_s + while True: + try: + st = self.status() + if st["state"] == state: + return st + except LinkError: + pass # busy (e.g. a game loading) + if time.monotonic() > deadline: + raise ControlError(f"not in state {state!r} after {timeout_s:.0f} s") + time.sleep(0.25) + + def buttons(self, mask: int, hold_ms: int = 0) -> None: + """Hold `mask` for hold_ms (then release), or until the next call (0).""" + self._call(BUTTONS, struct.pack(" None: + self.buttons(Buttons.parse(names), hold_ms) + if gap_ms: + time.sleep(gap_ms / 1000) + + def save(self, slot: int) -> None: + self._call(SAVE, bytes([slot]), timeout_s=60) + + def load(self, slot: int) -> None: + self._call(LOAD, bytes([slot]), timeout_s=60) + + def screenshot(self, remote_path: str = "screenshots/screenshot.bin") -> str: + """Save the running game's frame on the SD card ([u16be w][u16be h][RGB565]); returns its path.""" + return self._call(SCREENSHOT, self.remote(remote_path).encode())["path"] + + def frame(self, progress=None) -> "Frame": + """The running game's frame, copied straight from its frame buffer + (firmware before protocol 2 saves it on the card and it is read from + there).""" + info = self._call(SCREENSHOT, timeout_s=15) + if "path" in info: # older firmware + data = self.read_file(info["path"]) + if len(data) < 4: + raise ControlError(f"the screenshot file {info['path']} is {len(data)} bytes") + w, h = struct.unpack(">HH", data[:4]) + px = data[4:] + if w: + h = min(h, len(px) // (w * 2)) + return Frame(w, h, None, px[:w * h * 2]) + size = info["size"] + out = bytearray() + while len(out) < size: + n = min(4000, size - len(out)) + chunk = self._call(SCREENSHOT_READ, struct.pack(" None: + self._call(USB_DRIVE, bytes([1 if host else 0]), timeout_s=20) + + def reload_roms(self) -> int: + return self._call(RELOAD_ROMS)["total"] + + def enter_updater(self) -> None: + self._call(ENTER_UPDATER) + + # -- files on the SD card -------------------------------------------------- + def ls(self, path: str = "") -> List[dict]: + path = self.remote(path).encode() + r = self._call(FILE_LIST, path) + out = r["entries"] + # a full page says where the next starts; older firmware only says "truncated" + while r.get("truncated") and r.get("next") is not None and r["entries"]: + r = self._call(FILE_LIST, path + b"\0" + str(r["next"]).encode()) + out += r["entries"] + return out + + def stat(self, path: str) -> Optional[dict]: + """None if there is no such file; any other failure raises.""" + try: + return self._call(FILE_STAT, self.remote(path).encode()) + except ControlError as e: + if "does not exist" in str(e): + return None + raise + + def mkdir(self, path: str) -> None: + self._call(MKDIR, self.remote(path).encode()) + + def rm(self, path: str) -> None: + self._call(FILE_DELETE, self.remote(path).encode(), timeout_s=60) + + def read_file(self, path: str, progress=None) -> bytes: + path = self.remote(path) + st = self._call(FILE_STAT, path.encode()) + size = st["size"] + out = bytearray() + while len(out) < size: + n = min(4000, size - len(out)) + chunk = self._call(FILE_READ, struct.pack(" None: + path = self.remote(path) + p = path.encode() + chunk = CHUNK - len(p) + if chunk < 256: + raise ControlError("path too long") + off = 0 + while True: + part = data[off: off + chunk] + self._call(FILE_WRITE, struct.pack("= len(data): + break + self._call(FILE_CLOSE) + + def push(self, local: str, remote: str, progress=None) -> List[str]: + """Copy a file or a directory tree to the SD card; returns the remote files.""" + written = [] + if os.path.isdir(local): + for root, _dirs, files in os.walk(local): + for f in files: + src = os.path.join(root, f) + rel = os.path.relpath(src, local) + dst = f"{remote.rstrip('/')}/{rel}" + self.write_file(dst, open(src, "rb").read(), progress) + written.append(self.remote(dst)) + else: + if remote.endswith("/"): + remote += os.path.basename(local) + self.write_file(remote, open(local, "rb").read(), progress) + written.append(self.remote(remote)) + return written + + def add_rom(self, rom_path: str, name: str, boxart: str = "", remove: bool = False) -> int: + """Add (or with remove=True take out) a metadata.csv line; returns the + number of games after reloading the list.""" + rom_rel = rom_path[len(self.root) + 1:] if rom_path.startswith(self.root + "/") else rom_path + # metadata.csv has no quoting: the paths end at a comma (the name, the + # last field, may have them) and a line break starts another game + for field, value in (("ROM path", rom_rel), ("boxart path", boxart), ("name", name)): + if "\n" in value or "\r" in value or (field != "name" and "," in value): + raise ControlError(f"the {field} cannot hold {'a comma' if ',' in value else 'a line break'}: {value!r}") + meta = self.remote("metadata.csv") + # only a missing file starts an empty list: a failed read must not + # rewrite metadata.csv with just this game + text = self.read_file(meta).decode() if self.stat(meta) is not None else "" + lines = [l for l in text.splitlines() if l.strip() and l.split(",")[0].strip() != rom_rel] + if not remove: + lines.append(f"{rom_rel}, {boxart}, {name}") + self.write_file(meta, ("\n".join(lines) + "\n").encode()) + return self.reload_roms() + + # -- the espp system service ------------------------------------------------ + RESET_REASONS = {0: "unknown", 1: "power-on", 2: "external", 3: "software", 4: "panic", 5: "interrupt WDT", + 6: "task WDT", 7: "other WDT", 8: "deep sleep", 9: "brownout", 10: "SDIO", 11: "USB", + 12: "JTAG", 13: "eFuse", 14: "power glitch", 15: "CPU lockup"} + + def info(self) -> dict: + """The espp system service's GET_INFO: chip, firmware, partitions, reset reason, uptime...""" + fr = self.link.request(SYSTEM_MODULE, 0x01, b"", timeout_s=5, reply_types=(0x81, 0x84)) + if fr.type != 0x81: + raise ControlError("GET_INFO failed") + p, i, out = fr.payload, 0, {} + strs = {1: "chip", 6: "project", 7: "firmware", 5: "idf", 8: "build_date", 9: "build_time", + 11: "running_partition", 12: "boot_partition"} + while i + 2 <= len(p): + tag, n = p[i], p[i + 1] + v = p[i + 2:i + 2 + n] + i += 2 + n + if tag in strs: + out[strs[tag]] = v.decode(errors="replace") + elif tag == 2: + out["chip_revision"] = int.from_bytes(v, "little") + elif tag == 3: + out["cores"] = v[0] + elif tag == 10: + out["elf_sha256"] = v.hex() + elif tag == 13: + out["ota_state"] = {0: "new", 1: "pending verify", 2: "valid", 3: "invalid", 4: "aborted", + 0xFE: "undefined", 0xFF: "n/a"}.get(v[0], v[0]) + elif tag == 14: + out["reset_reason"] = self.RESET_REASONS.get(v[0], v[0]) + elif tag == 15: + out["uptime_ms"] = int.from_bytes(v, "little") + elif tag == 16: + out["mac"] = ":".join(f"{b:02x}" for b in v) + elif tag in (17, 18, 19, 20, 21): + out[{17: "flash_size", 18: "psram_size", 19: "cpu_mhz", 20: "free_heap", 21: "min_free_heap"}[tag]] = \ + int.from_bytes(v, "little") + return out + + def reboot(self, bootloader: bool = False, delay_ms: int = 250) -> None: + self.link.request(SYSTEM_MODULE, 0x03 if bootloader else 0x02, struct.pack("/python``) or in a project's +``managed_components/espp__/python`` after a build. +""" + +from __future__ import annotations + +import importlib +import os +import sys +from pathlib import Path + +_HERE = Path(__file__).resolve() +_REPO = _HERE.parents[3] # tools/emulink/emulink/espp_tools.py -> the project + + +def _candidates(component: str): + if os.environ.get("ESPP_DIR"): + yield Path(os.environ["ESPP_DIR"]) / "components" / component / "python" + for base in (_REPO, _REPO / "updater"): + yield base / "managed_components" / f"espp__{component}" / "python" + yield Path.home() / "esp-cpp" / "espp" / "components" / component / "python" + + +def load(package: str, component: str): + """Import `package` (e.g. espp_ota) from wherever the espp component is.""" + try: + return importlib.import_module(package) + except ImportError: + pass + for c in _candidates(component): + if (c / package).is_dir(): + sys.path.insert(0, str(c)) + return importlib.import_module(package) + raise ImportError(f"{package} not found: set ESPP_DIR to an espp checkout, or build the project " + f"so managed_components/espp__{component} exists") diff --git a/tools/emulink/emulink/frame.py b/tools/emulink/emulink/frame.py new file mode 100644 index 00000000..6949550f --- /dev/null +++ b/tools/emulink/emulink/frame.py @@ -0,0 +1,86 @@ +"""The espp stream_frame v2 codec (see espp/components/stream_frame). + +[magic u16 = 0x4F54]["flags u8"][module u8][type u8]{[correlation u16]}[len u32][payload][crc32 u32] +little-endian; flags bit0 = reply, bit1 = correlation present, bits 4..7 = version (1). +""" + +from __future__ import annotations + +import struct +import zlib +from dataclasses import dataclass +from typing import List, Optional + +MAGIC = 0x4F54 +MAGIC_BYTES = struct.pack(" bool: + return bool(self.flags & FLAG_REPLY) + + +def build(module: int, type_: int, payload: bytes = b"", reply: bool = False, + correlation: Optional[int] = None) -> bytes: + if len(payload) > MAX_PAYLOAD: + raise ValueError(f"payload too large ({len(payload)} > {MAX_PAYLOAD})") + flags = (VERSION << 4) | (FLAG_REPLY if reply else 0) | (FLAG_CORRELATION if correlation is not None else 0) + out = bytearray(MAGIC_BYTES) + out += bytes([flags, module & 0xFF, type_ & 0xFF]) + if correlation is not None: + out += struct.pack(" None: + self._buf = bytearray() + + def feed(self, data: bytes) -> List[Frame]: + self._buf += data + frames: List[Frame] = [] + while True: + i = self._buf.find(MAGIC_BYTES) + if i < 0: + # keep a trailing half magic + del self._buf[:-1] + return frames + if i: + del self._buf[:i] + if len(self._buf) < 5: + return frames + flags = self._buf[2] + hdr = 5 + (2 if flags & FLAG_CORRELATION else 0) + 4 + if len(self._buf) < hdr: + return frames + corr = struct.unpack_from(" MAX_PAYLOAD: + del self._buf[:2] # not a frame: resync past this magic + continue + total = hdr + length + 4 + if len(self._buf) < total: + return frames + crc = struct.unpack_from(" List[dict]: + """The emulators on the bus: [{serial, product, bus, address}].""" + core, util = _usb() + out = [] + for dev in core.find(find_all=True, idVendor=VID, idProduct=PID) or []: + try: + serial = util.get_string(dev, dev.iSerialNumber) + product = util.get_string(dev, dev.iProduct) + except Exception: + continue + if serial in SERIALS: + out.append({"serial": serial, "product": product, "bus": dev.bus, "address": dev.address, "dev": dev}) + return out + + +class Link: + """One open vendor interface. Also a transport for the espp host clients + (``write(bytes, timeout_ms)`` / ``read(max_len, timeout_ms)``).""" + + def __init__(self, serial: Optional[str] = None) -> None: + self.serial = serial or os.environ.get("EMULINK_SERIAL") + self._dev = None + self._itf = None + self._ep_in = None + self._ep_out = None + self._parser = _f.Parser() + self._pending: Deque[_f.Frame] = deque() + self._corr = itertools.count(1) + self.product = "" + + # -- lifecycle ------------------------------------------------------------- + def open(self, timeout_s: float = 0.0) -> "Link": + core, util = _usb() + deadline = time.monotonic() + timeout_s + while True: + devs = [d for d in find_devices() if self.serial in (None, d["serial"])] + if devs: + break + if time.monotonic() >= deadline: + raise LinkError("no emulator found on USB" + (f" with serial {self.serial!r}" if self.serial else "")) + time.sleep(0.5) + d = devs[0] + self._dev, self.serial, self.product = d["dev"], d["serial"], d["product"] + try: + return self._claim(core, util) + except core.USBError as e: + # e.g. still enumerating after a reset: the caller may retry + self._dev = None + raise LinkError(f"cannot open the device's vendor interface: {e}") from e + + def _claim(self, core, util) -> "Link": + cfg = self._dev.get_active_configuration() + for itf in cfg: + if itf.bInterfaceClass != 0xFF: + continue + eps = list(itf) + ep_in = next((e for e in eps if util.endpoint_direction(e.bEndpointAddress) == util.ENDPOINT_IN), None) + ep_out = next((e for e in eps if util.endpoint_direction(e.bEndpointAddress) == util.ENDPOINT_OUT), None) + if ep_in is not None and ep_out is not None: + self._itf, self._ep_in, self._ep_out = itf.bInterfaceNumber, ep_in, ep_out + break + if self._itf is None: + raise LinkError("the device has no vendor interface") + try: + if self._dev.is_kernel_driver_active(self._itf): + self._dev.detach_kernel_driver(self._itf) + except (NotImplementedError, core.USBError): + pass + util.claim_interface(self._dev, self._itf) + return self + + def close(self) -> None: + if self._dev is not None: + _, util = _usb() + try: + util.release_interface(self._dev, self._itf) + util.dispose_resources(self._dev) + except Exception: + pass + self._dev = None + self._itf = None + # (a reply cut off by a reset must not be glued onto the next one) + self._parser = _f.Parser() + self._pending.clear() + + def __enter__(self) -> "Link": + return self.open() if self._dev is None else self + + def __exit__(self, *exc) -> None: + self.close() + + # -- raw transport (espp clients use these) -------------------------------- + def write(self, data: bytes, timeout_ms: int = 5000) -> int: + try: + return self._ep_out.write(data, timeout=timeout_ms) + except Exception as e: + raise LinkError(f"USB write failed: {e}") from e + + def read(self, max_len: int = 16384, timeout_ms: int = 1000) -> bytes: + core, _ = _usb() + try: + return bytes(self._ep_in.read(max(max_len, 64), timeout=timeout_ms)) + except core.USBTimeoutError: + return b"" + except core.USBError as e: + if getattr(e, "errno", None) in (60, 110) or "timed out" in str(e).lower(): + return b"" + raise LinkError(f"USB read failed: {e}") from e + + # -- request / reply ------------------------------------------------------- + def request(self, module: int, type_: int, payload: bytes = b"", timeout_s: float = 10.0, + reply_types: Optional[tuple] = None) -> _f.Frame: + """Send a request and return its reply (matched by module and + correlation id; frames for anything else are dropped).""" + corr = next(self._corr) & 0xFFFF + try: + self.write(_f.build(module, type_, payload, correlation=corr)) + except LinkError: + # the host reset the interface (e.g. macOS after ejecting the + # device's drive): open it again once + self.close() + self.open(timeout_s=10) + self.write(_f.build(module, type_, payload, correlation=corr)) + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + while self._pending: + fr = self._pending.popleft() + if fr.is_reply and fr.module == module and (fr.correlation in (None, corr)) and \ + (reply_types is None or fr.type in reply_types): + return fr + data = self.read(16384, timeout_ms=200) + if data: + self._pending.extend(self._parser.feed(data)) + raise LinkError(f"no reply from module {module:#x} to request {type_:#x} in {timeout_s:.0f} s") + + +def find_console_port(serial: Optional[str] = None) -> Optional[str]: + """The CDC console's serial port (e.g. /dev/cu.usbmodem...) of an emulator.""" + from serial.tools import list_ports + + for p in list_ports.comports(): + if p.vid == VID and p.pid == PID and (p.serial_number in SERIALS) and serial in (None, p.serial_number): + return p.device + return None diff --git a/updater/CMakeLists.txt b/updater/CMakeLists.txt new file mode 100644 index 00000000..119ebbd5 --- /dev/null +++ b/updater/CMakeLists.txt @@ -0,0 +1,14 @@ +# The ESP-Box-Emu updater: a small app in the ota_1 slot (the emulator cannot +# write its own flash, see partitions.csv). An update reboots into it (the emulator's +# test control ENTER_UPDATER request); it takes the new emulator image over +# the USB link (espp OTA service), writes ota_0 and boots it. With nothing to +# do it boots the emulator again after a while. See tools/emulink. +cmake_minimum_required(VERSION 3.20) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +set(COMPONENTS main esptool_py CACHE STRING "List of components to include" FORCE) + +project(esp-box-emu-updater) + +set(CMAKE_CXX_STANDARD 23) diff --git a/updater/main/CMakeLists.txt b/updater/main/CMakeLists.txt new file mode 100644 index 00000000..a931eb73 --- /dev/null +++ b/updater/main/CMakeLists.txt @@ -0,0 +1,3 @@ +idf_component_register(SRCS "updater.cpp" + INCLUDE_DIRS "." + REQUIRES app_update esp_hal_usb esp_timer hal driver ota dispatcher system usb_device) diff --git a/updater/main/idf_component.yml b/updater/main/idf_component.yml new file mode 100644 index 00000000..220d4514 --- /dev/null +++ b/updater/main/idf_component.yml @@ -0,0 +1,7 @@ +## IDF Component Manager Manifest File +dependencies: + idf: '>=6.0' + espp/usb_device: '>=1.4.2' + espp/ota: '>=1.4.2' + espp/dispatcher: '>=1.4.2' + espp/system: '>=1.4.2' diff --git a/updater/main/updater.cpp b/updater/main/updater.cpp new file mode 100644 index 00000000..3e5c5564 --- /dev/null +++ b/updater/main/updater.cpp @@ -0,0 +1,139 @@ +// The ESP-Box-Emu updater (the ota_1 slot). The emulator app (ota_0) runs its +// code from PSRAM (SPIRAM_FETCH_INSTRUCTIONS), and writing the flash from it +// corrupts its PSRAM heap; instead an update reboots into this small app (no +// PSRAM), which serves the espp OTA protocol on the USB-C port's vendor +// interface, writes the new emulator into ota_0 and boots it (the OTA service +// restarts after FINISH). The same scheme as tab5-emu's updater. +// +// Booted with no update to take (e.g. ENTER_UPDATER and then nothing), it +// boots the emulator again after kIdleTimeout. If the emulator image is not +// usable (a failed update, or one that rolled back here) it waits for one. +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dispatcher_worker.hpp" +#include "logger.hpp" +#include "ota.hpp" +#include "ota_service.hpp" +#include "system_service.hpp" +#include "usb_device.hpp" + +using namespace std::chrono_literals; + +static constexpr auto kIdleTimeout = 90s; + +// Before a reboot into the ROM download mode: the S3's one internal USB PHY +// is muxed to the OTG controller (TinyUSB) by an RTC-domain register that +// survives the reset; give it back to USB-Serial-JTAG (see the emulator's +// BoxEmu::usb_prepare_for_rom_download()). +static void usb_phy_to_serial_jtag() { + usb_serial_jtag_ll_phy_enable_external(false); + RTCCNTL.usb_conf.sw_usb_phy_sel = 0; + RTCCNTL.usb_conf.sw_hw_usb_phy_sel = 0; +} + +static const esp_partition_t *emulator_partition() { + return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, nullptr); +} + +// Whether ota_0 holds an app that can boot (a valid image that did not fail +// its verification after an update). +static bool emulator_bootable() { + const auto *p = emulator_partition(); + if (!p) return false; + esp_app_desc_t desc; + if (esp_ota_get_partition_description(p, &desc) != ESP_OK) return false; + esp_ota_img_states_t state; + if (esp_ota_get_state_partition(p, &state) == ESP_OK && + (state == ESP_OTA_IMG_INVALID || state == ESP_OTA_IMG_ABORTED)) { + return false; + } + return true; +} + +extern "C" void app_main(void) { + espp::Logger logger({.tag = "updater", .level = espp::Logger::Verbosity::INFO}); + logger.info("ESP-Box-Emu updater {}", esp_app_get_description()->version); + // this app is flashed once, not through an OTA; never leave it pending + esp_ota_mark_app_valid_cancel_rollback(); + + espp::UsbDevice::Config cfg; + cfg.manufacturer = "esp-cpp"; + cfg.product = "ESP-Box-Emu updater"; + cfg.serial_number = "esp-box-emu"; + espp::UsbDevice::CdcFunction cdc; + cdc.interface_name = "ESP-Box-Emu updater console"; + cdc.route_console = true; + cfg.cdc = cdc; + espp::UsbDevice::VendorFunction vendor; + vendor.interface_name = "ESP-Box-Emu link"; + vendor.webusb = true; + vendor.landing_page_url = "esp-cpp.github.io/espp/apps/ota_console.html"; + cfg.vendor = vendor; + + espp::UsbDevice usb(cfg); + + std::mutex tx_mutex; + auto send = [&](std::span frame) { + std::lock_guard lk(tx_mutex); + usb.write_vendor(frame); + }; + + std::atomic busy{false}; // an update has started: do not time out + // the idle timeout counts from the last request (a discovery or status + // query only delays it; an update, once it writes, stops it) + std::atomic last_rx_us{esp_timer_get_time()}; + espp::Ota ota({.progress_callback = [&](size_t written, size_t total) { busy = true; }}); + espp::OtaService ota_service(ota, {.send = send, .log_level = espp::Logger::Verbosity::INFO}); + espp::SystemService system_service({.send = send, + .on_reboot_request = + [](espp::SystemService::RebootKind kind) { + if (kind == espp::SystemService::RebootKind::Bootloader) { + usb_phy_to_serial_jtag(); + } + return true; + }}); + espp::DispatcherWorker link({.send = send, + .on_overflow = [&]() { ota_service.on_rx_overflow(); }, + .task_config = {.name = "link", .stack_size_bytes = 8192}}); + link.register_module(ota_service); + link.register_module(system_service); + link.serve_discovery("ESP-Box-Emu updater", esp_app_get_description()->version); + usb.set_vendor_receive_callback([&](std::span data) { + last_rx_us = esp_timer_get_time(); + link.push(data); + }); + + std::error_code ec; + if (!usb.initialize(ec)) { + logger.error("USB device: {}", ec.message()); + } + logger.info("waiting for an emulator image (espp OTA on the vendor interface)"); + + while (true) { + std::this_thread::sleep_for(1s); + // nothing asked of us: back to the emulator, if it can boot + const auto idle = std::chrono::microseconds(esp_timer_get_time() - last_rx_us); + if (!busy && idle > kIdleTimeout && emulator_bootable()) { + // (a slot whose header reads fine can still fail the full image check: + // then stay here, where an update can still fix it) + if (const esp_err_t err = esp_ota_set_boot_partition(emulator_partition()); err != ESP_OK) { + logger.error("the emulator image does not verify ({}); waiting for an update", esp_err_to_name(err)); + busy = true; + continue; + } + logger.info("no update; booting the emulator"); + esp_restart(); + } + } +} diff --git a/updater/sdkconfig.defaults b/updater/sdkconfig.defaults new file mode 100644 index 00000000..24d96f38 --- /dev/null +++ b/updater/sdkconfig.defaults @@ -0,0 +1,26 @@ +CONFIG_IDF_TARGET="esp32s3" + +CONFIG_COMPILER_OPTIMIZATION_SIZE=y + +CONFIG_ESPTOOLPY_FLASHMODE_QIO=y +CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y +CONFIG_ESPTOOLPY_FLASHSIZE="16MB" + +# the emulator's partition table (this app is built for its ota_1 slot) +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="../partitions.csv" +CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y + +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y + +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 +CONFIG_ESP_TASK_WDT_EN=n + +# the composite USB device: console on CDC, the OTA link on a vendor interface +CONFIG_TINYUSB_CDC_ENABLED=y +CONFIG_TINYUSB_CDC_COUNT=1 +CONFIG_TINYUSB_CDC_TX_BUFSIZE=2048 +CONFIG_TINYUSB_VENDOR_COUNT=1 +CONFIG_TINYUSB_VENDOR_RX_BUFSIZE=1024 +CONFIG_TINYUSB_VENDOR_TX_BUFSIZE=4608