From e0c87b0b93238b7f1bb8f6e2d39c2c839cf20eeb Mon Sep 17 00:00:00 2001 From: Addison King Date: Mon, 26 Oct 2026 00:02:14 -0400 Subject: [PATCH 1/4] feat: add manual exposure, night burst, and rear light controls --- README.md | 75 +++++- arm7/include/aptina.h | 5 +- arm7/source/aptina.c | 223 +++++++++++++++- arm7/source/aptina_i2c.c | 19 +- arm7/source/i2c_handler.c | 35 ++- arm9/include/camera.h | 8 + arm9/include/night.h | 20 ++ arm9/source/camera.c | 65 ++++- arm9/source/main.c | 418 ++++++++++++++++++++++++++---- arm9/source/night.c | 102 ++++++++ shared/include/pxi_vars.h | 23 +- tools/capture/Makefile | 13 + tools/capture/exposure_test.c | 237 +++++++++++++++++ tools/capture/night_test.c | 98 +++++++ tools/capture/rear_light_test.c | 75 ++++++ tools/capture/shim/nds.h | 14 + tools/capture/shim/nds/arm7/i2c.h | 1 + 17 files changed, 1338 insertions(+), 93 deletions(-) create mode 100644 arm9/include/night.h create mode 100644 arm9/source/night.c create mode 100644 tools/capture/Makefile create mode 100644 tools/capture/exposure_test.c create mode 100644 tools/capture/night_test.c create mode 100644 tools/capture/rear_light_test.c create mode 100644 tools/capture/shim/nds.h create mode 100644 tools/capture/shim/nds/arm7/i2c.h diff --git a/README.md b/README.md index 9aeb222..b3ff75b 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,9 @@ A homebrew camera app for the Nintendo DSi. Fork of [Pk11's dsi-camera](https:// ## Features - Photos: raw 640x480 YUV from either camera, burst capture while held +- Advanced photo controls: real sensor integration (shutter) and analogue gain +- Night burst: four full-resolution frames aligned and merged on the DSi into one photo +- Rear camera light toggle; always off during Night Burst captures - Video: 256x192 with microphone audio at up to 10fps, recorded to a simple chunked container - Album: date-grouped thumbnail gallery with full-screen viewing, video playback with sound, and delete - Optional timestamp watermark burned into photos and video frames as they're captured @@ -19,7 +22,7 @@ A homebrew camera app for the Nintendo DSi. Fork of [Pk11's dsi-camera](https:// | L/R | Take photos / start & stop recording | | Y | Toggle photo / video mode | | A | Swap camera | -| X | Toggle timestamp watermark | +| X | Advanced controls | | SELECT | Album | | START | Exit | @@ -36,8 +39,8 @@ The host-side photo index tests can be run without devkitPro using Copy `dsi-camera.nds` to your SD card and launch it (tested with Unlaunch). Photos and videos are saved to `sd:/photos/`; drop `tools/convert.sh` in that -folder and run it on a PC to get PNGs and MP4s. Options (currently just the -timestamp watermark) persist in `sd:/photos/settings.cfg`. +folder and run it on a PC to get PNGs and MP4s. Photo controls and the +timestamp watermark persist in `sd:/photos/settings.cfg`. The watermark is off by default. When on, the capture date and time are drawn into the pixels themselves — bottom right, white with a black outline — so they @@ -51,3 +54,69 @@ clean. - [Arisotura](http://kuribo64.net) for the camera init research - [devkitPro](https://github.com/devkitPro) for devkitARM, libnds, and calico - [nocash](https://problemkaputt.de) for GBATEK + +## Advanced controls + +Press **X**. Use up/down to select a row and left/right to adjust, +or tap the arrows beside a value. Press **A** on Shutter to return to Auto, +on Gain, Night Burst, or Timestamp to cycle/toggle, or on Reset to restore all +settings. Press **B** or **X** to return to the viewfinder. The top screen stays +live while adjusting. Gain is gray and cannot be selected until Shutter is manual. +In photo mode, L/R takes photos directly from Advanced without closing it; +the save confirmation appears below the controls. Hold L/R for regular burst +capture, or tap once for a Night Burst photo. +In video mode, the photo controls are disabled; Timestamp and Reset remain available. +Rear Light is available whenever the outer camera is selected. + +- **Shutter:** Auto, or 1–640 sensor lines. This writes the MT9V113's physical + coarse integration register (`0x3012`), disables the live sequencer drivers + as well as their state presets, and reapplies the setting + after preview/capture transitions. Shorter values collect less light; longer + values collect more. These are sensor integration units, not calibrated + fractions of a second. The fine integration term is fixed at `0x006B`. +- **Gain:** nominal 1x, 2x, 4x, or 8x analogue sensor gain with a manual + shutter. The dedicated color-channel gain registers (`0x302A`–`0x3030`) + preserve the color balance sampled when leaving Auto; white balance stays + locked during manual exposure. Sensor gain limits and quantization can limit + the selected gain. Auto restores the original core registers, automatic + exposure, gain, and white balance. This is not an ISO scale. +- **Night Burst:** one shutter press captures four frames and saves one merged + photo. Hold still; press B to cancel. Alignment compensates for small camera + shifts, and changed pixels are rejected to limit ghosting. If alignment fails, + the first frame supplies the affected detail. It reduces noise without raising + brightness or recovering clipped highlights. Use a longer manual integration + when more light is needed. Only the completed photo and its thumbnail are saved; + source frames stay in RAM. Timestamping happens after the merge. +- **Timestamp:** burns the capture date and time into saved photos and video. +- **Rear Light:** controls the pink indicator beside the outer camera and saves + your preference. Night Burst always switches it off before capturing any + frames, then restores your preference, including after cancellation or failure. + If switching it off cannot be verified, the burst does not capture a photo. + The inner camera keeps this light off. + +For the moon, start with a short manual shutter and 1x gain, then lengthen the +integration until the bright surface has detail. Night Burst can reduce noise +at that same exposure. The DSi's fixed wide-angle lens still limits lunar detail. +There is no digital exposure/brightness adjustment in this pipeline. + +Shutter, Gain, and Night Burst apply only to photos. Video restores each sensor's automatic +exposure settings; returning to photo mode reapplies the saved photo controls. +New settings default to Auto / 1x / Night Burst Off. Existing settings files +remain compatible. + +Sensor writes are grouped and integration/gain are read back at sensor frame +boundaries before use. Context changes wait for final preview/capture entry +before reapplying the controls. Failures keep the previous selection, show a +stage/register code, and append expected/observed values to +`/photos/exposure-errors.log` before rollback. Exact +shutter times and actual sensor behavior still need validation on a physical DSi; +no diagnostic or probe app is included. Register definitions follow +[GBATEK's Aptina register research](https://mgba-emu.github.io/gbatek/#dsi-aptina-camera-registers-core-3000h-31ffh-38xxh). + +Host checks for frame alignment, noise reduction, motion rejection, and sensor +register/restore behavior, including live AE overwrite, delayed context entry, +and deferred/quantized gains (with mocked I2C): + +```sh +make -C tools/capture test +``` diff --git a/arm7/include/aptina.h b/arm7/include/aptina.h index b6b0d46..28d17c3 100644 --- a/arm7/include/aptina.h +++ b/arm7/include/aptina.h @@ -12,7 +12,10 @@ extern "C" { void init(u8 device); void activate(u8 device); void deactivate(u8 device); -void setMode(CaptureMode mode); +bool setRearLight(bool enabled); +bool setMode(CaptureMode mode); +bool setExposure(unsigned lines, unsigned gain); +unsigned exposureError(ExposureErrorField field); #ifdef __cplusplus } diff --git a/arm7/source/aptina.c b/arm7/source/aptina.c index 69dffbc..3ee2e40 100644 --- a/arm7/source/aptina.c +++ b/arm7/source/aptina.c @@ -3,6 +3,16 @@ #include "aptina_i2c.h" u8 currentDevice = I2C_CAM0; +static bool s_cameraActive; +static bool s_rearLight = true; + +bool setRearLight(bool enabled) { + u8 value = enabled && s_cameraActive && currentDevice == I2C_CAM1; + if(!i2cWriteRegister(I2C_PM, I2CREGPM_CAMLED, value) || (i2cReadRegister(I2C_PM, I2CREGPM_CAMLED) & 3) != value) + return false; + s_rearLight = enabled; + return true; +} // Waits until the bits of the register are clear void aptWaitClr(u8 device, u16 reg, u16 mask) { @@ -138,10 +148,9 @@ void activate(u8 device) { aptWriteRegister( device, 0x3012, 0x0010); // COARSE_INTEGRATION_TIME (Y Time) ; set to large number for more brightness aptSet(device, 0x001A, 0x0200); // RESET_AND_MISC_CONTROL (Parallel On) ;-Data on - if(device == I2C_CAM1) - i2cWriteRegister(0x4A, 0x31, 0x01); - - currentDevice = device; + currentDevice = device; + s_cameraActive = true; + setRearLight(s_rearLight); } void deactivate(u8 device) { @@ -149,13 +158,209 @@ void deactivate(u8 device) { aptSet(device, 0x0018, 0x0001); // STANDBY_CONTROL (set bit0=1=Standby) ;\. aptWaitSet(device, 0x0018, 0x4000); // STANDBY_CONTROL (wait for StandbyDone) ; Standby aptWaitClr(device, 0x301A, 0x0004); // UNDOC_CORE_301A (wait for StandbyDone) ;/ - if(device == I2C_CAM1) - i2cWriteRegister(0x4A, 0x31, 0x00); + s_cameraActive = false; + i2cWriteRegister(I2C_PM, I2CREGPM_CAMLED, 0); currentDevice = I2C_CAM0; } -void setMode(CaptureMode mode) { - aptWriteMcu(currentDevice, 0xA103, mode); - aptWaitMcuClr(currentDevice, 0xA103, 0xFFFF); +// Save each sensor's automation and calibrated core values independently. +static const u16 s_autoRegs[] = { + 0xA117, + 0xA11D, + 0xA123, + 0xA129, // AE in every preview/transition state + 0xA118, + 0xA11E, + 0xA124, + 0xA12A, // flicker detection + 0xA119, + 0xA11F, + 0xA125, + 0xA12B, // white balance + 0xA11A, + 0xA120, + 0xA126, + 0xA12C, // histogram gain + 0xA115, + 0xA102 // capture options, live driver enable mask +}; +#define AUTO_REG_COUNT (sizeof(s_autoRegs) / sizeof(s_autoRegs[0])) +static const u16 s_coreRegs[] = {0x3012, 0x3014, 0x302A, 0x302C, 0x302E, 0x3030}; +#define CORE_REG_COUNT (sizeof(s_coreRegs) / sizeof(s_coreRegs[0])) +static u16 s_autoValues[2][AUTO_REG_COUNT]; +static u16 s_coreValues[2][CORE_REG_COUNT]; +static bool s_manual[2], s_coreValid[2]; +static u16 s_exposureError[EXPOSURE_ERROR_FIELDS]; + +static bool exposureFail(u16 stage, u16 reg, u16 expected, u16 observed) { + if(!s_exposureError[EXPOSURE_ERROR_STAGE]) { + s_exposureError[EXPOSURE_ERROR_STAGE] = stage; + s_exposureError[EXPOSURE_ERROR_REGISTER] = reg; + s_exposureError[EXPOSURE_ERROR_EXPECTED] = expected; + s_exposureError[EXPOSURE_ERROR_OBSERVED] = observed; + } + return false; +} + +unsigned exposureError(ExposureErrorField field) { return field < EXPOSURE_ERROR_FIELDS ? s_exposureError[field] : 0; } + +static bool exposureReadMcu(u16 reg, u16 *value) { + if(!aptWriteRegister(currentDevice, 0x098C, reg)) + return exposureFail(1, reg, 0, 0xFFFF); + *value = aptReadRegister(currentDevice, 0x0990); + if(*value == 0xFFFF) + return exposureFail(1, reg, 0, *value); + return true; +} + +static bool exposureWriteMcu(u16 reg, u16 value) { + if(!aptWriteRegister(currentDevice, 0x098C, reg) || !aptWriteRegister(currentDevice, 0x0990, value)) + return exposureFail(2, reg, value, 0xFFFF); + u16 observed; + if(!exposureReadMcu(reg, &observed)) + return false; + return observed == value || exposureFail(3, reg, value, observed); +} + +bool setMode(CaptureMode mode) { + if(!aptWriteRegister(currentDevice, 0x098C, 0xA103) || !aptWriteRegister(currentDevice, 0x0990, mode)) + return exposureFail(2, 0xA103, mode, 0xFFFF); + u16 expected = mode == CAPTURE_MODE_PREVIEW ? 3 : 7; + u16 state = 0xFFFF; + for(int i = 0; i <= 180; i++) { + u16 command; + if(!exposureReadMcu(0xA103, &command) || !exposureReadMcu(0xA104, &state)) + return false; + // Command acceptance precedes context entry and its core-register reload. + if(command == 0 && state == expected) + return true; + if(i < 180) + swiWaitForVBlank(); + } + return exposureFail(4, 0xA104, expected, state); +} + +static bool exposureFreeze(int cam) { + // SEQ_MODE is the live enable mask. Changing state presets alone leaves + // the currently executing AE/AWB drivers free to overwrite manual values. + if(!exposureWriteMcu(0xA102, s_autoValues[cam][AUTO_REG_COUNT - 1] & ~0x0F)) + return false; + for(unsigned i = 0; i < AUTO_REG_COUNT - 1; i++) { + u16 value = s_autoRegs[i] == 0xA115 ? s_autoValues[cam][i] & ~0x70 : 0; + if(!exposureWriteMcu(s_autoRegs[i], value)) + return false; + } + return true; +} + +static bool exposureWriteCore(const u16 *values) { + u16 hold = aptReadRegister(currentDevice, 0x3022); + if(hold == 0xFFFF || (hold & 0x0100)) + return exposureFail(1, 0x3022, 0, hold); + bool written = aptWriteRegister(currentDevice, 0x3022, hold | 0x0100) && + aptReadRegister(currentDevice, 0x3022) == (hold | 0x0100); + if(!written) + exposureFail(2, 0x3022, hold | 0x0100, hold); + for(unsigned i = 0; written && i < CORE_REG_COUNT; i++) { + if(aptReadRegister(currentDevice, s_coreRegs[i]) == values[i]) + continue; + written = aptWriteRegister(currentDevice, s_coreRegs[i], values[i]) != 0; + if(!written) + exposureFail(2, s_coreRegs[i], values[i], 0xFFFF); + } + bool released = false; + for(int i = 0; i < 3 && !released; i++) + released = aptWriteRegister(currentDevice, 0x3022, hold) && aptReadRegister(currentDevice, 0x3022) == hold; + if(!released) + exposureFail(2, 0x3022, hold, aptReadRegister(currentDevice, 0x3022)); + if(!written || !released) + return false; + // Core writes can latch at the next sensor frame, not the next LCD VBlank. + for(int attempt = 0; attempt <= 180; attempt++) { + unsigned i; + u16 observed = 0; + for(i = 0; i < CORE_REG_COUNT; i++) { + observed = aptReadRegister(currentDevice, s_coreRegs[i]); + if(observed != values[i]) + break; + } + if(i == CORE_REG_COUNT) + return true; + if(attempt == 180) + return exposureFail(5, s_coreRegs[i], values[i], observed); + swiWaitForVBlank(); + } + return false; +} + +static bool exposureRestore(int cam) { + if(!s_manual[cam]) + return true; + if(s_coreValid[cam] && !exposureWriteCore(s_coreValues[cam])) + return false; + // Restore SEQ_MODE last, after the core and state presets are consistent. + for(unsigned i = 0; i < AUTO_REG_COUNT; i++) + if(!exposureWriteMcu(s_autoRegs[i], s_autoValues[cam][i])) + return false; + s_manual[cam] = s_coreValid[cam] = false; + return true; +} + +bool setExposure(unsigned lines, unsigned gain) { + for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) + s_exposureError[i] = 0; + if(lines > CAM_EXPOSURE_MAX_LINES || gain > 3) + return exposureFail(6, 0x3012, CAM_EXPOSURE_MAX_LINES, lines); + int cam = currentDevice == I2C_CAM0 ? 0 : 1; + if(!lines) + return exposureRestore(cam); + if(!s_manual[cam]) { + for(unsigned i = 0; i < AUTO_REG_COUNT; i++) + if(!exposureReadMcu(s_autoRegs[i], &s_autoValues[cam][i])) + return false; + s_manual[cam] = true; + } + if(!exposureFreeze(cam)) + return false; + if(!s_coreValid[cam]) { + // Finish any auto-function work already in flight before sampling color. + for(int i = 0; i < 12; i++) + swiWaitForVBlank(); + for(unsigned i = 0; i < CORE_REG_COUNT; i++) { + u16 value = aptReadRegister(currentDevice, s_coreRegs[i]); + if(value == 0xFFFF || (i >= 2 && (value < 8 || value > 127))) + return exposureFail(1, s_coreRegs[i], i >= 2 ? 8 : 0, value); + s_coreValues[cam][i] = value; + } + s_coreValid[cam] = true; + } + u16 values[CORE_REG_COUNT]; + values[0] = lines; + values[1] = 0x006B; + // Preserve the sensor's calibrated color ratios. Writing GLOBAL_GAIN while + // AWB runs both destroys those ratios and makes gain readback unstable. + unsigned green = s_coreValues[cam][2]; + unsigned factor = ((8u << gain) * 256 + green / 2) / green; + unsigned minimum = 0, maximum = 0xFFFF; + for(unsigned i = 2; i < CORE_REG_COUNT; i++) { + unsigned base = s_coreValues[cam][i]; + unsigned low = (8 * 256 + base - 1) / base, high = 127 * 256 / base; + if(low > minimum) + minimum = low; + if(high < maximum) + maximum = high; + } + if(factor < minimum) + factor = minimum; + if(factor > maximum) + factor = maximum; + for(unsigned i = 2; i < CORE_REG_COUNT; i++) { + unsigned value = (s_coreValues[cam][i] * factor + 128) / 256; + // The DSi rounds odd analog codes down even at low gain (13 -> 12). + // Higher ranges have a four-code step. Verify the achievable value. + value &= value >= 64 ? ~3u : ~1u; + values[i] = value; + } + return exposureWriteCore(values); } diff --git a/arm7/source/aptina_i2c.c b/arm7/source/aptina_i2c.c index 0aaf787..8b713bd 100644 --- a/arm7/source/aptina_i2c.c +++ b/arm7/source/aptina_i2c.c @@ -67,32 +67,41 @@ u8 aptSelectRegister(u8 reg, u8 flags) { u8 aptWriteRegister(u8 device, u16 reg, u16 data) { int i; + u8 result = 0; + i2cLock(); for(i = 0; i < 8; i++) { if(aptSelectDevice(device, I2C_START) && aptSelectRegister(reg >> 8, I2C_NONE) && aptSelectRegister(reg & 0xFF, I2C_NONE)) { - if(aptSetData(data >> 8, I2C_NONE) && aptSetData(data & 0xFF, I2C_STOP)) - return 1; + if(aptSetData(data >> 8, I2C_NONE) && aptSetData(data & 0xFF, I2C_STOP)) { + result = 1; + break; + } } REG_I2CCNT = 0xC5; } - return 0; + i2cUnlock(); + return result; } u16 aptReadRegister(u8 device, u16 reg) { int i; + u16 result = 0xFFFF; + i2cLock(); for(i = 0; i < 8; i++) { if(aptSelectDevice(device, I2C_START) && aptSelectRegister(reg >> 8, I2C_NONE) && aptSelectRegister(reg & 0xFF, I2C_STOP)) { if(aptSelectDevice(device | 1, I2C_START)) { - return (aptGetData(I2C_READ | I2C_ACK) << 8) | aptGetData(I2C_STOP | I2C_READ); + result = (aptGetData(I2C_READ | I2C_ACK) << 8) | aptGetData(I2C_STOP | I2C_READ); + break; } } REG_I2CCNT = 0xC5; } - return 0xFFFF; + i2cUnlock(); + return result; } diff --git a/arm7/source/i2c_handler.c b/arm7/source/i2c_handler.c index 5a59851..de287dd 100644 --- a/arm7/source/i2c_handler.c +++ b/arm7/source/i2c_handler.c @@ -3,10 +3,9 @@ #include "aptina.h" #include "aptina_i2c.h" -#include - #include #include +#include // Management structure and stack space for PXI server thread Thread s_i2cPxiThread; @@ -28,10 +27,9 @@ static void micexStart(void) { REG_MICEX_CNT = MICEX_CNT_NO_R | MICEX_CNT_RATE_DIV(1) | MICEX_CNT_ENABLE; // div1 = 16364Hz } -#define MIC_NDMA_CFG \ - (NDMA_DST_MODE(NdmaMode_Increment) | NDMA_SRC_MODE(NdmaMode_Fixed) | NDMA_BLK_WORDS(8) | \ - NDMA_TIMING(NdmaTiming_MicData) | NDMA_TX_MODE(NdmaTxMode_Timing) | NDMA_IRQ_ENABLE | \ - NDMA_START) +#define MIC_NDMA_CFG \ + (NDMA_DST_MODE(NdmaMode_Increment) | NDMA_SRC_MODE(NdmaMode_Fixed) | NDMA_BLK_WORDS(8) | \ + NDMA_TIMING(NdmaTiming_MicData) | NDMA_TX_MODE(NdmaTxMode_Timing) | NDMA_IRQ_ENABLE | NDMA_START) // Fully (re)initializes NDMA channel ch to capture one mic buffer into `slot`. // A wedged channel can't be revived with just |= NDMA_START, so always rebuild @@ -91,8 +89,8 @@ static void micWatchdogTick(TickTask *t) { } static void micStart(void) { - s_micDone = (vu32 *)s_micAddr; - *s_micDone = 0; + s_micDone = (vu32 *)s_micAddr; + *s_micDone = 0; for(int i = 1; i < 6; i++) ((vu32 *)s_micAddr)[i] = 0; // reset debug telemetry s_micActive = true; @@ -128,6 +126,11 @@ int i2cPxiThreadMain(void *arg) { // Receive a message u32 msg = mailboxRecv(&mb); u32 retval = 0; + if(msg & CAM_EXPOSURE_REQUEST) { + retval = setExposure(msg & CAM_EXPOSURE_LINES_MASK, (msg >> CAM_EXPOSURE_GAIN_SHIFT) & 3); + pxiReply(PxiChannel_User0, retval); + continue; + } switch(msg) { case CAM_INIT: @@ -152,12 +155,16 @@ int i2cPxiThreadMain(void *arg) { retval = CAM1_DEACTIVATE; break; case CAM_SET_MODE_PREVIEW: - setMode(CAPTURE_MODE_PREVIEW); - retval = CAPTURE_MODE_PREVIEW; + retval = setMode(CAPTURE_MODE_PREVIEW) ? CAPTURE_MODE_PREVIEW : 0; break; case CAM_SET_MODE_CAPTURE: - setMode(CAPTURE_MODE_CAPTURE); - retval = CAPTURE_MODE_CAPTURE; + retval = setMode(CAPTURE_MODE_CAPTURE) ? CAPTURE_MODE_CAPTURE : 0; + break; + case CAM_GET_EXPOSURE_ERROR_STAGE: + case CAM_GET_EXPOSURE_ERROR_REGISTER: + case CAM_GET_EXPOSURE_ERROR_EXPECTED: + case CAM_GET_EXPOSURE_ERROR_OBSERVED: + retval = exposureError(msg - CAM_GET_EXPOSURE_ERROR_STAGE); break; case CAM_GET_KEY0: case CAM_GET_KEY1: @@ -186,6 +193,10 @@ int i2cPxiThreadMain(void *arg) { micStop(); retval = CAM_MIC_STOP; break; + case CAM_REAR_LIGHT_OFF: + case CAM_REAR_LIGHT_ON: + retval = setRearLight(msg == CAM_REAR_LIGHT_ON); + break; case CAM_LED_OFF: case CAM_LED_ON: case CAM_LED_BLINK: diff --git a/arm9/include/camera.h b/arm9/include/camera.h index cb1b23e..528f2c6 100644 --- a/arm9/include/camera.h +++ b/arm9/include/camera.h @@ -34,11 +34,19 @@ bool cameraActivate(Camera cam); // Deactivates a camera bool cameraDeactivate(Camera cam); +// Rear camera indicator light; stays off while the inner camera is active. +bool cameraSetRearLight(bool enabled); + // Grabs a single frame into dst (RAM or VRAM) and leaves the camera stopped. // The camera interface is (re)configured per call, so this is cheap only for // snapshots. Returns false if the transfer did not finish (camera stalled). bool cameraCapture(u16 *dst, CaptureMode mode); +// Real sensor integration in rows (0 = auto), analogue gain 1x/2x/4x/8x. +// Applied again after mode changes; false means register verification failed. +bool cameraSetExposure(unsigned lines, unsigned gain); +unsigned cameraExposureError(ExposureErrorField field); + // Continuous preview capture: the camera interface is started once and NDMA1 // is re-armed from its completion IRQ into one of three internal frame buffers, // so the sensor never has to be stopped/flushed between frames. Only preview diff --git a/arm9/include/night.h b/arm9/include/night.h new file mode 100644 index 0000000..72c20b5 --- /dev/null +++ b/arm9/include/night.h @@ -0,0 +1,20 @@ +#ifndef NIGHT_H +#define NIGHT_H + +#include +#include + +#define NIGHT_WIDTH 640 +#define NIGHT_HEIGHT 480 +#define NIGHT_BYTES (NIGHT_WIDTH * NIGHT_HEIGHT * 2) +#define NIGHT_FRAMES 4 + +typedef struct NightStack NightStack; + +// The reference stays owned by the caller and unchanged until finish. +NightStack *nightCreate(const uint8_t *reference); +bool nightAdd(NightStack *stack, const uint8_t *frame); +void nightFinish(NightStack *stack, uint8_t *out); +void nightFree(NightStack *stack); + +#endif diff --git a/arm9/source/camera.c b/arm9/source/camera.c index bd04c32..e07eb4d 100644 --- a/arm9/source/camera.c +++ b/arm9/source/camera.c @@ -33,6 +33,10 @@ CaptureMode activeMode = CAPTURE_MODE_PREVIEW; alignas(32) static u16 s_frames[CAM_FRAMES][256 * 192]; static bool s_streaming; +static unsigned s_exposureLines; +static unsigned s_exposureGain; +static u16 s_exposureError[EXPOSURE_ERROR_FIELDS]; +static bool s_exposureDirty = true; static bool s_modeValid; // sensor is known to be in activeMode static volatile u32 s_frameCount; // frames completed since stream start static volatile u8 s_fill; // buffer the camera is writing right now @@ -102,14 +106,19 @@ bool cameraActivate(Camera cam) { u32 command = (cam == CAM_INNER) ? CAM0_ACTIVATE : CAM1_ACTIVATE; if(pxiSendAndReceive(PXI_CAMERA, command) == command) { - activeCamera = cam; - s_modeValid = false; // waking a camera is the safe place to resend the mode + activeCamera = cam; + s_exposureDirty = true; + s_modeValid = false; // waking a camera is the safe place to resend the mode return true; } else { return false; } } +bool cameraSetRearLight(bool enabled) { + return pxiSendAndReceive(PXI_CAMERA, enabled ? CAM_REAR_LIGHT_ON : CAM_REAR_LIGHT_OFF) == 1; +} + bool cameraDeactivate(Camera cam) { cameraStreamStop(); @@ -139,15 +148,22 @@ static bool camWaitDone(u32 vblanks) { // Sets up the sensor mode and the CAM_CNT format bits, then starts the camera // interface. Only called when the interface is not streaming. -static void camConfigure(CaptureMode mode) { +static bool camConfigure(CaptureMode mode) { bool preview = mode == CAPTURE_MODE_PREVIEW; if(mode != activeMode || !s_modeValid) { - pxiSendAndReceive(PXI_CAMERA, preview ? CAM_SET_MODE_PREVIEW : CAM_SET_MODE_CAPTURE); - activeMode = mode; - s_modeValid = true; + if(pxiSendAndReceive(PXI_CAMERA, preview ? CAM_SET_MODE_PREVIEW : CAM_SET_MODE_CAPTURE) != mode) + return false; + activeMode = mode; + s_modeValid = true; + s_exposureDirty = true; } + if(s_exposureDirty) { + if(!cameraSetExposure(s_exposureLines, s_exposureGain)) + return false; + s_exposureDirty = false; + } REG_CAM_CNT &= ~BIT(15); // allow changing params if(preview) // YUV-to-RGB555 and "scanline count - 1" = 3 REG_CAM_CNT |= 0x2003; @@ -155,11 +171,43 @@ static void camConfigure(CaptureMode mode) { REG_CAM_CNT &= ~0x2003; REG_CAM_CNT |= BIT(5); // clear overrun flag, flush till next camera vblank REG_CAM_CNT |= BIT(15); + return true; +} + +bool cameraSetExposure(unsigned lines, unsigned gain) { + if(lines > CAM_EXPOSURE_MAX_LINES || gain > 3 || activeCamera == CAM_NONE) + return false; + bool streaming = cameraStreamRunning(); + if(streaming) + cameraStreamStop(); + bool ok = pxiSendAndReceive(PXI_CAMERA, CAM_EXPOSURE_REQUEST | lines | (gain << CAM_EXPOSURE_GAIN_SHIFT)) == 1; + if(ok) { + s_exposureLines = lines; + s_exposureGain = gain; + s_exposureDirty = false; + } + bool restored = ok; + if(!ok) { + for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) + s_exposureError[i] = pxiSendAndReceive(PXI_CAMERA, CAM_GET_EXPOSURE_ERROR_STAGE + i); + restored = + pxiSendAndReceive( + PXI_CAMERA, CAM_EXPOSURE_REQUEST | s_exposureLines | (s_exposureGain << CAM_EXPOSURE_GAIN_SHIFT)) == 1; + s_exposureDirty = !restored; + } + if(streaming && restored) + cameraStreamStart(); + return ok; +} + +unsigned cameraExposureError(ExposureErrorField field) { + return field < EXPOSURE_ERROR_FIELDS ? s_exposureError[field] : 0; } bool cameraCapture(u16 *dst, CaptureMode mode) { cameraStreamStop(); - camConfigure(mode); + if(!camConfigure(mode)) + return false; u32 bytes = mode == CAPTURE_MODE_PREVIEW ? CAM_PREVIEW_SIZE : (640 * 480 * 2); @@ -187,7 +235,8 @@ bool cameraStreamStart(void) { cameraStreamStop(); - camConfigure(CAPTURE_MODE_PREVIEW); + if(!camConfigure(CAPTURE_MODE_PREVIEW)) + return false; // Drop any dirty lines the CPU may still hold for the capture buffers: the // DMA bypasses the cache and a stray writeback would corrupt a frame. diff --git a/arm9/source/main.c b/arm9/source/main.c index ff99f22..abc1be0 100644 --- a/arm9/source/main.c +++ b/arm9/source/main.c @@ -1,4 +1,5 @@ #include "camera.h" +#include "night.h" #include "version.h" #include @@ -39,12 +40,19 @@ int clamp(int val, int min, int max) { return val < min ? min : (val > max ? max static u16 *s_subGfx; // bottom-screen bitmap, drawn by the ui* helpers static Camera s_camera; // currently active camera static bool s_videoMode; // camera screen: photo vs video mode +static const unsigned s_shutterLines[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 640}; +#define SHUTTER_COUNT (sizeof(s_shutterLines) / sizeof(s_shutterLines[0])) +static unsigned s_shutter; +static unsigned s_gain; +static bool s_nightBurst; +static bool s_rearLight = true; static bool s_timestamp; // burn the capture time into saved pixels static char s_savedMsg[48]; // last "saved video" summary, kept after the redraw static void uiStatus(const char *s); void uiSpace(void); static void watermarkYuv(u16 *yuv, time_t t); static void watermarkFrame(u16 *gfx, time_t t); +static void drainJobs(void); // The viewfinder is a continuous camera stream now. camera.c owns the state; // these wrappers just avoid restarting a stream that is already running. @@ -60,8 +68,16 @@ static void streamStop(void) { cameraStreamStop(); } static void lidSleep(void) { bool wasStreaming = cameraStreamRunning(); streamStop(); + drainJobs(); + if(pmShouldReset()) + return; cameraDeactivate(s_camera); - pmEnterSleep(); + // Saving and sensor standby can take long enough for the lid to reopen. + scanKeys(); + if((keysHeld() & KEY_LID) && !pmShouldReset()) + pmEnterSleep(); + if(pmShouldReset()) + return; cameraActivate(s_camera); if(wasStreaming) streamStart(); @@ -138,6 +154,7 @@ static void yuvToRgb(const u16 *yuv, u8 *rgb) { static void rawPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.YUV", num); } static void thumbPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.THM", num); } +static void metadataPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.TXT", num); } static void vidPath(char *out, int num) { sprintf(out, RAW_DIR "/VID_%04d.VID", num); } static void vidThumbPath(char *out, int num) { sprintf(out, RAW_DIR "/VID_%04d.THM", num); } @@ -150,9 +167,18 @@ static void cfgLoad(void) { if(!f) return; char line[64]; - while(fgets(line, sizeof(line), f)) + while(fgets(line, sizeof(line), f)) { if(strncmp(line, "timestamp=", 10) == 0) s_timestamp = atoi(line + 10) != 0; + else if(strncmp(line, "shutter=", 8) == 0) + s_shutter = (unsigned)clamp(atoi(line + 8), 0, SHUTTER_COUNT - 1); + else if(strncmp(line, "gain=", 5) == 0) + s_gain = (unsigned)clamp(atoi(line + 5), 0, 3); + else if(strncmp(line, "night_burst=", 12) == 0) + s_nightBurst = atoi(line + 12) != 0; + else if(strncmp(line, "rear_light=", 11) == 0) + s_rearLight = atoi(line + 11) != 0; + } fclose(f); } @@ -160,7 +186,8 @@ static void cfgSave(void) { FILE *f = fopen(CFG_PATH, "w"); if(!f) return; - fprintf(f, "timestamp=%d\n", s_timestamp ? 1 : 0); + fprintf(f, "timestamp=%d\nshutter=%u\ngain=%u\nnight_burst=%d\nrear_light=%d\n", + s_timestamp ? 1 : 0, s_shutter, s_gain, s_nightBurst ? 1 : 0, s_rearLight ? 1 : 0); fclose(f); } @@ -249,14 +276,47 @@ static int dayKey(time_t t) { #define JOB_PHOTO 0 // (JOB_ values 1 and 2 are CHUNK_VIDEO / CHUNK_AUDIO) +typedef struct PhotoMetadata { + time_t captured; + Camera camera; + unsigned lines, gain; + bool night, rearLight, watermark; +} PhotoMetadata; + typedef struct Job { u32 type; // JOB_PHOTO / CHUNK_VIDEO / CHUNK_AUDIO u32 aux; // photo num / chunk index (frame or audio block number) u32 slot; // ring/pool slot to return after writing (video/audio) u32 size; // payload bytes (video/audio) u16 *buf; + PhotoMetadata photo; } Job; +static bool savePhotoMetadata(int num, const PhotoMetadata *photo) { + char path[40], shutter[20], gain[12]; + metadataPath(path, num); + FILE *f = fopen(path, "w"); + if(!f) + return false; + if(photo->lines) { + snprintf(shutter, sizeof(shutter), "%u lines", photo->lines); + snprintf(gain, sizeof(gain), "%ux", photo->gain); + } else { + strcpy(shutter, "auto"); + strcpy(gain, "auto"); + } + bool saved = fprintf(f, + "captured_unix=%ld\ncamera=%s\nshutter=%s\ngain_nominal=%s\n" + "night_burst=%d\nframes=%d\nrear_light_during_capture=%d\ntimestamp=%d\n", + (long)photo->captured, photo->camera == CAM_OUTER ? "outer" : "inner", shutter, gain, + photo->night, photo->night ? NIGHT_FRAMES : 1, photo->rearLight, photo->watermark) >= 0; + if(fclose(f) != 0) + saved = false; + if(!saved) + remove(path); + return saved; +} + #define JOB_QUEUE_LEN 32 static Thread s_workerThread; @@ -333,20 +393,24 @@ static int workerMain(void *arg) { rawPath(path, job->aux); FILE *f = fopen(path, "wb"); char msg[32]; + bool saved = false; if(f) { - fwrite(job->buf, 1, RAW_SIZE, f); - fclose(f); - sprintf(msg, "SAVED IMG_%04d", (int)job->aux); - } else { - sprintf(msg, "SAVE FAILED: IMG_%04d", (int)job->aux); + saved = fwrite(job->buf, 1, RAW_SIZE, f) == RAW_SIZE; + if(fclose(f) != 0) + saved = false; + if(!saved) + remove(path); } + bool metadataSaved = saved && savePhotoMetadata(job->aux, &job->photo); + snprintf(msg, sizeof(msg), !saved ? "SAVE FAILED: IMG_%04d" : + metadataSaved ? "SAVED IMG_%04d" : "SAVED IMG_%04d - NO METADATA", (int)job->aux); uiStatus(msg); // Thumbnail cache for the album grid. u16 thumb[THUMB_W * THUMB_H]; blitYuvScaled(job->buf, thumb, THUMB_W, THUMB_W, THUMB_H); thumbPath(path, job->aux); - f = fopen(path, "wb"); + f = saved ? fopen(path, "wb") : NULL; if(f) { fwrite(thumb, 1, sizeof(thumb), f); fclose(f); @@ -384,41 +448,80 @@ static void drainJobs(void) { swiWaitForVBlank(); } -// Captures one full-res frame and queues it for background saving. Blocks -// only for the capture DMA itself (or for a queue slot if the SD card is -// >JOB_QUEUE_LEN frames behind). `previewGfx` is the top-screen bitmap; the -// frame is drawn to it so the preview updates during a burst. +// Night source frames remain in RAM; only the completed photo is queued. static bool captureRaw(u16 *previewGfx) { u16 *yuv = NULL; Job *job = NULL; + if(s_nightBurst) + drainJobs(); for(;;) { - if(!yuv) // cache line aligned: the camera DMA writes around the cache + if(!yuv) yuv = (u16 *)memalign(32, RAW_SIZE); if(!job) job = (Job *)malloc(sizeof(Job)); if(yuv && job) break; - // Out of RAM: let the worker finish a frame and retry. + if(!JOBS_PENDING) { + free(yuv); + free(job); + uiStatus("NOT ENOUGH MEMORY"); + return false; + } swiWaitForVBlank(); } - // Bounded inside camera.c: a stalled camera fails the shot instead of - // hanging the app. - if(!cameraCapture(yuv, CAPTURE_MODE_CAPTURE)) { - free(yuv); - free(job); - return false; - } - - // The sensor's first scanline carries garbage/embedded data (shows up as - // green speckles); paper over it with the second line. + time_t shotTime = time(NULL); + job->photo = (PhotoMetadata){ + .captured = shotTime, + .camera = s_camera, + .lines = s_shutterLines[s_shutter], + .gain = s_shutter ? 1u << s_gain : 0, + .night = s_nightBurst, + .rearLight = s_camera == CAM_OUTER && s_rearLight && !s_nightBurst, + .watermark = s_timestamp, + }; + NightStack *stack = NULL; + u16 *next = NULL; + const char *error = "CAMERA FAILED - TRY AGAIN"; + if(s_nightBurst) + uiStatus("HOLD STILL 1/4 B: CANCEL"); + if(!cameraCapture(yuv, CAPTURE_MODE_CAPTURE)) + goto fail; memcpy(yuv, yuv + 640, 640 * sizeof(u16)); - // Stamped before the preview blit and the thumbnail, so what's shown - // matches what lands on the card. + if(s_nightBurst) { + next = (u16 *)memalign(32, RAW_SIZE); + stack = nightCreate((const u8 *)yuv); + if(!next || !stack) { + error = "NOT ENOUGH MEMORY"; + goto fail; + } + for(int i = 1; i < NIGHT_FRAMES; i++) { + scanKeys(); + if((keysDown() & KEY_B) || (keysHeld() & KEY_LID) || pmShouldReset()) { + error = "NIGHT BURST CANCELLED"; + goto fail; + } + char msg[40]; + sprintf(msg, "HOLD STILL %d/4 B: CANCEL", i + 1); + uiStatus(msg); + if(!cameraCapture(next, CAPTURE_MODE_CAPTURE)) + goto fail; + memcpy(next, next + 640, 640 * sizeof(u16)); + nightAdd(stack, (const u8 *)next); + } + scanKeys(); + if((keysDown() & KEY_B) || (keysHeld() & KEY_LID) || pmShouldReset()) { + error = "NIGHT BURST CANCELLED"; + goto fail; + } + uiStatus("PROCESSING..."); + nightFinish(stack, (u8 *)yuv); + nightFree(stack); + free(next); + } if(s_timestamp) - watermarkYuv(yuv, time(NULL)); - + watermarkYuv(yuv, shotTime); if(previewGfx) blitYuv(yuv, previewGfx); @@ -426,9 +529,37 @@ static bool captureRaw(u16 *previewGfx) { job->aux = s_nextRawNum++; job->buf = yuv; while(!mailboxTrySend(&s_jobMailbox, (u32)job)) - swiWaitForVBlank(); // queue full, wait for the worker + swiWaitForVBlank(); s_jobsQueued++; return true; + +fail: + nightFree(stack); + free(next); + free(yuv); + free(job); + uiStatus(error); + return false; +} + +static void takePhotos(u16 *gfx) { + streamStop(); + if(s_nightBurst && !cameraSetRearLight(false)) { + cameraSetRearLight(s_rearLight); + uiStatus("REAR LIGHT OFF FAILED - NO PHOTO"); + streamStart(); + return; + } + pxiSendAndReceive(PXI_CAMERA, CAM_LED_ON); + do { + if(!captureRaw(gfx)) + break; + scanKeys(); + } while(!s_nightBurst && (keysHeld() & (KEY_L | KEY_R)) && !(keysHeld() & KEY_LID) && !pmShouldReset()); + pxiSendAndReceive(PXI_CAMERA, CAM_LED_OFF); + if(s_nightBurst && !cameraSetRearLight(s_rearLight)) + uiStatus("REAR LIGHT RESTORE FAILED"); + streamStart(); } // --- Video playback: audio streams through a looping ring while frames are @@ -925,6 +1056,9 @@ static void softDelete(int num, bool isVideo) { thumbPath(from, num); sprintf(to, RAW_DIR "/trash/IMG_%04d.THM", num); rename(from, to); + metadataPath(from, num); + sprintf(to, RAW_DIR "/trash/IMG_%04d.TXT", num); + rename(from, to); } } @@ -1012,6 +1146,10 @@ static const u8 *glyph(char c) { if(c >= 'a' && c <= 'z') c -= 'a' - 'A'; switch(c) { + case '+': { + static const u8 plus[5] = {0x08, 0x08, 0x3E, 0x08, 0x08}; + return plus; + } case '?': return s_font[38]; case '.': @@ -1190,18 +1328,190 @@ static void uiCameraScreen(int cam, bool fatInited) { uiTextCenter(44, sub, UI_DIM); uiSpace(); - int y = 84; + int y = 78; if(fatInited) { - uiKey(y, "L/R", s_videoMode ? "RECORD" : "TAKE PHOTOS"); - uiKey(y += 16, "Y", s_videoMode ? "PHOTO MODE" : "VIDEO MODE"); - uiKey(y += 16, "A", "SWAP CAMERA"); - uiKey(y += 16, "SELECT", "ALBUM"); - uiKey(y += 16, "X", s_timestamp ? "TIMESTAMP: ON" : "TIMESTAMP: OFF"); + uiKey(y, "L/R", s_videoMode ? "RECORD" : s_nightBurst ? "NIGHT PHOTO" : "TAKE PHOTOS"); + uiKey(y += 14, "Y", s_videoMode ? "PHOTO MODE" : "VIDEO MODE"); + uiKey(y += 14, "A", "SWAP CAMERA"); + uiKey(y += 14, "X", "ADVANCED"); + uiKey(y += 14, "SELECT", "ALBUM"); } else { uiTextCenter(y, "NO SD CARD - CANT SAVE", UI_FG); - uiKey(y += 16, "A", "SWAP CAMERA"); + uiKey(y += 14, "A", "SWAP CAMERA"); + } + uiKey(y += 14, "START", "EXIT"); +} + +#define UI_ACCENT (BIT(15) | RGB15(31, 25, 5)) +#define UI_PANEL (BIT(15) | RGB15(6, 6, 7)) + +enum { ADV_SHUTTER, ADV_GAIN, ADV_NIGHT, ADV_REAR_LIGHT, ADV_TIMESTAMP, ADV_RESET, ADV_COUNT }; +#define ADV_ROW_Y 52 +#define ADV_ROW_H 17 + +static bool advancedRowEnabled(int row) { + if(row == ADV_SHUTTER || row == ADV_NIGHT) + return !s_videoMode; + if(row == ADV_GAIN) + return !s_videoMode && s_shutter; + if(row == ADV_REAR_LIGHT) + return s_camera == CAM_OUTER; + return true; +} + +static int advancedMoveSelection(int selected, int direction) { + do { + selected = (selected + direction + ADV_COUNT) % ADV_COUNT; + } while(!advancedRowEnabled(selected)); + return selected; +} + +static void uiAdvancedScreen(int selected) { + uiHeader("ADVANCED"); + uiTextCenter(43, s_videoMode ? "VIDEO - PHOTO CONTROLS LOCKED" : "PHOTO", UI_DIM); + const char *labels[] = {"SHUTTER", "GAIN", "NIGHT BURST", "REAR LIGHT", "TIMESTAMP", "RESET"}; + char shutter[16], gain[16]; + if(!s_videoMode && s_shutter) + sprintf(shutter, "%u LINE%s", s_shutterLines[s_shutter], s_shutterLines[s_shutter] == 1 ? "" : "S"); + else + strcpy(shutter, "AUTO"); + if(!s_videoMode && s_shutter) + sprintf(gain, "%uX", 1u << s_gain); + else + strcpy(gain, "AUTO"); + const char *values[] = {shutter, gain, !s_videoMode && s_nightBurst ? "ON" : "OFF", + s_camera == CAM_OUTER && s_rearLight ? "ON" : "OFF", s_timestamp ? "ON" : "OFF", ""}; + for(int i = 0; i < ADV_COUNT; i++) { + int y = ADV_ROW_Y + i * ADV_ROW_H; + bool enabled = advancedRowEnabled(i); + bool active = enabled && i == selected; + uiRect(12, y, 232, ADV_ROW_H, active ? UI_PANEL : UI_BG); + if(active) + uiRect(12, y + 3, 2, 11, UI_ACCENT); + uiText(22, y + 5, labels[i], !enabled ? UI_DIM : active ? UI_ACCENT : UI_FG); + uiText(222 - strlen(values[i]) * 6, y + 5, values[i], enabled ? UI_FG : UI_DIM); + if(enabled && i != ADV_RESET) { + uiText(138, y + 5, "<", UI_DIM); + uiText(234, y + 5, ">", UI_DIM); + } + } + uiTextCenter(159, "UP/DOWN SELECT < > ADJUST", UI_DIM); + uiTextCenter(171, s_videoMode ? "A: SET B/X: DONE" : "A: SET L/R: PHOTO B/X: DONE", UI_DIM); + const char *hints[] = {"A: AUTO - MANUAL UNLOCKS GAIN", "HIGHER GAIN ADDS NOISE", + "4 FRAMES - REAR LIGHT OFF", "OFF WHILE NIGHT BURST SHOOTS", + "BURN DATE AND TIME INTO IMAGE", "A: RESET ALL SETTINGS"}; + uiStatus(hints[selected]); +} + +static void uiExposureFailure(unsigned lines, unsigned gain) { + unsigned stage = cameraExposureError(EXPOSURE_ERROR_STAGE); + unsigned reg = cameraExposureError(EXPOSURE_ERROR_REGISTER); + char message[40]; + snprintf(message, sizeof(message), "SENSOR E%u R%04X - TRY AUTO", stage, reg); + uiStatus(message); + FILE *f = fopen(RAW_DIR "/exposure-errors.log", "a"); + if(!f) + return; + fprintf(f, "time=%ld camera=%d lines=%u gain=%u stage=%u reg=%04X expected=%04X observed=%04X\n", + (long)time(NULL), s_camera, lines, gain, stage, reg, + cameraExposureError(EXPOSURE_ERROR_EXPECTED), cameraExposureError(EXPOSURE_ERROR_OBSERVED)); + fclose(f); +} + +static void advancedMenu(u16 *gfx) { + int selected = s_videoMode ? ADV_TIMESTAMP : ADV_SHUTTER; + keysSetRepeat(18, 6); + uiAdvancedScreen(selected); + while(!pmShouldReset()) { + swiWaitForVBlank(); + scanKeys(); + if(keysHeld() & KEY_LID) { + lidSleep(); + continue; + } + u16 *frame = cameraNextFrame(); + if(frame) + memcpy(gfx, frame, VID_FRAME_SIZE); + u16 pressed = keysDownRepeat(); + bool tappedAction = false; + if(keysDown() & KEY_TOUCH) { + touchPosition touch; + touchRead(&touch); + if(touch.py >= ADV_ROW_Y && touch.py < ADV_ROW_Y + ADV_COUNT * ADV_ROW_H) { + int row = (touch.py - ADV_ROW_Y) / ADV_ROW_H; + if(!advancedRowEnabled(row)) + continue; + selected = row; + if(touch.px >= 128) { + if(selected == ADV_RESET) + tappedAction = true; + else + pressed |= touch.px < 180 ? KEY_LEFT : KEY_RIGHT; + } + } + } + if(keysDown() & (KEY_B | KEY_X | KEY_START)) + break; + if(!s_videoMode && (keysDown() & (KEY_L | KEY_R))) { + takePhotos(gfx); + continue; + } + if(!pressed) + continue; + unsigned oldShutter = s_shutter, oldGain = s_gain; + bool oldNight = s_nightBurst, oldTimestamp = s_timestamp, oldRearLight = s_rearLight; + if(pressed & KEY_UP) + selected = advancedMoveSelection(selected, -1); + else if(pressed & KEY_DOWN) + selected = advancedMoveSelection(selected, 1); + int direction = (pressed & KEY_LEFT) ? -1 : (pressed & KEY_RIGHT) ? 1 : 0; + bool action = tappedAction || (keysDown() & KEY_A); + if(selected == ADV_SHUTTER) { + if(direction) + s_shutter = clamp((int)s_shutter + direction, 0, SHUTTER_COUNT - 1); + if(action) + s_shutter = 0; + } else if(selected == ADV_GAIN) { + if(action) + s_gain = (s_gain + 1) % 4; + else if(direction) + s_gain = clamp((int)s_gain + direction, 0, 3); + } else if(selected == ADV_NIGHT && (action || direction)) { + s_nightBurst = direction ? direction > 0 : !s_nightBurst; + } else if(selected == ADV_TIMESTAMP && (action || direction)) { + s_timestamp = direction ? direction > 0 : !s_timestamp; + } else if(selected == ADV_REAR_LIGHT && (action || direction)) { + s_rearLight = direction ? direction > 0 : !s_rearLight; + } else if(selected == ADV_RESET && action) { + s_shutter = s_gain = 0; + s_nightBurst = false; + s_timestamp = false; + s_rearLight = true; + } + bool changed = !s_videoMode && (oldShutter != s_shutter || oldGain != s_gain); + unsigned attemptedLines = s_shutterLines[s_shutter], attemptedGain = s_gain; + if(changed) + uiStatus("APPLYING SENSOR SETTINGS..."); + bool ok = !changed || cameraSetExposure(attemptedLines, attemptedGain); + if(!ok) { + s_shutter = oldShutter; + s_gain = oldGain; + s_nightBurst = oldNight; + s_timestamp = oldTimestamp; + s_rearLight = oldRearLight; + } + bool lightOk = oldRearLight == s_rearLight || cameraSetRearLight(s_rearLight); + if(!lightOk) { + s_rearLight = oldRearLight; + cameraSetRearLight(s_rearLight); + } + uiAdvancedScreen(selected); + if(!ok) + uiExposureFailure(attemptedLines, attemptedGain); + else if(!lightOk) + uiStatus("REAR LIGHT SETTING FAILED"); } - uiKey(y += 16, "START", "EXIT"); + cfgSave(); } // Centered modal question; waits for A (true) / B (false). @@ -1701,6 +2011,7 @@ int main(int argc, char **argv) { uiStatus("INITIALIZING..."); pxiWaitRemote(PXI_CAMERA); // Wait for ARM7 to initialize PXI cameraInit(); + bool lightReady = cameraSetRearLight(s_rearLight); soundInit(); // ARM9 interface to the ARM7 sound driver (video playback) soundPowerOn(); soundSetMixerConfig(SoundOutSrc_Mixer, SoundOutSrc_Mixer, false, false); @@ -1722,9 +2033,15 @@ int main(int argc, char **argv) { Camera camera = CAM_OUTER; s_camera = camera; cameraActivate(camera); + if(!cameraSetExposure(s_shutterLines[s_shutter], s_gain)) { + s_shutter = s_gain = 0; + cameraSetExposure(0, 0); + } streamStart(); // continuous viewfinder uiCameraScreen(camera, fatInited); + if(!lightReady) + uiStatus("REAR LIGHT SETTING FAILED"); while(1) { u16 pressed = 0; @@ -1740,7 +2057,6 @@ int main(int argc, char **argv) { scanKeys(); // Lid closed: shut the camera off and sleep until it reopens. if(keysHeld() & KEY_LID) { - drainJobs(); // don't sleep with writes half-finished lidSleep(); continue; } @@ -1760,13 +2076,17 @@ int main(int argc, char **argv) { uiCameraScreen(camera, fatInited); } else if(fatInited && pressed & KEY_Y) { - s_videoMode = !s_videoMode; + bool video = !s_videoMode; + if(!cameraSetExposure(video ? 0 : s_shutterLines[s_shutter], s_gain)) { + uiExposureFailure(video ? 0 : s_shutterLines[s_shutter], s_gain); + continue; + } + s_videoMode = video; uiCameraScreen(camera, fatInited); } else if(fatInited && pressed & KEY_X) { - s_timestamp = !s_timestamp; - cfgSave(); + drainJobs(); + advancedMenu(gfx); uiCameraScreen(camera, fatInited); - uiStatus(s_timestamp ? "TIMESTAMP ON" : "TIMESTAMP OFF"); } else if(fatInited && pressed & (KEY_L | KEY_R)) { if(s_videoMode) { // Tap L/R to record, tap again to stop. @@ -1778,17 +2098,7 @@ int main(int argc, char **argv) { if(s_savedMsg[0]) uiStatus(s_savedMsg); // survives the redraw above } else { - // Hold L/R to keep taking photos continuously. Camera LED - // lights while shooting, like a shutter indicator. - streamStop(); // photos reconfigure the sensor for 640x480 - pxiSendAndReceive(PXI_CAMERA, CAM_LED_ON); - do { - captureRaw(gfx); - scanKeys(); - // Don't keep shooting into a closed lid (e.g. in a pocket). - } while((keysHeld() & (KEY_L | KEY_R)) && !(keysHeld() & KEY_LID)); - pxiSendAndReceive(PXI_CAMERA, CAM_LED_OFF); - streamStart(); + takePhotos(gfx); uiSpace(); // refresh the free-space line after the burst } } else if(fatInited && pressed & KEY_SELECT) { diff --git a/arm9/source/night.c b/arm9/source/night.c new file mode 100644 index 0000000..f6689e3 --- /dev/null +++ b/arm9/source/night.c @@ -0,0 +1,102 @@ +#include "night.h" + +#include +#include + +struct NightStack { + const uint8_t *reference; + uint16_t *sum; + uint8_t *count; + unsigned frames; +}; + +NightStack *nightCreate(const uint8_t *reference) { + NightStack *s = calloc(1, sizeof(*s)); + if(!s) + return NULL; + s->sum = malloc(NIGHT_BYTES * sizeof(*s->sum)); + s->count = malloc(NIGHT_WIDTH * NIGHT_HEIGHT / 2); + if(!s->sum || !s->count) { + nightFree(s); + return NULL; + } + s->reference = reference; + s->frames = 1; + for(int i = 0; i < NIGHT_BYTES; i++) + s->sum[i] = reference[i]; + memset(s->count, 1, NIGHT_WIDTH * NIGHT_HEIGHT / 2); + return s; +} + +// Sparse luma alignment. Even horizontal shifts preserve YUV422 chroma pairs. +// Prefer zero shift on a tie so a flat dark sky doesn't drift arbitrarily. +static unsigned alignmentError(const uint8_t *a, const uint8_t *b, int dx, int dy) { + unsigned error = 0; + for(int y = 16; y < NIGHT_HEIGHT - 16; y += 8) { + for(int x = 16; x < NIGHT_WIDTH - 16; x += 8) { + int p = (y * NIGHT_WIDTH + x) * 2; + int q = ((y + dy) * NIGHT_WIDTH + x + dx) * 2; + error += abs(a[p] - b[q]); + } + } + return error; +} + +bool nightAdd(NightStack *s, const uint8_t *frame) { + if(s->frames >= NIGHT_FRAMES) + return false; + int dx = 0, dy = 0; + unsigned best = alignmentError(s->reference, frame, 0, 0); + for(int y = -8; y <= 8; y++) { + for(int x = -8; x <= 8; x += 2) { + unsigned error = alignmentError(s->reference, frame, x, y); + if(error < best) { + best = error; + dx = x; + dy = y; + } + } + } + // A changed scene or a large exposure jump should keep the reference. + if(best > 28u * 56 * 76) + return false; + s->frames++; + for(int y = 0; y < NIGHT_HEIGHT; y++) { + int sy = y + dy; + if(sy < 0 || sy >= NIGHT_HEIGHT) + continue; + for(int x = 0; x < NIGHT_WIDTH; x += 2) { + int sx = x + dx; + if(sx < 0 || sx >= NIGHT_WIDTH - 1) + continue; + int p = (y * NIGHT_WIDTH + x) * 2; + int q = (sy * NIGHT_WIDTH + sx) * 2; + const uint8_t *ref = s->reference + p; + const uint8_t *src = frame + q; + // Reject moving subjects locally instead of leaving ghost trails. + if(abs(ref[0] - src[0]) > 24 || abs(ref[2] - src[2]) > 24 || abs(ref[1] - src[1]) > 32 || + abs(ref[3] - src[3]) > 32) + continue; + for(int c = 0; c < 4; c++) + s->sum[p + c] += src[c]; + s->count[p / 4]++; + } + } + return true; +} + +void nightFinish(NightStack *s, uint8_t *out) { + for(int p = 0; p < NIGHT_BYTES; p += 4) { + unsigned n = s->count[p / 4]; + for(int c = 0; c < 4; c++) + out[p + c] = (s->sum[p + c] + n / 2) / n; + } +} + +void nightFree(NightStack *s) { + if(!s) + return; + free(s->sum); + free(s->count); + free(s); +} diff --git a/shared/include/pxi_vars.h b/shared/include/pxi_vars.h index f4eab66..0aed59c 100644 --- a/shared/include/pxi_vars.h +++ b/shared/include/pxi_vars.h @@ -37,9 +37,30 @@ typedef enum { // Power LED (BPTWL reg 0x63): OFF = blue, ON/BLINK = red (shutter/REC cue). CAM_LED_OFF, CAM_LED_ON, - CAM_LED_BLINK + CAM_LED_BLINK, + CAM_GET_EXPOSURE_ERROR_STAGE, + CAM_GET_EXPOSURE_ERROR_REGISTER, + CAM_GET_EXPOSURE_ERROR_EXPECTED, + CAM_GET_EXPOSURE_ERROR_OBSERVED, + CAM_REAR_LIGHT_OFF, + CAM_REAR_LIGHT_ON } PxiCommand; +// Packed exposure request fits PXI's 26-bit immediate; halfword mic addresses +// cannot be mistaken for one. Zero lines restores the sensor's auto exposure. +#define CAM_EXPOSURE_REQUEST (1u << 24) +#define CAM_EXPOSURE_LINES_MASK 0x3FFu +#define CAM_EXPOSURE_GAIN_SHIFT 10 +#define CAM_EXPOSURE_MAX_LINES 640 + +typedef enum { + EXPOSURE_ERROR_STAGE, + EXPOSURE_ERROR_REGISTER, + EXPOSURE_ERROR_EXPECTED, + EXPOSURE_ERROR_OBSERVED, + EXPOSURE_ERROR_FIELDS +} ExposureErrorField; + // Mic ring layout: u32 completion counter at the base, then MIC_RING_BUFS // buffers of MIC_BUF_BYTES each (base + 32). #define MIC_RING_BUFS 4 diff --git a/tools/capture/Makefile b/tools/capture/Makefile new file mode 100644 index 0000000..5c3aec9 --- /dev/null +++ b/tools/capture/Makefile @@ -0,0 +1,13 @@ +CC = clang +CFLAGS = -std=c11 -Wall -Wextra -Werror -fsanitize=address,undefined +ROOT = ../.. + +.PHONY: test + +test: + $(CC) $(CFLAGS) -I$(ROOT)/arm9/include $(ROOT)/arm9/source/night.c night_test.c -o /tmp/dsi-camera-night-test + /tmp/dsi-camera-night-test + $(CC) $(CFLAGS) -Wno-unused-parameter -Ishim -I$(ROOT)/arm7/include -I$(ROOT)/shared/include $(ROOT)/arm7/source/aptina.c exposure_test.c -o /tmp/dsi-camera-exposure-test + /tmp/dsi-camera-exposure-test + $(CC) $(CFLAGS) -Wno-unused-parameter -Ishim -I$(ROOT)/arm7/include -I$(ROOT)/shared/include $(ROOT)/arm7/source/aptina.c rear_light_test.c -o /tmp/dsi-camera-rear-light-test + /tmp/dsi-camera-rear-light-test diff --git a/tools/capture/exposure_test.c b/tools/capture/exposure_test.c new file mode 100644 index 0000000..9d50dd2 --- /dev/null +++ b/tools/capture/exposure_test.c @@ -0,0 +1,237 @@ +#include "aptina.h" +#include "aptina_i2c.h" + +#include +#include +#include +#include + +extern u8 currentDevice; +static u16 core[2][65536], mcu[2][65536], address[2]; +static u16 pending[2][6]; +static unsigned coreDelay[2], contextDelay[2], waits; +static u16 nextState[2]; +static int failReg = -1, ignoreReg = -1, failMcu = -1; +static bool overrideExposure, stuckContext, liveAe, deferredCore, inFlightAwb; +static const u16 coreRegs[] = {0x3012, 0x3014, 0x302A, 0x302C, 0x302E, 0x3030}; +static const u16 baseline[] = {120, 246, 32, 36, 40, 32}; +static const u16 autoRegs[] = {0xA117, + 0xA11D, + 0xA123, + 0xA129, + 0xA118, + 0xA11E, + 0xA124, + 0xA12A, + 0xA119, + 0xA11F, + 0xA125, + 0xA12B, + 0xA11A, + 0xA120, + 0xA126, + 0xA12C, + 0xA115, + 0xA102}; + +static int cameraIndex(void) { return currentDevice == I2C_CAM0 ? 0 : 1; } + +u8 aptWriteRegister(u8 device, u16 reg, u16 value) { + int cam = device == I2C_CAM0 ? 0 : 1; + if(reg == failReg) + return 0; + if(reg == ignoreReg) + return 1; + if(reg == 0x098C) { + address[cam] = value; + return 1; + } + if(reg == 0x0990) { + if(address[cam] == failMcu) + return 0; + mcu[cam][address[cam]] = value; + if(address[cam] == 0xA103 && !stuckContext) { + nextState[cam] = value == CAPTURE_MODE_PREVIEW ? 3 : 7; + contextDelay[cam] = 4; + mcu[cam][0xA103] = 0; + mcu[cam][0xA104] = 5; + } + return 1; + } + // Do not destroy the sensor's color/digital calibration via global gain. + assert(reg == 0x3022 || reg == 0x3012 || reg == 0x3014 || (reg >= 0x302A && reg <= 0x3030)); + if(reg == 0x3022) { + if(!(value & 0x0100) && (core[cam][reg] & 0x0100)) { + if(deferredCore) + coreDelay[cam] = 20; // intentionally longer than the old fixed wait + else + for(unsigned i = 0; i < 6; i++) + core[cam][coreRegs[i]] = pending[cam][i]; + } else if(value & 0x0100) { + for(unsigned i = 0; i < 6; i++) + pending[cam][i] = core[cam][coreRegs[i]]; + } + core[cam][reg] = value; + return 1; + } + for(unsigned i = 0; i < 6; i++) { + if(reg != coreRegs[i]) + continue; + if(i >= 2) + value &= value >= 64 ? ~3u : ~1u; + if(core[cam][0x3022] & 0x0100) + pending[cam][i] = value; + else + core[cam][reg] = value; + return 1; + } + abort(); +} + +u16 aptReadRegister(u8 device, u16 reg) { + int cam = device == I2C_CAM0 ? 0 : 1; + return reg == 0x0990 ? mcu[cam][address[cam]] : core[cam][reg]; +} + +void swiWaitForVBlank(void) { + waits++; + int cam = cameraIndex(); + if(liveAe && (mcu[cam][0xA102] & 1)) + core[cam][0x3012] = 999; + if(inFlightAwb) { + // A color update already queued when live drivers were disabled. + core[cam][0x302C] = 44; + inFlightAwb = false; + } + if(coreDelay[cam] && !--coreDelay[cam]) + for(unsigned i = 0; i < 6; i++) + core[cam][coreRegs[i]] = pending[cam][i]; + if(overrideExposure) + core[cam][0x3012] = 999; + if(contextDelay[cam] && !--contextDelay[cam]) { + mcu[cam][0xA104] = nextState[cam]; + for(unsigned i = 0; i < 6; i++) + core[cam][coreRegs[i]] = baseline[i]; + } +} +u8 i2cWriteRegister(u8 device, u8 reg, u8 value) { return 1; } +u8 i2cReadRegister(u8 device, u8 reg) { return 0; } + +static void setup(int cam) { + currentDevice = cam ? I2C_CAM1 : I2C_CAM0; + assert(setExposure(0, 0)); + for(unsigned i = 0; i < sizeof(autoRegs) / sizeof(*autoRegs); i++) + mcu[cam][autoRegs[i]] = autoRegs[i] == 0xA115 ? 0x72 : autoRegs[i] == 0xA102 ? 0x8F : cam + 1; + for(unsigned i = 0; i < 6; i++) + core[cam][coreRegs[i]] = baseline[i]; + core[cam][0x3022] = 1; + mcu[cam][0xA104] = 3; +} + +static void restored(int cam) { + assert(core[cam][0x3022] == 1); + for(unsigned i = 0; i < 6; i++) + assert(core[cam][coreRegs[i]] == baseline[i]); + for(unsigned i = 0; i < sizeof(autoRegs) / sizeof(*autoRegs); i++) + assert(mcu[cam][autoRegs[i]] == (autoRegs[i] == 0xA115 ? 0x72 : autoRegs[i] == 0xA102 ? 0x8F : cam + 1)); +} + +int main(void) { + liveAe = true; + deferredCore = true; + setup(0); + core[0][0x302E] = 52; + // Physical DSi failure: blue gain request 13 reads back as 12. + assert(setExposure(1, 0)); + assert(core[0][0x302E] == 12); + assert(core[0][0x3012] == 1); + assert(setExposure(0, 0)); + assert(core[0][0x302E] == 52); + for(int cam = 0; cam < 2; cam++) { + setup(cam); + // This recreates the reported auto->manual failure with live AE enabled. + assert(setExposure(1, 0)); + assert(mcu[cam][0xA102] == 0x80); + assert(mcu[cam][0xA115] == 0x02); + assert(core[cam][0x3012] == 1 && core[cam][0x3014] == 0x6B); + assert(core[cam][0x302A] == 8 && core[cam][0x302C] == 8 && core[cam][0x302E] == 10); + for(unsigned gain = 0; gain < 4; gain++) { + assert(setExposure(640, gain)); + assert(core[cam][0x3012] == 640); + assert(core[cam][0x302A] == (8u << gain)); + assert(core[cam][0x302C] == (gain ? 9u << gain : 8)); + assert(core[cam][0x302E] == (10u << gain)); + } + assert(setMode(CAPTURE_MODE_CAPTURE)); + assert(!contextDelay[cam] && mcu[cam][0xA104] == 7); + assert(setExposure(64, 0)); + for(int i = 0; i < 8; i++) + swiWaitForVBlank(); + assert(core[cam][0x3012] == 64); + assert(setMode(CAPTURE_MODE_PREVIEW)); + assert(setExposure(64, 0)); + assert(core[cam][0x3012] == 64); + assert(setExposure(0, 0)); + restored(cam); + } + setup(0); + inFlightAwb = true; + assert(setExposure(8, 0)); + assert(core[0][0x302C] == 10); // Color baseline sampled after the queued update. + assert(setExposure(0, 0)); + assert(core[0][0x302C] == 44); + + setup(0); + core[0][0x302A] = core[0][0x3030] = 12; + core[0][0x302C] = 14; + core[0][0x302E] = 16; + assert(setExposure(8, 2)); + assert(core[0][0x302A] == 32 && core[0][0x302C] == 36 && core[0][0x302E] == 42); + assert(setExposure(0, 0)); + assert(core[0][0x302A] == 12 && core[0][0x302C] == 14 && core[0][0x302E] == 16); + + setup(0); + assert(!setExposure(641, 0) && !setExposure(1, 4)); + failMcu = 0xA102; + assert(!setExposure(8, 0)); + assert(exposureError(EXPOSURE_ERROR_STAGE) == 2); + assert(exposureError(EXPOSURE_ERROR_REGISTER) == 0xA102); + failMcu = -1; + assert(setExposure(0, 0)); + restored(0); + + setup(0); + failReg = 0x3012; + assert(!setExposure(8, 0)); + assert(exposureError(EXPOSURE_ERROR_REGISTER) == 0x3012); + assert(!(core[0][0x3022] & 0x0100)); + failReg = -1; + assert(setExposure(0, 0)); + restored(0); + + setup(0); + ignoreReg = 0x3012; + assert(!setExposure(8, 0)); + assert(exposureError(EXPOSURE_ERROR_STAGE) == 5); + assert(exposureError(EXPOSURE_ERROR_REGISTER) == 0x3012); + assert(exposureError(EXPOSURE_ERROR_EXPECTED) == 8); + assert(exposureError(EXPOSURE_ERROR_OBSERVED) == 120); + ignoreReg = -1; + assert(setExposure(0, 0)); + restored(0); + + setup(0); + assert(setExposure(8, 0)); + overrideExposure = true; + assert(!setExposure(4, 0)); + overrideExposure = false; + assert(setExposure(0, 0)); + restored(0); + + stuckContext = true; + waits = 0; + assert(!setMode(CAPTURE_MODE_CAPTURE)); + assert(waits == 180 && exposureError(EXPOSURE_ERROR_REGISTER) == 0xA104); + puts("exposure: live AE regression, delayed/quantized gains, color preservation, context entry, both cameras, " + "restore, failed/ignored writes, override, timeout passed"); +} diff --git a/tools/capture/night_test.c b/tools/capture/night_test.c new file mode 100644 index 0000000..3e18bf6 --- /dev/null +++ b/tools/capture/night_test.c @@ -0,0 +1,98 @@ +#include "night.h" + +#include +#include +#include +#include + +static unsigned rng = 7; +static int noise(void) { + rng = rng * 1664525u + 1013904223u; + return (int)((rng >> 24) % 17) - 8; +} + +static void flat(uint8_t *frame, int y) { + for(int p = 0; p < NIGHT_BYTES; p += 4) { + frame[p] = frame[p + 2] = y; + frame[p + 1] = 110; + frame[p + 3] = 145; + } +} + +int main(void) { + uint8_t *ref = malloc(NIGHT_BYTES), *next = malloc(NIGHT_BYTES), *out = malloc(NIGHT_BYTES); + assert(ref && next && out); + flat(ref, 60); + NightStack *s = nightCreate(ref); + assert(s); + nightFinish(s, out); + assert(memcmp(ref, out, NIGHT_BYTES) == 0); + for(int n = 0; n < 3; n++) + assert(nightAdd(s, ref)); + assert(!nightAdd(s, ref)); + nightFinish(s, out); + assert(memcmp(ref, out, NIGHT_BYTES) == 0); + nightFree(s); + + // Independent sensor noise should fall without changing chroma or brightness. + for(int p = 0; p < NIGHT_BYTES; p += 2) + ref[p] = 60 + noise(); + s = nightCreate(ref); + for(int n = 0; n < 3; n++) { + flat(next, 60); + for(int p = 0; p < NIGHT_BYTES; p += 2) + next[p] = 60 + noise(); + assert(nightAdd(s, next)); + } + nightFinish(s, out); + unsigned before = 0, after = 0; + for(int p = 0; p < NIGHT_BYTES; p += 2) { + before += (ref[p] - 60) * (ref[p] - 60); + after += (out[p] - 60) * (out[p] - 60); + } + assert(after * 2 < before); + nightFree(s); + + // Local motion must retain the first frame, without smearing a bright moon. + flat(ref, 30); + flat(next, 30); + for(int y = 200; y < 240; y++) + for(int x = 300; x < 340; x++) + ref[(y * NIGHT_WIDTH + x) * 2] = 220; + s = nightCreate(ref); + assert(nightAdd(s, next)); + nightFinish(s, out); + assert(memcmp(ref, out, NIGHT_BYTES) == 0); + nightFree(s); + + // Full-frame translation aligns luma and keeps Cb/Cr in their own slots. + for(int y = 0; y < NIGHT_HEIGHT; y++) { + for(int x = 0; x < NIGHT_WIDTH; x += 2) { + int p = (y * NIGHT_WIDTH + x) * 2; + ref[p] = ref[p + 2] = 40 + (rng >> 24) % 160; + rng = rng * 1664525u + 1013904223u; + ref[p + 1] = 110; + ref[p + 3] = 145; + } + } + flat(next, 20); + for(int y = 0; y < NIGHT_HEIGHT - 3; y++) + memcpy(next + ((y + 3) * NIGHT_WIDTH + 4) * 2, ref + y * NIGHT_WIDTH * 2, (NIGHT_WIDTH - 4) * 2); + s = nightCreate(ref); + assert(nightAdd(s, next)); + nightFinish(s, out); + assert(memcmp(ref, out, NIGHT_BYTES) == 0); + nightFree(s); + + flat(ref, 30); + flat(next, 230); + s = nightCreate(ref); + assert(!nightAdd(s, next)); + nightFinish(s, ref); // in-place output is the capture path + assert(ref[0] == 30); + nightFree(s); + free(ref); + free(next); + free(out); + puts("night: identity, frame cap, noise reduction, motion rejection, translation, edges, scene changes passed"); +} diff --git a/tools/capture/rear_light_test.c b/tools/capture/rear_light_test.c new file mode 100644 index 0000000..1f1ef99 --- /dev/null +++ b/tools/capture/rear_light_test.c @@ -0,0 +1,75 @@ +#include "aptina.h" +#include "aptina_i2c.h" + +#include +#include + +static u16 core[2][65536]; +static u8 light; +static bool failWrite, ignoreWrite; + +u8 aptWriteRegister(u8 device, u16 reg, u16 value) { + int cam = device == I2C_CAM0 ? 0 : 1; + core[cam][reg] = value; + if(reg == 0x0018) { + if(value & 1) { + core[cam][reg] |= 0x4000; + core[cam][0x301A] &= ~4; + } else { + core[cam][reg] &= ~0x4000; + core[cam][0x301A] |= 4; + } + } + return 1; +} + +u16 aptReadRegister(u8 device, u16 reg) { return core[device == I2C_CAM0 ? 0 : 1][reg]; } + +u8 i2cWriteRegister(u8 device, u8 reg, u8 value) { + assert(device == I2C_PM && reg == I2CREGPM_CAMLED); + if(failWrite) + return 0; + if(!ignoreWrite) + light = value; + return 1; +} + +u8 i2cReadRegister(u8 device, u8 reg) { + assert(device == I2C_PM && reg == I2CREGPM_CAMLED); + return light; +} + +void swiWaitForVBlank(void) { assert(!"unexpected wait"); } + +int main(void) { + assert(setRearLight(false) && !light); + activate(I2C_CAM1); + assert(!light); + assert(setRearLight(true) && light == 1); + assert(setRearLight(false) && !light); + deactivate(I2C_CAM1); + activate(I2C_CAM1); + assert(!light); + assert(setRearLight(true) && light == 1); + deactivate(I2C_CAM1); + assert(!light); + activate(I2C_CAM0); + assert(!light); + assert(setRearLight(true) && !light); + deactivate(I2C_CAM0); + activate(I2C_CAM1); + assert(light == 1); + failWrite = true; + assert(!setRearLight(false) && light == 1); + failWrite = false; + ignoreWrite = true; + assert(!setRearLight(false) && light == 1); + ignoreWrite = false; + deactivate(I2C_CAM1); + activate(I2C_CAM1); + assert(light == 1); + assert(setRearLight(false) && !light); + deactivate(I2C_CAM1); + assert(!light); + puts("rear light: verified writes, inner/outer switching, sleep persistence, failed/ignored writes passed"); +} diff --git a/tools/capture/shim/nds.h b/tools/capture/shim/nds.h new file mode 100644 index 0000000..f72d399 --- /dev/null +++ b/tools/capture/shim/nds.h @@ -0,0 +1,14 @@ +#ifndef TEST_NDS_H +#define TEST_NDS_H +#include +#include +typedef uint8_t u8; +typedef uint16_t u16; +#define I2C_CAM0 0x7A +#define I2C_CAM1 0x78 +#define I2C_PM 0x4A +#define I2CREGPM_CAMLED 0x31 +void swiWaitForVBlank(void); +u8 i2cWriteRegister(u8 device, u8 reg, u8 value); +u8 i2cReadRegister(u8 device, u8 reg); +#endif diff --git a/tools/capture/shim/nds/arm7/i2c.h b/tools/capture/shim/nds/arm7/i2c.h new file mode 100644 index 0000000..c4909c4 --- /dev/null +++ b/tools/capture/shim/nds/arm7/i2c.h @@ -0,0 +1 @@ +// The exposure tests replace I2C with an in-memory sensor. From 78ce3362cfc8a130219745ebdf1424efd7ee715c Mon Sep 17 00:00:00 2001 From: Addison King Date: Mon, 26 Oct 2026 03:17:22 -0400 Subject: [PATCH 2/4] fix: recover camera controls after sensor failures --- README.md | 4 +- arm7/source/aptina.c | 14 ++- arm9/include/camera.h | 8 +- arm9/source/camera.c | 58 ++++++--- arm9/source/main.c | 171 ++++++++++++-------------- tools/capture/Makefile | 4 +- tools/capture/camera_test.c | 115 +++++++++++++++++ tools/capture/exposure_test.c | 16 +++ tools/capture/rear_light_test.c | 8 ++ tools/capture/shim/calico/arm/cache.h | 1 + tools/capture/shim/calico/nds/irq.h | 1 + tools/capture/shim/calico/nds/pxi.h | 1 + tools/capture/shim/nds.h | 16 +++ tools/capture/shim/nds/ndstypes.h | 1 + 14 files changed, 302 insertions(+), 116 deletions(-) create mode 100644 tools/capture/camera_test.c create mode 100644 tools/capture/shim/calico/arm/cache.h create mode 100644 tools/capture/shim/calico/nds/irq.h create mode 100644 tools/capture/shim/calico/nds/pxi.h create mode 100644 tools/capture/shim/nds/ndstypes.h diff --git a/README.md b/README.md index b3ff75b..cf73b8c 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ clean. Press **X**. Use up/down to select a row and left/right to adjust, or tap the arrows beside a value. Press **A** on Shutter to return to Auto, -on Gain, Night Burst, or Timestamp to cycle/toggle, or on Reset to restore all +on Gain, Night Burst, Rear Light, or Timestamp to cycle/toggle, or on Reset to restore all settings. Press **B** or **X** to return to the viewfinder. The top screen stays live while adjusting. Gain is gray and cannot be selected until Shutter is manual. In photo mode, L/R takes photos directly from Advanced without closing it; @@ -108,7 +108,7 @@ Sensor writes are grouped and integration/gain are read back at sensor frame boundaries before use. Context changes wait for final preview/capture entry before reapplying the controls. Failures keep the previous selection, show a stage/register code, and append expected/observed values to -`/photos/exposure-errors.log` before rollback. Exact +`/photos/exposure-errors.log`. Exact shutter times and actual sensor behavior still need validation on a physical DSi; no diagnostic or probe app is included. Register definitions follow [GBATEK's Aptina register research](https://mgba-emu.github.io/gbatek/#dsi-aptina-camera-registers-core-3000h-31ffh-38xxh). diff --git a/arm7/source/aptina.c b/arm7/source/aptina.c index 3ee2e40..6811541 100644 --- a/arm7/source/aptina.c +++ b/arm7/source/aptina.c @@ -7,10 +7,10 @@ static bool s_cameraActive; static bool s_rearLight = true; bool setRearLight(bool enabled) { - u8 value = enabled && s_cameraActive && currentDevice == I2C_CAM1; + s_rearLight = enabled; + u8 value = enabled && s_cameraActive && currentDevice == I2C_CAM1; if(!i2cWriteRegister(I2C_PM, I2CREGPM_CAMLED, value) || (i2cReadRegister(I2C_PM, I2CREGPM_CAMLED) & 3) != value) return false; - s_rearLight = enabled; return true; } @@ -256,8 +256,16 @@ static bool exposureFreeze(int cam) { static bool exposureWriteCore(const u16 *values) { u16 hold = aptReadRegister(currentDevice, 0x3022); - if(hold == 0xFFFF || (hold & 0x0100)) + if(hold == 0xFFFF) return exposureFail(1, 0x3022, 0, hold); + if(hold & 0x0100) { + hold &= ~0x0100; + bool released = false; + for(int i = 0; i < 3 && !released; i++) + released = aptWriteRegister(currentDevice, 0x3022, hold) && aptReadRegister(currentDevice, 0x3022) == hold; + if(!released) + return exposureFail(2, 0x3022, hold, aptReadRegister(currentDevice, 0x3022)); + } bool written = aptWriteRegister(currentDevice, 0x3022, hold | 0x0100) && aptReadRegister(currentDevice, 0x3022) == (hold | 0x0100); if(!written) diff --git a/arm9/include/camera.h b/arm9/include/camera.h index 528f2c6..39d1045 100644 --- a/arm9/include/camera.h +++ b/arm9/include/camera.h @@ -43,7 +43,7 @@ bool cameraSetRearLight(bool enabled); bool cameraCapture(u16 *dst, CaptureMode mode); // Real sensor integration in rows (0 = auto), analogue gain 1x/2x/4x/8x. -// Applied again after mode changes; false means register verification failed. +// Applied again after mode changes; false means sensor or preview setup failed. bool cameraSetExposure(unsigned lines, unsigned gain); unsigned cameraExposureError(ExposureErrorField field); @@ -56,10 +56,12 @@ bool cameraStreamStart(void); // Stops continuous capture (safe to call when not streaming). void cameraStreamStop(void); -// True while the continuous stream is armed. Single source of truth for -// whether the viewfinder should be producing frames. +// True while the continuous stream is armed. bool cameraStreamRunning(void); +// Includes a failed start that the preview watchdog will retry. +bool cameraStreamRequested(void); + // Returns the newest completed frame, or NULL if no new frame arrived since the // last call. The pointer is one of three buffers the camera rotates through, so // it stays valid for about two frame periods - copy out what you need right diff --git a/arm9/source/camera.c b/arm9/source/camera.c index e07eb4d..674a49a 100644 --- a/arm9/source/camera.c +++ b/arm9/source/camera.c @@ -33,6 +33,7 @@ CaptureMode activeMode = CAPTURE_MODE_PREVIEW; alignas(32) static u16 s_frames[CAM_FRAMES][256 * 192]; static bool s_streaming; +static bool s_streamRequested; static unsigned s_exposureLines; static unsigned s_exposureGain; static u16 s_exposureError[EXPOSURE_ERROR_FIELDS]; @@ -146,21 +147,29 @@ static bool camWaitDone(u32 vblanks) { return false; } -// Sets up the sensor mode and the CAM_CNT format bits, then starts the camera -// interface. Only called when the interface is not streaming. +static bool camApplyExposure(unsigned lines, unsigned gain); + +static void camReadExposureError(void) { + for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) + s_exposureError[i] = pxiSendAndReceive(PXI_CAMERA, CAM_GET_EXPOSURE_ERROR_STAGE + i); +} + +// Sets up the sensor mode and the CAM_CNT format bits while stopped. static bool camConfigure(CaptureMode mode) { bool preview = mode == CAPTURE_MODE_PREVIEW; if(mode != activeMode || !s_modeValid) { - if(pxiSendAndReceive(PXI_CAMERA, preview ? CAM_SET_MODE_PREVIEW : CAM_SET_MODE_CAPTURE) != mode) + if(pxiSendAndReceive(PXI_CAMERA, preview ? CAM_SET_MODE_PREVIEW : CAM_SET_MODE_CAPTURE) != mode) { + camReadExposureError(); return false; + } activeMode = mode; s_modeValid = true; s_exposureDirty = true; } if(s_exposureDirty) { - if(!cameraSetExposure(s_exposureLines, s_exposureGain)) + if(!camApplyExposure(s_exposureLines, s_exposureGain)) return false; s_exposureDirty = false; } @@ -174,12 +183,7 @@ static bool camConfigure(CaptureMode mode) { return true; } -bool cameraSetExposure(unsigned lines, unsigned gain) { - if(lines > CAM_EXPOSURE_MAX_LINES || gain > 3 || activeCamera == CAM_NONE) - return false; - bool streaming = cameraStreamRunning(); - if(streaming) - cameraStreamStop(); +static bool camApplyExposure(unsigned lines, unsigned gain) { bool ok = pxiSendAndReceive(PXI_CAMERA, CAM_EXPOSURE_REQUEST | lines | (gain << CAM_EXPOSURE_GAIN_SHIFT)) == 1; if(ok) { s_exposureLines = lines; @@ -188,15 +192,34 @@ bool cameraSetExposure(unsigned lines, unsigned gain) { } bool restored = ok; if(!ok) { - for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) - s_exposureError[i] = pxiSendAndReceive(PXI_CAMERA, CAM_GET_EXPOSURE_ERROR_STAGE + i); + camReadExposureError(); restored = pxiSendAndReceive( PXI_CAMERA, CAM_EXPOSURE_REQUEST | s_exposureLines | (s_exposureGain << CAM_EXPOSURE_GAIN_SHIFT)) == 1; s_exposureDirty = !restored; } - if(streaming && restored) - cameraStreamStart(); + return ok; +} + +bool cameraSetExposure(unsigned lines, unsigned gain) { + if(lines > CAM_EXPOSURE_MAX_LINES || gain > 3 || activeCamera == CAM_NONE) + return false; + bool resume = s_streamRequested; + unsigned oldLines = s_exposureLines, oldGain = s_exposureGain; + for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) + s_exposureError[i] = 0; + cameraStreamStop(); + bool ok = camApplyExposure(lines, gain); + if(resume && !cameraStreamStart()) { + if(ok) { + bool restored = camApplyExposure(oldLines, oldGain); + s_exposureLines = oldLines; + s_exposureGain = oldGain; + s_exposureDirty = !restored; + cameraStreamStart(); + } + return false; + } return ok; } @@ -234,6 +257,8 @@ bool cameraStreamStart(void) { return false; cameraStreamStop(); + s_streamRequested = true; + s_callsWithoutFrame = 0; if(!camConfigure(CAPTURE_MODE_PREVIEW)) return false; @@ -271,6 +296,7 @@ void cameraStreamStop(void) { REG_IF = IRQ_NDMA1; irqClear(IRQ_NDMA1); s_streaming = false; + s_streamRequested = false; } u16 *cameraNextFrame(void) { @@ -279,7 +305,7 @@ u16 *cameraNextFrame(void) { // Nothing for a long time means the camera stream died (or the sensor // went into standby); restart it rather than sitting on a frozen // picture forever. Callers poll once per vblank. - if(s_streaming && ++s_callsWithoutFrame > 240) { + if(s_streamRequested && ++s_callsWithoutFrame > 240) { s_callsWithoutFrame = 0; cameraStreamStart(); } @@ -299,3 +325,5 @@ u16 *cameraNextFrame(void) { u32 cameraStreamOverruns(void) { return s_overruns; } bool cameraStreamRunning(void) { return s_streaming; } + +bool cameraStreamRequested(void) { return s_streamRequested; } diff --git a/arm9/source/main.c b/arm9/source/main.c index abc1be0..eedc1d4 100644 --- a/arm9/source/main.c +++ b/arm9/source/main.c @@ -57,8 +57,11 @@ static void drainJobs(void); // The viewfinder is a continuous camera stream now. camera.c owns the state; // these wrappers just avoid restarting a stream that is already running. static void streamStart(void) { - if(!cameraStreamRunning()) - cameraStreamStart(); + bool lightReady = cameraSetRearLight(s_rearLight); + if(!cameraStreamRunning() && !cameraStreamStart()) + uiStatus("PREVIEW FAILED - TRY AGAIN"); + else if(!lightReady) + uiStatus("REAR LIGHT SETTING FAILED"); } static void streamStop(void) { cameraStreamStop(); } @@ -66,7 +69,7 @@ static void streamStop(void) { cameraStreamStop(); } // Lid closed: shut the camera off and sleep until it reopens. Usable from any // screen; VRAM survives sleep so nothing needs redrawing after. static void lidSleep(void) { - bool wasStreaming = cameraStreamRunning(); + bool wasStreaming = cameraStreamRequested(); streamStop(); drainJobs(); if(pmShouldReset()) @@ -154,7 +157,6 @@ static void yuvToRgb(const u16 *yuv, u8 *rgb) { static void rawPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.YUV", num); } static void thumbPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.THM", num); } -static void metadataPath(char *out, int num) { sprintf(out, RAW_DIR "/IMG_%04d.TXT", num); } static void vidPath(char *out, int num) { sprintf(out, RAW_DIR "/VID_%04d.VID", num); } static void vidThumbPath(char *out, int num) { sprintf(out, RAW_DIR "/VID_%04d.THM", num); } @@ -186,8 +188,13 @@ static void cfgSave(void) { FILE *f = fopen(CFG_PATH, "w"); if(!f) return; - fprintf(f, "timestamp=%d\nshutter=%u\ngain=%u\nnight_burst=%d\nrear_light=%d\n", - s_timestamp ? 1 : 0, s_shutter, s_gain, s_nightBurst ? 1 : 0, s_rearLight ? 1 : 0); + fprintf(f, + "timestamp=%d\nshutter=%u\ngain=%u\nnight_burst=%d\nrear_light=%d\n", + s_timestamp ? 1 : 0, + s_shutter, + s_gain, + s_nightBurst ? 1 : 0, + s_rearLight ? 1 : 0); fclose(f); } @@ -276,47 +283,14 @@ static int dayKey(time_t t) { #define JOB_PHOTO 0 // (JOB_ values 1 and 2 are CHUNK_VIDEO / CHUNK_AUDIO) -typedef struct PhotoMetadata { - time_t captured; - Camera camera; - unsigned lines, gain; - bool night, rearLight, watermark; -} PhotoMetadata; - typedef struct Job { u32 type; // JOB_PHOTO / CHUNK_VIDEO / CHUNK_AUDIO u32 aux; // photo num / chunk index (frame or audio block number) u32 slot; // ring/pool slot to return after writing (video/audio) u32 size; // payload bytes (video/audio) u16 *buf; - PhotoMetadata photo; } Job; -static bool savePhotoMetadata(int num, const PhotoMetadata *photo) { - char path[40], shutter[20], gain[12]; - metadataPath(path, num); - FILE *f = fopen(path, "w"); - if(!f) - return false; - if(photo->lines) { - snprintf(shutter, sizeof(shutter), "%u lines", photo->lines); - snprintf(gain, sizeof(gain), "%ux", photo->gain); - } else { - strcpy(shutter, "auto"); - strcpy(gain, "auto"); - } - bool saved = fprintf(f, - "captured_unix=%ld\ncamera=%s\nshutter=%s\ngain_nominal=%s\n" - "night_burst=%d\nframes=%d\nrear_light_during_capture=%d\ntimestamp=%d\n", - (long)photo->captured, photo->camera == CAM_OUTER ? "outer" : "inner", shutter, gain, - photo->night, photo->night ? NIGHT_FRAMES : 1, photo->rearLight, photo->watermark) >= 0; - if(fclose(f) != 0) - saved = false; - if(!saved) - remove(path); - return saved; -} - #define JOB_QUEUE_LEN 32 static Thread s_workerThread; @@ -401,9 +375,7 @@ static int workerMain(void *arg) { if(!saved) remove(path); } - bool metadataSaved = saved && savePhotoMetadata(job->aux, &job->photo); - snprintf(msg, sizeof(msg), !saved ? "SAVE FAILED: IMG_%04d" : - metadataSaved ? "SAVED IMG_%04d" : "SAVED IMG_%04d - NO METADATA", (int)job->aux); + snprintf(msg, sizeof(msg), saved ? "SAVED IMG_%04d" : "SAVE FAILED: IMG_%04d", (int)job->aux); uiStatus(msg); // Thumbnail cache for the album grid. @@ -470,18 +442,9 @@ static bool captureRaw(u16 *previewGfx) { swiWaitForVBlank(); } - time_t shotTime = time(NULL); - job->photo = (PhotoMetadata){ - .captured = shotTime, - .camera = s_camera, - .lines = s_shutterLines[s_shutter], - .gain = s_shutter ? 1u << s_gain : 0, - .night = s_nightBurst, - .rearLight = s_camera == CAM_OUTER && s_rearLight && !s_nightBurst, - .watermark = s_timestamp, - }; + time_t shotTime = time(NULL); NightStack *stack = NULL; - u16 *next = NULL; + u16 *next = NULL; const char *error = "CAMERA FAILED - TRY AGAIN"; if(s_nightBurst) uiStatus("HOLD STILL 1/4 B: CANCEL"); @@ -490,7 +453,7 @@ static bool captureRaw(u16 *previewGfx) { memcpy(yuv, yuv + 640, 640 * sizeof(u16)); if(s_nightBurst) { - next = (u16 *)memalign(32, RAW_SIZE); + next = (u16 *)memalign(32, RAW_SIZE); stack = nightCreate((const u8 *)yuv); if(!next || !stack) { error = "NOT ENOUGH MEMORY"; @@ -1056,9 +1019,6 @@ static void softDelete(int num, bool isVideo) { thumbPath(from, num); sprintf(to, RAW_DIR "/trash/IMG_%04d.THM", num); rename(from, to); - metadataPath(from, num); - sprintf(to, RAW_DIR "/trash/IMG_%04d.TXT", num); - rename(from, to); } } @@ -1379,12 +1339,16 @@ static void uiAdvancedScreen(int selected) { sprintf(gain, "%uX", 1u << s_gain); else strcpy(gain, "AUTO"); - const char *values[] = {shutter, gain, !s_videoMode && s_nightBurst ? "ON" : "OFF", - s_camera == CAM_OUTER && s_rearLight ? "ON" : "OFF", s_timestamp ? "ON" : "OFF", ""}; + const char *values[] = {shutter, + gain, + !s_videoMode && s_nightBurst ? "ON" : "OFF", + s_camera == CAM_OUTER && s_rearLight ? "ON" : "OFF", + s_timestamp ? "ON" : "OFF", + ""}; for(int i = 0; i < ADV_COUNT; i++) { - int y = ADV_ROW_Y + i * ADV_ROW_H; + int y = ADV_ROW_Y + i * ADV_ROW_H; bool enabled = advancedRowEnabled(i); - bool active = enabled && i == selected; + bool active = enabled && i == selected; uiRect(12, y, 232, ADV_ROW_H, active ? UI_PANEL : UI_BG); if(active) uiRect(12, y + 3, 2, 11, UI_ACCENT); @@ -1397,29 +1361,43 @@ static void uiAdvancedScreen(int selected) { } uiTextCenter(159, "UP/DOWN SELECT < > ADJUST", UI_DIM); uiTextCenter(171, s_videoMode ? "A: SET B/X: DONE" : "A: SET L/R: PHOTO B/X: DONE", UI_DIM); - const char *hints[] = {"A: AUTO - MANUAL UNLOCKS GAIN", "HIGHER GAIN ADDS NOISE", - "4 FRAMES - REAR LIGHT OFF", "OFF WHILE NIGHT BURST SHOOTS", - "BURN DATE AND TIME INTO IMAGE", "A: RESET ALL SETTINGS"}; + const char *hints[] = {"A: AUTO - MANUAL UNLOCKS GAIN", + "HIGHER GAIN ADDS NOISE", + "4 FRAMES - REAR LIGHT OFF", + "OFF WHILE NIGHT BURST SHOOTS", + "BURN DATE AND TIME INTO IMAGE", + "A: RESET ALL SETTINGS"}; uiStatus(hints[selected]); } static void uiExposureFailure(unsigned lines, unsigned gain) { unsigned stage = cameraExposureError(EXPOSURE_ERROR_STAGE); - unsigned reg = cameraExposureError(EXPOSURE_ERROR_REGISTER); + unsigned reg = cameraExposureError(EXPOSURE_ERROR_REGISTER); char message[40]; - snprintf(message, sizeof(message), "SENSOR E%u R%04X - TRY AUTO", stage, reg); + if(stage) + snprintf(message, sizeof(message), "SENSOR E%u R%04X - TRY AUTO", stage, reg); + else + strcpy(message, "PREVIEW FAILED - TRY AGAIN"); uiStatus(message); FILE *f = fopen(RAW_DIR "/exposure-errors.log", "a"); if(!f) return; - fprintf(f, "time=%ld camera=%d lines=%u gain=%u stage=%u reg=%04X expected=%04X observed=%04X\n", - (long)time(NULL), s_camera, lines, gain, stage, reg, - cameraExposureError(EXPOSURE_ERROR_EXPECTED), cameraExposureError(EXPOSURE_ERROR_OBSERVED)); + fprintf(f, + "time=%ld camera=%d lines=%u gain=%u stage=%u reg=%04X expected=%04X observed=%04X\n", + (long)time(NULL), + s_camera, + lines, + gain, + stage, + reg, + cameraExposureError(EXPOSURE_ERROR_EXPECTED), + cameraExposureError(EXPOSURE_ERROR_OBSERVED)); fclose(f); } -static void advancedMenu(u16 *gfx) { - int selected = s_videoMode ? ADV_TIMESTAMP : ADV_SHUTTER; +static bool advancedMenu(u16 *gfx) { + bool exitRequested = false; + int selected = s_videoMode ? ADV_TIMESTAMP : ADV_SHUTTER; keysSetRepeat(18, 6); uiAdvancedScreen(selected); while(!pmShouldReset()) { @@ -1432,7 +1410,7 @@ static void advancedMenu(u16 *gfx) { u16 *frame = cameraNextFrame(); if(frame) memcpy(gfx, frame, VID_FRAME_SIZE); - u16 pressed = keysDownRepeat(); + u16 pressed = keysDownRepeat(); bool tappedAction = false; if(keysDown() & KEY_TOUCH) { touchPosition touch; @@ -1450,8 +1428,10 @@ static void advancedMenu(u16 *gfx) { } } } - if(keysDown() & (KEY_B | KEY_X | KEY_START)) + if(keysDown() & (KEY_B | KEY_X | KEY_START)) { + exitRequested = (keysDown() & KEY_START) != 0; break; + } if(!s_videoMode && (keysDown() & (KEY_L | KEY_R))) { takePhotos(gfx); continue; @@ -1465,7 +1445,7 @@ static void advancedMenu(u16 *gfx) { else if(pressed & KEY_DOWN) selected = advancedMoveSelection(selected, 1); int direction = (pressed & KEY_LEFT) ? -1 : (pressed & KEY_RIGHT) ? 1 : 0; - bool action = tappedAction || (keysDown() & KEY_A); + bool action = tappedAction || (keysDown() & KEY_A); if(selected == ADV_SHUTTER) { if(direction) s_shutter = clamp((int)s_shutter + direction, 0, SHUTTER_COUNT - 1); @@ -1484,21 +1464,21 @@ static void advancedMenu(u16 *gfx) { s_rearLight = direction ? direction > 0 : !s_rearLight; } else if(selected == ADV_RESET && action) { s_shutter = s_gain = 0; - s_nightBurst = false; - s_timestamp = false; - s_rearLight = true; + s_nightBurst = false; + s_timestamp = false; + s_rearLight = true; } - bool changed = !s_videoMode && (oldShutter != s_shutter || oldGain != s_gain); + bool changed = !s_videoMode && (oldShutter != s_shutter || oldGain != s_gain); unsigned attemptedLines = s_shutterLines[s_shutter], attemptedGain = s_gain; if(changed) uiStatus("APPLYING SENSOR SETTINGS..."); bool ok = !changed || cameraSetExposure(attemptedLines, attemptedGain); if(!ok) { - s_shutter = oldShutter; - s_gain = oldGain; + s_shutter = oldShutter; + s_gain = oldGain; s_nightBurst = oldNight; - s_timestamp = oldTimestamp; - s_rearLight = oldRearLight; + s_timestamp = oldTimestamp; + s_rearLight = oldRearLight; } bool lightOk = oldRearLight == s_rearLight || cameraSetRearLight(s_rearLight); if(!lightOk) { @@ -1512,6 +1492,7 @@ static void advancedMenu(u16 *gfx) { uiStatus("REAR LIGHT SETTING FAILED"); } cfgSave(); + return exitRequested; } // Centered modal question; waits for A (true) / B (false). @@ -2011,7 +1992,7 @@ int main(int argc, char **argv) { uiStatus("INITIALIZING..."); pxiWaitRemote(PXI_CAMERA); // Wait for ARM7 to initialize PXI cameraInit(); - bool lightReady = cameraSetRearLight(s_rearLight); + cameraSetRearLight(s_rearLight); soundInit(); // ARM9 interface to the ARM7 sound driver (video playback) soundPowerOn(); soundSetMixerConfig(SoundOutSrc_Mixer, SoundOutSrc_Mixer, false, false); @@ -2033,15 +2014,17 @@ int main(int argc, char **argv) { Camera camera = CAM_OUTER; s_camera = camera; cameraActivate(camera); - if(!cameraSetExposure(s_shutterLines[s_shutter], s_gain)) { + unsigned bootLines = s_shutterLines[s_shutter], bootGain = s_gain; + bool exposureReady = cameraSetExposure(bootLines, bootGain); + if(!exposureReady) { + uiExposureFailure(bootLines, bootGain); s_shutter = s_gain = 0; cameraSetExposure(0, 0); } - streamStart(); // continuous viewfinder - uiCameraScreen(camera, fatInited); - if(!lightReady) - uiStatus("REAR LIGHT SETTING FAILED"); + streamStart(); // continuous viewfinder + if(!exposureReady) + uiStatus("SAVED EXPOSURE SETTING FAILED"); while(1) { u16 pressed = 0; @@ -2072,9 +2055,8 @@ int main(int argc, char **argv) { camera = camera == CAM_INNER ? CAM_OUTER : CAM_INNER; s_camera = camera; cameraActivate(camera); - streamStart(); - uiCameraScreen(camera, fatInited); + streamStart(); } else if(fatInited && pressed & KEY_Y) { bool video = !s_videoMode; if(!cameraSetExposure(video ? 0 : s_shutterLines[s_shutter], s_gain)) { @@ -2085,18 +2067,23 @@ int main(int argc, char **argv) { uiCameraScreen(camera, fatInited); } else if(fatInited && pressed & KEY_X) { drainJobs(); - advancedMenu(gfx); + if(advancedMenu(gfx)) { + cameraDeactivate(camera); + drainJobs(); + return 0; + } uiCameraScreen(camera, fatInited); + streamStart(); } else if(fatInited && pressed & (KEY_L | KEY_R)) { if(s_videoMode) { // Tap L/R to record, tap again to stop. drainJobs(); // finish any pending photo writes first s_savedMsg[0] = '\0'; recordVideo(gfx, s_nextVidNum++); - streamStart(); // recordVideo left the camera idle uiCameraScreen(camera, fatInited); if(s_savedMsg[0]) uiStatus(s_savedMsg); // survives the redraw above + streamStart(); // recordVideo left the camera idle } else { takePhotos(gfx); uiSpace(); // refresh the free-space line after the burst diff --git a/tools/capture/Makefile b/tools/capture/Makefile index 5c3aec9..8d77eaf 100644 --- a/tools/capture/Makefile +++ b/tools/capture/Makefile @@ -1,10 +1,12 @@ CC = clang -CFLAGS = -std=c11 -Wall -Wextra -Werror -fsanitize=address,undefined +CFLAGS = -std=c11 -Wall -Wextra -Werror -fsanitize=address,undefined -fno-sanitize-recover=all ROOT = ../.. .PHONY: test test: + $(CC) $(CFLAGS) -Wno-pointer-to-int-cast -Ishim -I$(ROOT)/arm9/include -I$(ROOT)/shared/include camera_test.c -o /tmp/dsi-camera-camera-test + /tmp/dsi-camera-camera-test $(CC) $(CFLAGS) -I$(ROOT)/arm9/include $(ROOT)/arm9/source/night.c night_test.c -o /tmp/dsi-camera-night-test /tmp/dsi-camera-night-test $(CC) $(CFLAGS) -Wno-unused-parameter -Ishim -I$(ROOT)/arm7/include -I$(ROOT)/shared/include $(ROOT)/arm7/source/aptina.c exposure_test.c -o /tmp/dsi-camera-exposure-test diff --git a/tools/capture/camera_test.c b/tools/capture/camera_test.c new file mode 100644 index 0000000..af9f044 --- /dev/null +++ b/tools/capture/camera_test.c @@ -0,0 +1,115 @@ +#include "camera.h" + +#include +#include + +#undef REG_CAM_MCNT +#undef REG_CAM_CNT +#undef REG_CAM_DAT +#undef REG_NDMA1SAD +#undef REG_NDMA1DAD +#undef REG_NDMA1TCNT +#undef REG_NDMA1WCNT +#undef REG_NDMA1BCNT +#undef REG_NDMA1CNT +static u16 REG_CAM_MCNT, REG_CAM_CNT, REG_CAM_DAT; +static u32 REG_NDMA1SAD, REG_NDMA1DAD, REG_NDMA1TCNT, REG_NDMA1WCNT, REG_NDMA1BCNT, REG_NDMA1CNT; +u32 REG_SCFG_CLK, REG_IF; + +#include "../../arm9/source/camera.c" + +static unsigned sensorLines, sensorGain, exposureCalls; +static unsigned failures; +static bool failMode; + +u32 pxiSendAndReceive(unsigned channel, u32 command) { + assert(channel == PXI_CAMERA); + if(command & CAM_EXPOSURE_REQUEST) { + exposureCalls++; + if(failures) { + failures--; + return 0; + } + sensorLines = command & CAM_EXPOSURE_LINES_MASK; + sensorGain = (command >> CAM_EXPOSURE_GAIN_SHIFT) & 3; + return 1; + } + if(command == CAM_SET_MODE_PREVIEW || command == CAM_SET_MODE_CAPTURE) + return failMode ? 0 : command == CAM_SET_MODE_PREVIEW ? CAPTURE_MODE_PREVIEW : CAPTURE_MODE_CAPTURE; + if(command >= CAM_GET_EXPOSURE_ERROR_STAGE && command <= CAM_GET_EXPOSURE_ERROR_OBSERVED) { + const u16 error[] = {2, 0x3022, 0, 0x100}; + return error[command - CAM_GET_EXPOSURE_ERROR_STAGE]; + } + return command; +} + +void swiDelay(unsigned delay) { (void)delay; } +void swiWaitForVBlank(void) { REG_NDMA1CNT = 0; } +void irqSet(u32 mask, void (*handler)(void)) { + (void)mask; + (void)handler; +} +void irqEnable(u32 mask) { (void)mask; } +void irqDisable(u32 mask) { (void)mask; } +void irqClear(u32 mask) { (void)mask; } +void armDCacheFlush(const void *address, unsigned size) { + (void)address; + (void)size; +} +void armDCacheInvalidate(const void *address, unsigned size) { + (void)address; + (void)size; +} + +static void pollPreview(void) { + for(unsigned i = 0; i < 241; i++) + assert(cameraNextFrame() == NULL); +} + +int main(void) { + assert(cameraActivate(CAM_OUTER)); + assert(cameraSetExposure(64, 2)); + assert(cameraStreamStart() && cameraStreamRunning()); + + failures = 1; + assert(!cameraSetExposure(640, 3)); + assert(cameraStreamRunning() && sensorLines == 64 && sensorGain == 2); + assert(cameraExposureError(EXPOSURE_ERROR_REGISTER) == 0x3022); + + // Failed apply, rollback, and preview reapply leave a recoverable request. + failures = 3; + assert(!cameraSetExposure(640, 3)); + assert(!cameraStreamRunning()); + assert(cameraSetExposure(128, 1)); + assert(cameraStreamRunning() && sensorLines == 128 && sensorGain == 1); + + failures = 3; + assert(!cameraSetExposure(640, 3)); + pollPreview(); + assert(cameraStreamRunning() && sensorLines == 128 && sensorGain == 1); + + cameraStreamStop(); + unsigned calls = exposureCalls; + pollPreview(); + assert(!cameraStreamRunning() && exposureCalls == calls); + + // A failed initial mode entry can recover without another shutter press. + assert(cameraActivate(CAM_INNER)); + failMode = true; + assert(!cameraStreamStart()); + assert(!cameraSetExposure(64, 0)); + assert(!cameraStreamRunning()); + failMode = false; + pollPreview(); + assert(cameraStreamRunning() && sensorLines == 128 && sensorGain == 1); + + u16 capture[256 * 192]; + assert(cameraCapture(capture, CAPTURE_MODE_PREVIEW)); + pollPreview(); + assert(!cameraStreamRunning()); + assert(cameraStreamStart()); + assert(cameraDeactivate(CAM_INNER)); + pollPreview(); + assert(!cameraStreamRunning()); + puts("camera: apply/rollback faults, preview retry, mode entry, capture and intentional stop passed"); +} diff --git a/tools/capture/exposure_test.c b/tools/capture/exposure_test.c index 9d50dd2..3e8e468 100644 --- a/tools/capture/exposure_test.c +++ b/tools/capture/exposure_test.c @@ -13,6 +13,7 @@ static unsigned coreDelay[2], contextDelay[2], waits; static u16 nextState[2]; static int failReg = -1, ignoreReg = -1, failMcu = -1; static bool overrideExposure, stuckContext, liveAe, deferredCore, inFlightAwb; +static bool failRelease; static const u16 coreRegs[] = {0x3012, 0x3014, 0x302A, 0x302C, 0x302E, 0x3030}; static const u16 baseline[] = {120, 246, 32, 36, 40, 32}; static const u16 autoRegs[] = {0xA117, @@ -40,6 +41,8 @@ u8 aptWriteRegister(u8 device, u16 reg, u16 value) { int cam = device == I2C_CAM0 ? 0 : 1; if(reg == failReg) return 0; + if(reg == 0x3022 && !(value & 0x0100) && failRelease) + return 0; if(reg == ignoreReg) return 1; if(reg == 0x098C) { @@ -228,6 +231,19 @@ int main(void) { assert(setExposure(0, 0)); restored(0); + setup(0); + failRelease = true; + assert(!setExposure(64, 2)); + assert(core[0][0x3022] & 0x0100); + assert(!setExposure(0, 0)); + failRelease = false; + assert(setExposure(0, 0)); + restored(0); + assert(setExposure(64, 2)); + assert(core[0][0x3012] == 64); + assert(setExposure(0, 0)); + restored(0); + stuckContext = true; waits = 0; assert(!setMode(CAPTURE_MODE_CAPTURE)); diff --git a/tools/capture/rear_light_test.c b/tools/capture/rear_light_test.c index 1f1ef99..332814f 100644 --- a/tools/capture/rear_light_test.c +++ b/tools/capture/rear_light_test.c @@ -65,10 +65,18 @@ int main(void) { ignoreWrite = true; assert(!setRearLight(false) && light == 1); ignoreWrite = false; + // The caller rolls a rejected toggle back to its previous preference. + assert(setRearLight(true)); deactivate(I2C_CAM1); activate(I2C_CAM1); assert(light == 1); assert(setRearLight(false) && !light); + failWrite = true; + assert(!setRearLight(true) && !light); + failWrite = false; + deactivate(I2C_CAM1); + activate(I2C_CAM1); + assert(light == 1); deactivate(I2C_CAM1); assert(!light); puts("rear light: verified writes, inner/outer switching, sleep persistence, failed/ignored writes passed"); diff --git a/tools/capture/shim/calico/arm/cache.h b/tools/capture/shim/calico/arm/cache.h new file mode 100644 index 0000000..1f05ed0 --- /dev/null +++ b/tools/capture/shim/calico/arm/cache.h @@ -0,0 +1 @@ +#include diff --git a/tools/capture/shim/calico/nds/irq.h b/tools/capture/shim/calico/nds/irq.h new file mode 100644 index 0000000..1f05ed0 --- /dev/null +++ b/tools/capture/shim/calico/nds/irq.h @@ -0,0 +1 @@ +#include diff --git a/tools/capture/shim/calico/nds/pxi.h b/tools/capture/shim/calico/nds/pxi.h new file mode 100644 index 0000000..1f05ed0 --- /dev/null +++ b/tools/capture/shim/calico/nds/pxi.h @@ -0,0 +1 @@ +#include diff --git a/tools/capture/shim/nds.h b/tools/capture/shim/nds.h index f72d399..9a13b9a 100644 --- a/tools/capture/shim/nds.h +++ b/tools/capture/shim/nds.h @@ -1,9 +1,25 @@ #ifndef TEST_NDS_H #define TEST_NDS_H +#include #include #include typedef uint8_t u8; typedef uint16_t u16; +typedef uint32_t u32; +typedef volatile u16 vu16; +typedef volatile u32 vu32; +#define BIT(n) (1u << (n)) +#define IRQ_NDMA1 BIT(29) +#define PxiChannel_User0 0 +extern u32 REG_SCFG_CLK, REG_IF; +void swiDelay(unsigned delay); +void irqSet(u32 mask, void (*handler)(void)); +void irqEnable(u32 mask); +void irqDisable(u32 mask); +void irqClear(u32 mask); +void armDCacheFlush(const void *address, unsigned size); +void armDCacheInvalidate(const void *address, unsigned size); +u32 pxiSendAndReceive(unsigned channel, u32 command); #define I2C_CAM0 0x7A #define I2C_CAM1 0x78 #define I2C_PM 0x4A diff --git a/tools/capture/shim/nds/ndstypes.h b/tools/capture/shim/nds/ndstypes.h new file mode 100644 index 0000000..1f05ed0 --- /dev/null +++ b/tools/capture/shim/nds/ndstypes.h @@ -0,0 +1 @@ +#include From 55715b552fca659396e768485fbd9934648ef4c9 Mon Sep 17 00:00:00 2001 From: Addison King Date: Mon, 26 Oct 2026 03:37:42 -0400 Subject: [PATCH 3/4] fix: preserve camera failure diagnostics during recovery --- arm9/source/camera.c | 9 ++++++--- arm9/source/main.c | 4 ++-- tools/capture/camera_test.c | 30 ++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/arm9/source/camera.c b/arm9/source/camera.c index 674a49a..a6ffb3e 100644 --- a/arm9/source/camera.c +++ b/arm9/source/camera.c @@ -34,6 +34,7 @@ alignas(32) static u16 s_frames[CAM_FRAMES][256 * 192]; static bool s_streaming; static bool s_streamRequested; +static bool s_rearLight = true; static unsigned s_exposureLines; static unsigned s_exposureGain; static u16 s_exposureError[EXPOSURE_ERROR_FIELDS]; @@ -117,6 +118,7 @@ bool cameraActivate(Camera cam) { } bool cameraSetRearLight(bool enabled) { + s_rearLight = enabled; return pxiSendAndReceive(PXI_CAMERA, enabled ? CAM_REAR_LIGHT_ON : CAM_REAR_LIGHT_OFF) == 1; } @@ -202,12 +204,12 @@ static bool camApplyExposure(unsigned lines, unsigned gain) { } bool cameraSetExposure(unsigned lines, unsigned gain) { + for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) + s_exposureError[i] = 0; if(lines > CAM_EXPOSURE_MAX_LINES || gain > 3 || activeCamera == CAM_NONE) return false; bool resume = s_streamRequested; unsigned oldLines = s_exposureLines, oldGain = s_exposureGain; - for(unsigned i = 0; i < EXPOSURE_ERROR_FIELDS; i++) - s_exposureError[i] = 0; cameraStreamStop(); bool ok = camApplyExposure(lines, gain); if(resume && !cameraStreamStart()) { @@ -307,7 +309,8 @@ u16 *cameraNextFrame(void) { // picture forever. Callers poll once per vblank. if(s_streamRequested && ++s_callsWithoutFrame > 240) { s_callsWithoutFrame = 0; - cameraStreamStart(); + if(cameraStreamStart()) + cameraSetRearLight(s_rearLight); } return NULL; } diff --git a/arm9/source/main.c b/arm9/source/main.c index eedc1d4..73917fe 100644 --- a/arm9/source/main.c +++ b/arm9/source/main.c @@ -59,7 +59,7 @@ static void drainJobs(void); static void streamStart(void) { bool lightReady = cameraSetRearLight(s_rearLight); if(!cameraStreamRunning() && !cameraStreamStart()) - uiStatus("PREVIEW FAILED - TRY AGAIN"); + uiStatus(lightReady ? "PREVIEW FAILED - TRY AGAIN" : "PREVIEW AND REAR LIGHT FAILED"); else if(!lightReady) uiStatus("REAR LIGHT SETTING FAILED"); } @@ -2022,9 +2022,9 @@ int main(int argc, char **argv) { cameraSetExposure(0, 0); } uiCameraScreen(camera, fatInited); - streamStart(); // continuous viewfinder if(!exposureReady) uiStatus("SAVED EXPOSURE SETTING FAILED"); + streamStart(); // continuous viewfinder while(1) { u16 pressed = 0; diff --git a/tools/capture/camera_test.c b/tools/capture/camera_test.c index af9f044..11bf44d 100644 --- a/tools/capture/camera_test.c +++ b/tools/capture/camera_test.c @@ -21,9 +21,18 @@ u32 REG_SCFG_CLK, REG_IF; static unsigned sensorLines, sensorGain, exposureCalls; static unsigned failures; static bool failMode; +static bool failLight, light; +static unsigned lightWrites; u32 pxiSendAndReceive(unsigned channel, u32 command) { assert(channel == PXI_CAMERA); + if(command == CAM_REAR_LIGHT_ON || command == CAM_REAR_LIGHT_OFF) { + lightWrites++; + if(failLight) + return 0; + light = command == CAM_REAR_LIGHT_ON; + return 1; + } if(command & CAM_EXPOSURE_REQUEST) { exposureCalls++; if(failures) { @@ -111,5 +120,26 @@ int main(void) { assert(cameraDeactivate(CAM_INNER)); pollPreview(); assert(!cameraStreamRunning()); + assert(cameraExposureError(EXPOSURE_ERROR_STAGE)); + assert(!cameraSetExposure(64, 0)); + assert(!cameraExposureError(EXPOSURE_ERROR_STAGE)); + assert(!cameraExposureError(EXPOSURE_ERROR_REGISTER)); + + // A recovered preview retries a light write that failed alongside it. + assert(cameraActivate(CAM_OUTER)); + failLight = failMode = true; + assert(!cameraSetRearLight(true)); + assert(!cameraStreamStart()); + failLight = failMode = false; + pollPreview(); + assert(cameraStreamRunning() && light); + assert(cameraSetRearLight(false)); + unsigned writes = lightWrites; + cameraStreamStop(); + pollPreview(); + assert(!light && lightWrites == writes); + assert(cameraStreamStart()); + pollPreview(); + assert(!light && lightWrites == writes + 1); puts("camera: apply/rollback faults, preview retry, mode entry, capture and intentional stop passed"); } From 3de242468d9af87744dc17662226fc71d798251f Mon Sep 17 00:00:00 2001 From: Addison King Date: Tue, 27 Oct 2026 13:45:45 -0400 Subject: [PATCH 4/4] feat: add white balance control for photos - add auto plus three cool and three warm steps to advanced menu - apply warmth to captured YUV frames and approximate it in live preview - persist setting in config and cover warm/cool/clipping in tests --- README.md | 10 +++++-- arm9/include/white_balance.h | 10 +++++++ arm9/source/main.c | 48 +++++++++++++++++++++++------- arm9/source/white_balance.c | 29 ++++++++++++++++++ tools/capture/Makefile | 3 ++ tools/capture/white_balance_test.c | 32 ++++++++++++++++++++ 6 files changed, 119 insertions(+), 13 deletions(-) create mode 100644 arm9/include/white_balance.h create mode 100644 arm9/source/white_balance.c create mode 100644 tools/capture/white_balance_test.c diff --git a/README.md b/README.md index cf73b8c..4e8fda0 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A homebrew camera app for the Nintendo DSi. Fork of [Pk11's dsi-camera](https:// ## Features - Photos: raw 640x480 YUV from either camera, burst capture while held -- Advanced photo controls: real sensor integration (shutter) and analogue gain +- Advanced photo controls: real sensor integration (shutter), analogue gain, and white balance - Night burst: four full-resolution frames aligned and merged on the DSi into one photo - Rear camera light toggle; always off during Night Burst captures - Video: 256x192 with microphone audio at up to 10fps, recorded to a simple chunked container @@ -58,7 +58,7 @@ clean. ## Advanced controls Press **X**. Use up/down to select a row and left/right to adjust, -or tap the arrows beside a value. Press **A** on Shutter to return to Auto, +or tap the arrows beside a value. Press **A** on Shutter or White Balance to return to Auto, on Gain, Night Burst, Rear Light, or Timestamp to cycle/toggle, or on Reset to restore all settings. Press **B** or **X** to return to the viewfinder. The top screen stays live while adjusting. Gain is gray and cannot be selected until Shutter is manual. @@ -80,6 +80,10 @@ Rear Light is available whenever the outer camera is selected. locked during manual exposure. Sensor gain limits and quantization can limit the selected gain. Auto restores the original core registers, automatic exposure, gain, and white balance. This is not an ISO scale. +- **White Balance:** Auto, or three cooler and three warmer steps. This adjusts + photo color on the DSi relative to the sensor's current white balance; it is + not a calibrated color temperature or a sensor setting. The live preview is + an approximation of the saved result. - **Night Burst:** one shutter press captures four frames and saves one merged photo. Hold still; press B to cancel. Alignment compensates for small camera shifts, and changed pixels are rejected to limit ghosting. If alignment fails, @@ -99,7 +103,7 @@ integration until the bright surface has detail. Night Burst can reduce noise at that same exposure. The DSi's fixed wide-angle lens still limits lunar detail. There is no digital exposure/brightness adjustment in this pipeline. -Shutter, Gain, and Night Burst apply only to photos. Video restores each sensor's automatic +Shutter, Gain, White Balance, and Night Burst apply only to photos. Video restores each sensor's automatic exposure settings; returning to photo mode reapplies the saved photo controls. New settings default to Auto / 1x / Night Burst Off. Existing settings files remain compatible. diff --git a/arm9/include/white_balance.h b/arm9/include/white_balance.h new file mode 100644 index 0000000..82cb8b6 --- /dev/null +++ b/arm9/include/white_balance.h @@ -0,0 +1,10 @@ +#ifndef WHITE_BALANCE_H +#define WHITE_BALANCE_H + +#include +#include + +void whiteBalanceYuv(uint8_t *frame, size_t pixels, int warmth); +void whiteBalancePreview(const uint16_t *src, uint16_t *dst, size_t pixels, int warmth); + +#endif diff --git a/arm9/source/main.c b/arm9/source/main.c index 73917fe..7b0f888 100644 --- a/arm9/source/main.c +++ b/arm9/source/main.c @@ -1,6 +1,7 @@ #include "camera.h" #include "night.h" #include "version.h" +#include "white_balance.h" #include #include @@ -44,6 +45,7 @@ static const unsigned s_shutterLines[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 5 #define SHUTTER_COUNT (sizeof(s_shutterLines) / sizeof(s_shutterLines[0])) static unsigned s_shutter; static unsigned s_gain; +static int s_warmth; static bool s_nightBurst; static bool s_rearLight = true; static bool s_timestamp; // burn the capture time into saved pixels @@ -176,6 +178,8 @@ static void cfgLoad(void) { s_shutter = (unsigned)clamp(atoi(line + 8), 0, SHUTTER_COUNT - 1); else if(strncmp(line, "gain=", 5) == 0) s_gain = (unsigned)clamp(atoi(line + 5), 0, 3); + else if(strncmp(line, "warmth=", 7) == 0) + s_warmth = clamp(atoi(line + 7), -3, 3); else if(strncmp(line, "night_burst=", 12) == 0) s_nightBurst = atoi(line + 12) != 0; else if(strncmp(line, "rear_light=", 11) == 0) @@ -189,10 +193,11 @@ static void cfgSave(void) { if(!f) return; fprintf(f, - "timestamp=%d\nshutter=%u\ngain=%u\nnight_burst=%d\nrear_light=%d\n", + "timestamp=%d\nshutter=%u\ngain=%u\nwarmth=%d\nnight_burst=%d\nrear_light=%d\n", s_timestamp ? 1 : 0, s_shutter, s_gain, + s_warmth, s_nightBurst ? 1 : 0, s_rearLight ? 1 : 0); fclose(f); @@ -483,6 +488,7 @@ static bool captureRaw(u16 *previewGfx) { nightFree(stack); free(next); } + whiteBalanceYuv((u8 *)yuv, 640 * 480, s_warmth); if(s_timestamp) watermarkYuv(yuv, shotTime); if(previewGfx) @@ -1305,12 +1311,12 @@ static void uiCameraScreen(int cam, bool fatInited) { #define UI_ACCENT (BIT(15) | RGB15(31, 25, 5)) #define UI_PANEL (BIT(15) | RGB15(6, 6, 7)) -enum { ADV_SHUTTER, ADV_GAIN, ADV_NIGHT, ADV_REAR_LIGHT, ADV_TIMESTAMP, ADV_RESET, ADV_COUNT }; +enum { ADV_SHUTTER, ADV_GAIN, ADV_WHITE_BALANCE, ADV_NIGHT, ADV_REAR_LIGHT, ADV_TIMESTAMP, ADV_RESET, ADV_COUNT }; #define ADV_ROW_Y 52 -#define ADV_ROW_H 17 +#define ADV_ROW_H 14 static bool advancedRowEnabled(int row) { - if(row == ADV_SHUTTER || row == ADV_NIGHT) + if(row == ADV_SHUTTER || row == ADV_WHITE_BALANCE || row == ADV_NIGHT) return !s_videoMode; if(row == ADV_GAIN) return !s_videoMode && s_shutter; @@ -1329,8 +1335,12 @@ static int advancedMoveSelection(int selected, int direction) { static void uiAdvancedScreen(int selected) { uiHeader("ADVANCED"); uiTextCenter(43, s_videoMode ? "VIDEO - PHOTO CONTROLS LOCKED" : "PHOTO", UI_DIM); - const char *labels[] = {"SHUTTER", "GAIN", "NIGHT BURST", "REAR LIGHT", "TIMESTAMP", "RESET"}; - char shutter[16], gain[16]; + const char *labels[] = {"SHUTTER", "GAIN", "WHITE BALANCE", "NIGHT BURST", "REAR LIGHT", "TIMESTAMP", "RESET"}; + char shutter[16], gain[16], warmth[16]; + if(!s_warmth || s_videoMode) + strcpy(warmth, "AUTO"); + else + sprintf(warmth, "%s %d", s_warmth > 0 ? "WARM" : "COOL", abs(s_warmth)); if(!s_videoMode && s_shutter) sprintf(shutter, "%u LINE%s", s_shutterLines[s_shutter], s_shutterLines[s_shutter] == 1 ? "" : "S"); else @@ -1341,6 +1351,7 @@ static void uiAdvancedScreen(int selected) { strcpy(gain, "AUTO"); const char *values[] = {shutter, gain, + warmth, !s_videoMode && s_nightBurst ? "ON" : "OFF", s_camera == CAM_OUTER && s_rearLight ? "ON" : "OFF", s_timestamp ? "ON" : "OFF", @@ -1363,6 +1374,7 @@ static void uiAdvancedScreen(int selected) { uiTextCenter(171, s_videoMode ? "A: SET B/X: DONE" : "A: SET L/R: PHOTO B/X: DONE", UI_DIM); const char *hints[] = {"A: AUTO - MANUAL UNLOCKS GAIN", "HIGHER GAIN ADDS NOISE", + "A: AUTO < COOL / WARM >", "4 FRAMES - REAR LIGHT OFF", "OFF WHILE NIGHT BURST SHOOTS", "BURN DATE AND TIME INTO IMAGE", @@ -1408,8 +1420,12 @@ static bool advancedMenu(u16 *gfx) { continue; } u16 *frame = cameraNextFrame(); - if(frame) - memcpy(gfx, frame, VID_FRAME_SIZE); + if(frame) { + if(!s_videoMode && s_warmth) + whiteBalancePreview(frame, gfx, VID_W * VID_H, s_warmth); + else + memcpy(gfx, frame, VID_FRAME_SIZE); + } u16 pressed = keysDownRepeat(); bool tappedAction = false; if(keysDown() & KEY_TOUCH) { @@ -1439,6 +1455,7 @@ static bool advancedMenu(u16 *gfx) { if(!pressed) continue; unsigned oldShutter = s_shutter, oldGain = s_gain; + int oldWarmth = s_warmth; bool oldNight = s_nightBurst, oldTimestamp = s_timestamp, oldRearLight = s_rearLight; if(pressed & KEY_UP) selected = advancedMoveSelection(selected, -1); @@ -1456,6 +1473,11 @@ static bool advancedMenu(u16 *gfx) { s_gain = (s_gain + 1) % 4; else if(direction) s_gain = clamp((int)s_gain + direction, 0, 3); + } else if(selected == ADV_WHITE_BALANCE) { + if(action) + s_warmth = 0; + else if(direction) + s_warmth = clamp(s_warmth + direction, -3, 3); } else if(selected == ADV_NIGHT && (action || direction)) { s_nightBurst = direction ? direction > 0 : !s_nightBurst; } else if(selected == ADV_TIMESTAMP && (action || direction)) { @@ -1464,6 +1486,7 @@ static bool advancedMenu(u16 *gfx) { s_rearLight = direction ? direction > 0 : !s_rearLight; } else if(selected == ADV_RESET && action) { s_shutter = s_gain = 0; + s_warmth = 0; s_nightBurst = false; s_timestamp = false; s_rearLight = true; @@ -1476,6 +1499,7 @@ static bool advancedMenu(u16 *gfx) { if(!ok) { s_shutter = oldShutter; s_gain = oldGain; + s_warmth = oldWarmth; s_nightBurst = oldNight; s_timestamp = oldTimestamp; s_rearLight = oldRearLight; @@ -2045,8 +2069,12 @@ int main(int argc, char **argv) { } // Blit whatever the camera has produced since the last vblank. u16 *frame = cameraNextFrame(); - if(frame) - memcpy(gfx, frame, VID_FRAME_SIZE); + if(frame) { + if(!s_videoMode && s_warmth) + whiteBalancePreview(frame, gfx, VID_W * VID_H, s_warmth); + else + memcpy(gfx, frame, VID_FRAME_SIZE); + } pressed = keysDown(); } while(!pressed); diff --git a/arm9/source/white_balance.c b/arm9/source/white_balance.c new file mode 100644 index 0000000..ca46369 --- /dev/null +++ b/arm9/source/white_balance.c @@ -0,0 +1,29 @@ +#include "white_balance.h" + +static int clampByte(int value) { return value < 0 ? 0 : value > 255 ? 255 : value; } +static int roundedDivide(int value, int divisor) { + return value < 0 ? -((-value + divisor / 2) / divisor) : (value + divisor / 2) / divisor; +} +static int clamp5(int value) { return value < 0 ? 0 : value > 31 ? 31 : value; } + +void whiteBalanceYuv(uint8_t *frame, size_t pixels, int warmth) { + if(!warmth) + return; + for(size_t i = 0; i + 1 < pixels; i += 2) { + uint8_t *pair = frame + i * 2; + int light = (pair[0] + pair[2]) / 2; + pair[1] = clampByte(pair[1] - warmth * light / 64); + pair[3] = clampByte(pair[3] + warmth * light / 128); + } +} + +void whiteBalancePreview(const uint16_t *src, uint16_t *dst, size_t pixels, int warmth) { + for(size_t i = 0; i < pixels; i++) { + unsigned pixel = src[i]; + int r = pixel & 31, g = (pixel >> 5) & 31, b = (pixel >> 10) & 31; + int light = (r * 77 + g * 150 + b * 29) / 256; + r = clamp5(r + roundedDivide(warmth * light, 90)); + b = clamp5(b - roundedDivide(warmth * light, 37)); + dst[i] = (pixel & 0x8000) | (b << 10) | (g << 5) | r; + } +} diff --git a/tools/capture/Makefile b/tools/capture/Makefile index 8d77eaf..e98eea0 100644 --- a/tools/capture/Makefile +++ b/tools/capture/Makefile @@ -13,3 +13,6 @@ test: /tmp/dsi-camera-exposure-test $(CC) $(CFLAGS) -Wno-unused-parameter -Ishim -I$(ROOT)/arm7/include -I$(ROOT)/shared/include $(ROOT)/arm7/source/aptina.c rear_light_test.c -o /tmp/dsi-camera-rear-light-test /tmp/dsi-camera-rear-light-test + + $(CC) $(CFLAGS) -I$(ROOT)/arm9/include $(ROOT)/arm9/source/white_balance.c white_balance_test.c -o /tmp/dsi-camera-white-balance-test + /tmp/dsi-camera-white-balance-test diff --git a/tools/capture/white_balance_test.c b/tools/capture/white_balance_test.c new file mode 100644 index 0000000..5588f80 --- /dev/null +++ b/tools/capture/white_balance_test.c @@ -0,0 +1,32 @@ +#include "white_balance.h" + +#include +#include +#include + +int main(void) { + const uint8_t original[] = {0, 128, 0, 128, 128, 128, 128, 128, 255, 255, 255, 0}; + uint8_t frame[sizeof(original)]; + memcpy(frame, original, sizeof(frame)); + whiteBalanceYuv(frame, 6, 0); + assert(memcmp(frame, original, sizeof(frame)) == 0); + whiteBalanceYuv(frame, 6, 3); + assert(frame[1] == 128 && frame[3] == 128); + assert(frame[5] < 128 && frame[7] > 128); + assert(frame[0] == 0 && frame[4] == 128 && frame[8] == 255); + memcpy(frame, original, sizeof(frame)); + whiteBalanceYuv(frame, 6, -3); + assert(frame[5] > 128 && frame[7] < 128); + assert(frame[9] == 255 && frame[11] == 0); + uint16_t preview[] = {0x8000, 0xC210, 0xFFFF}; + uint16_t out[3]; + whiteBalancePreview(preview, out, 3, 3); + assert(out[0] == preview[0]); + assert((out[1] & 31) >= (preview[1] & 31)); + assert(((out[1] >> 10) & 31) < ((preview[1] >> 10) & 31)); + whiteBalancePreview(preview, out, 3, -3); + assert((out[1] & 31) <= (preview[1] & 31)); + assert(((out[1] >> 10) & 31) > ((preview[1] >> 10) & 31)); + puts("white balance: auto, warm, cool, black, clipping, preview"); + return 0; +}