Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
- Video: 256x192 @ 10fps with microphone audio, recorded to a simple chunked container
- 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
- Export photos to the stock DSi Camera album (signed, shows up like a real photo)
Expand Down
35 changes: 29 additions & 6 deletions arm9/include/camera.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ extern "C" {
#define REG_NDMA1BCNT *(vu32 *)0x04004130
#define REG_NDMA1CNT *(vu32 *)0x04004138

// Preview frame (256x192 RGB555) in bytes and NDMA words.
#define CAM_PREVIEW_SIZE (256 * 192 * 2)
#define CAM_PREVIEW_WORDS (CAM_PREVIEW_SIZE / 4)

typedef enum { CAM_NONE, CAM_INNER, CAM_OUTER } Camera;

// Initializes the cameras
Expand All @@ -30,14 +34,33 @@ bool cameraActivate(Camera cam);
// Deactivates a camera
bool cameraDeactivate(Camera cam);

// Starts transfer from the camera to the specified RAM/VRAM using NDMA 1
void cameraTransferStart(u16 *dst, CaptureMode mode);
// 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);

// 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
// mode (256x192) is supported; call cameraCapture for 640x480 shots.
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.
bool cameraStreamRunning(void);

// Stops camera transfer
void cameraTransferStop(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
// away. Cache is invalidated for you.
u16 *cameraNextFrame(void);

// Checks if a camera transfer is active
bool cameraTransferActive(void);
// Number of camera FIFO overrun episodes (data dropped between re-arms) since
// boot. Never reset; the recorder reports the delta for its clip.
u32 cameraStreamOverruns(void);

#ifdef __cplusplus
}
Expand Down
199 changes: 181 additions & 18 deletions arm9/source/camera.c
Original file line number Diff line number Diff line change
@@ -1,14 +1,71 @@
#include "camera.h"

#include "calico/arm/cache.h"
#include "calico/nds/irq.h"
#include "calico/nds/pxi.h"

#include <nds.h>
#include <stddef.h>

// https://problemkaputt.de/gbatek-dsi-cameras.htm

Camera activeCamera = CAM_NONE;
CaptureMode activeMode = CAPTURE_MODE_PREVIEW;

// NDMA1 is the camera channel. "Start by hardware, repeat until TCNT" with
// TCNT = one whole frame is the documented camera usage: the channel raises an
// IRQ after the last block, and the IRQ re-arms it into the other buffer.
//
// The important part is what we do NOT do: CAM_CNT.15 (transfer enable) is set
// once and left alone while streaming. Clearing it per frame - which is what
// the older code did, to make the config bits writeable - plus the implicit
// CAM_CNT.5 flush ("flush CAM_DAT till next Camera Vblank") throws away most of
// a sensor frame on every capture, which is why preview and recording ran at
// about half the sensor's frame rate.
#define CAM_NDMA_CFG 0xCB044000u // start | irq enable | camera timing | 16-word blocks | fixed src
#define CAM_NDMA_ONE 0x8B044000u // same, without the completion IRQ

// Frame buffers in main RAM. The ISR writes the next frame into one while the
// ARM9 reads another; the third absorbs a consumer that is a frame late.
// Cache line aligned so invalidating a finished frame never touches
// neighbouring data.
#define CAM_FRAMES 3
alignas(32) static u16 s_frames[CAM_FRAMES][256 * 192];

static bool s_streaming;
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
static volatile u32 s_overruns; // CAM_CNT.4 episodes seen in the ISR
static bool s_overrunSeen; // CAM_CNT.4 stays latched until a flush
static u32 s_seen; // frames handed to the caller so far
static u32 s_callsWithoutFrame; // stall watchdog for cameraNextFrame

// Re-arm straight from the completion IRQ so the gap between frames is a few
// microseconds, not the time it takes the main loop to notice and copy.
static void camDmaIsr(void) {
int next = s_fill + 1;
if(next == CAM_FRAMES)
next = 0;
s_fill = (u8)next;
s_frameCount++;

// Bit 4 latches until it is cleared with bit 5, so count episodes, not
// every frame that happens to still see it.
if(REG_CAM_CNT & BIT(4)) {
if(!s_overrunSeen)
s_overruns++;
s_overrunSeen = true;
} else {
s_overrunSeen = false;
}

REG_NDMA1DAD = (u32)s_frames[next];
REG_NDMA1TCNT = CAM_PREVIEW_WORDS;
REG_NDMA1WCNT = 512; // 4 scanlines per block
REG_NDMA1CNT = CAM_NDMA_CFG;
}

bool cameraInit() {
REG_SCFG_CLK |= BIT(2); // CamInterfaceClock = ON
REG_CAM_MCNT = 0; // Camera Module Control
Expand All @@ -33,57 +90,163 @@ bool cameraInit() {
REG_SCFG_CLK |= BIT(8); // CamExternal Clock = ON
swiDelay(0x14);

s_modeValid = false;
return val == 0x2280;
}

bool cameraActivate(Camera cam) {
if(activeCamera != CAM_NONE)
cameraDeactivate(activeCamera);

cameraStreamStop();

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
return true;
} else {
return false;
}
}

bool cameraDeactivate(Camera cam) {
cameraStreamStop();

u32 command = (cam == CAM_INNER) ? CAM0_DEACTIVATE : CAM1_DEACTIVATE;
if(pxiSendAndReceive(PXI_CAMERA, command) == command) {
activeCamera = CAM_NONE;
s_modeValid = false;
return true;
} else {
return false;
}
}

void cameraTransferStart(u16 *dst, CaptureMode mode) {
// Waits for NDMA1 to go idle, bailing out after roughly `vblanks` frames so a
// wedged camera can never hang the app. Always leaves the channel disabled.
static bool camWaitDone(u32 vblanks) {
for(u32 i = 0; i < vblanks; i++) {
if(!(REG_NDMA1CNT & BIT(31))) {
REG_NDMA1CNT = 0;
return true;
}
swiWaitForVBlank();
}
REG_NDMA1CNT = 0;
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 void camConfigure(CaptureMode mode) {
bool preview = mode == CAPTURE_MODE_PREVIEW;

if(mode != activeMode) {
if(mode != activeMode || !s_modeValid) {
pxiSendAndReceive(PXI_CAMERA, preview ? CAM_SET_MODE_PREVIEW : CAM_SET_MODE_CAPTURE);
activeMode = mode;
activeMode = mode;
s_modeValid = true;
}

if(REG_CAM_CNT & BIT(15))
cameraTransferStop();

if(preview) // enable YUV-to-RGB555 and set "scanline count - 1" to 3
REG_CAM_CNT &= ~BIT(15); // allow changing params
if(preview) // YUV-to-RGB555 and "scanline count - 1" = 3
REG_CAM_CNT |= 0x2003;
else // raw YUV and "scaline count -1" to 0
else // raw YUV and "scanline count - 1" = 0
REG_CAM_CNT &= ~0x2003;
REG_CAM_CNT |= BIT(5); // flush data fifo
REG_CAM_CNT |= BIT(15); // start transfer
REG_NDMA1SAD = (u32)&REG_CAM_DAT; // source CAM_DTA
REG_NDMA1DAD = (u32)dst; // dest RAM/VRAM
REG_NDMA1TCNT = (preview ? 256 * 192 : 640 * 480) / 2; // total length in words
REG_NDMA1WCNT = preview ? 512 : 320; // block length in words
REG_NDMA1BCNT = 2; // timing interval or so
REG_NDMA1CNT = 0x8B044000; // start camera DMA
REG_CAM_CNT |= BIT(5); // clear overrun flag, flush till next camera vblank
REG_CAM_CNT |= BIT(15);
}

bool cameraCapture(u16 *dst, CaptureMode mode) {
cameraStreamStop();
camConfigure(mode);

u32 bytes = mode == CAPTURE_MODE_PREVIEW ? CAM_PREVIEW_SIZE : (640 * 480 * 2);

// Clean the destination before the DMA: a reuse of this buffer can leave
// dirty lines that would otherwise be evicted over the incoming frame.
armDCacheFlush(dst, bytes);

REG_NDMA1SAD = (u32)&REG_CAM_DAT;
REG_NDMA1DAD = (u32)dst;
REG_NDMA1TCNT = (mode == CAPTURE_MODE_PREVIEW ? CAM_PREVIEW_WORDS : (640 * 480) / 2);
REG_NDMA1WCNT = (mode == CAPTURE_MODE_PREVIEW ? 512 : 320);
REG_NDMA1BCNT = 2;
REG_NDMA1CNT = CAM_NDMA_ONE;

bool ok = camWaitDone(120); // ~2s at 60Hz
if(ok) // the DMA wrote around the cache, drop whatever the CPU still has
armDCacheInvalidate(dst, bytes);
REG_CAM_CNT &= ~BIT(15);
return ok;
}

bool cameraStreamStart(void) {
if(activeCamera == CAM_NONE) // nothing to stream from
return false;

cameraStreamStop();

camConfigure(CAPTURE_MODE_PREVIEW);

// 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.
armDCacheFlush(s_frames, sizeof(s_frames));

s_fill = 0;
s_frameCount = 0;
s_seen = 0;
s_overrunSeen = false;
s_callsWithoutFrame = 0;
s_streaming = true;

REG_IF = IRQ_NDMA1; // drop a completion latched while the IRQ was masked
irqSet(IRQ_NDMA1, camDmaIsr);
irqEnable(IRQ_NDMA1);

REG_NDMA1SAD = (u32)&REG_CAM_DAT;
REG_NDMA1DAD = (u32)s_frames[0];
REG_NDMA1TCNT = CAM_PREVIEW_WORDS;
REG_NDMA1WCNT = 512;
REG_NDMA1BCNT = 2;
REG_NDMA1CNT = CAM_NDMA_CFG;
return true;
}

void cameraStreamStop(void) {
// Mask first so the ISR can't re-arm the channel behind our back, then
// shut it down and drop any completion that latched in between.
irqDisable(IRQ_NDMA1);
REG_NDMA1CNT = 0;
REG_CAM_CNT &= ~BIT(15);
REG_IF = IRQ_NDMA1;
irqClear(IRQ_NDMA1);
s_streaming = false;
}

u16 *cameraNextFrame(void) {
u32 count = s_frameCount;
if(count == s_seen || count == 0) {
// 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) {
s_callsWithoutFrame = 0;
cameraStreamStart();
}
return NULL;
}

s_callsWithoutFrame = 0;

// With three buffers the frame we hand out is two completions away from
// being written again; anything older is already gone.
s_seen = count;
u16 *f = s_frames[(count - 1) % CAM_FRAMES];
armDCacheInvalidate(f, CAM_PREVIEW_SIZE);
return f;
}

void cameraTransferStop() { REG_CAM_CNT &= ~BIT(15); }
u32 cameraStreamOverruns(void) { return s_overruns; }

bool cameraTransferActive() { return REG_NDMA1CNT & BIT(31); }
bool cameraStreamRunning(void) { return s_streaming; }
Loading
Loading