diff --git a/README.md b/README.md index ac83a5b..665c7d5 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 -- 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) diff --git a/arm9/include/camera.h b/arm9/include/camera.h index 5c116ae..cb1b23e 100644 --- a/arm9/include/camera.h +++ b/arm9/include/camera.h @@ -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 @@ -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 } diff --git a/arm9/source/camera.c b/arm9/source/camera.c index b88240e..bd04c32 100644 --- a/arm9/source/camera.c +++ b/arm9/source/camera.c @@ -1,14 +1,71 @@ #include "camera.h" +#include "calico/arm/cache.h" +#include "calico/nds/irq.h" #include "calico/nds/pxi.h" #include +#include // 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 @@ -33,6 +90,7 @@ bool cameraInit() { REG_SCFG_CLK |= BIT(8); // CamExternal Clock = ON swiDelay(0x14); + s_modeValid = false; return val == 0x2280; } @@ -40,9 +98,12 @@ 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; @@ -50,40 +111,142 @@ bool cameraActivate(Camera cam) { } 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)®_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)®_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)®_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; } diff --git a/arm9/source/main.c b/arm9/source/main.c index 5b0938b..ff99f22 100644 --- a/arm9/source/main.c +++ b/arm9/source/main.c @@ -36,34 +36,53 @@ int clamp(int val, int min, int max) { return val < min ? min : (val > max ? max : val); } -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 bool s_timestamp; // burn the capture time into saved pixels +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 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); +// 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(); +} + +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(); + streamStop(); cameraDeactivate(s_camera); pmEnterSleep(); cameraActivate(s_camera); + if(wasStreaming) + streamStart(); } // --- Video recording: 256x192 RGB555 frames from preview mode + mic audio, // --- written as a custom .VID container by the worker thread. +// +// VID_MAGIC "DSIVID02" video chunks carry the capture time in milliseconds in +// their chunk index field, so playback is paced by when each frame was really +// taken. "DSIVID01" files (frame index only) still play. -#define VID_FPS 10 // what a DSi SD card can actually sustain (~1MB/s) +#define VID_FPS 10 // capture throttle; the sensor itself runs slower than this #define VID_W 256 #define VID_H 192 #define VID_FRAME_SIZE (VID_W * VID_H * 2) #define VID_SLOTS 24 // ~2.4MB ring; a frame is dropped if it fills #define AUD_CHUNKS 16 -#define VID_MAGIC "DSIVID01" +#define VID_MAGIC "DSIVID02" +#define VID_MAGIC_OLD "DSIVID01" #define CHUNK_VIDEO 1 #define CHUNK_AUDIO 2 #define MIC_RATE_HZ 16364 // MICEX rate div1 @@ -196,9 +215,13 @@ static int scanRaw(Photo **outPhotos) { FILE *vf = fopen(path, "rb"); if(vf) { u32 vh[10]; - if(fread(vh, sizeof(vh), 1, vf) == 1 && memcmp(vh, VID_MAGIC, 8) == 0) { - u32 vsec = vh[4] ? vh[8] / vh[4] : 0; - u32 asec = vh[6] ? vh[9] / vh[6] : 0; + if(fread(vh, sizeof(vh), 1, vf) == 1 && + (memcmp(vh, VID_MAGIC, 8) == 0 || memcmp(vh, VID_MAGIC_OLD, 8) == 0)) { + // DSIVID02 stores the real length; DSIVID01 and + // interrupted recordings fall back to frames/fps. + bool hasDuration = memcmp(vh, VID_MAGIC, 8) == 0 && vh[5] > 1; + u32 vsec = hasDuration ? (u32)(((u64)vh[5] + 500) / 1000) : (vh[4] ? vh[8] / vh[4] : 0); + u32 asec = vh[6] ? vh[9] / vh[6] : 0; ph[count].durSec = (u16)(vsec > asec ? vsec : asec); } fclose(vf); @@ -252,9 +275,9 @@ static u8 s_camKey[16]; // Video frame ring (producer: record loop; consumer: worker). static u16 s_vidRing[VID_SLOTS][VID_W * VID_H]; static Job s_vidJobs[VID_SLOTS]; -static u8 s_vidFree[VID_SLOTS]; // SPSC ring of free slot indices -static vu32 s_vidFreeHead = 0; // written by worker -static vu32 s_vidFreeTail = 0; // written by record loop +static vu8 s_vidFree[VID_SLOTS]; // SPSC ring of free slot indices +static vu32 s_vidFreeHead = 0; // written by worker +static vu32 s_vidFreeTail = 0; // written by record loop // Audio chunk pool (producer: record loop via micDrain; consumer: worker). typedef struct AudioChunk { @@ -262,7 +285,7 @@ typedef struct AudioChunk { alignas(32) u8 data[MIC_BUF_BYTES]; } AudioChunk; static AudioChunk s_audPool[AUD_CHUNKS]; -static u8 s_audFree[AUD_CHUNKS]; +static vu8 s_audFree[AUD_CHUNKS]; static vu32 s_audFreeHead = 0; static vu32 s_audFreeTail = 0; @@ -313,9 +336,9 @@ static int workerMain(void *arg) { if(f) { fwrite(job->buf, 1, RAW_SIZE, f); fclose(f); - sprintf(msg, "SAVED IMG_%04d", job->aux); + sprintf(msg, "SAVED IMG_%04d", (int)job->aux); } else { - sprintf(msg, "SAVE FAILED: IMG_%04d", job->aux); + sprintf(msg, "SAVE FAILED: IMG_%04d", (int)job->aux); } uiStatus(msg); @@ -338,10 +361,14 @@ static int workerMain(void *arg) { fwrite(hdr, sizeof(hdr), 1, s_vidFile); fwrite(job->buf, job->size, 1, s_vidFile); } - if(job->type == CHUNK_VIDEO) - s_vidFree[s_vidFreeHead++ % VID_SLOTS] = (u8)job->slot; - else - s_audFree[s_audFreeHead++ % AUD_CHUNKS] = (u8)job->slot; + // Publish the slot before the counter: the main thread can preempt us. + if(job->type == CHUNK_VIDEO) { + s_vidFree[s_vidFreeHead % VID_SLOTS] = (u8)job->slot; + s_vidFreeHead++; + } else { + s_audFree[s_audFreeHead % AUD_CHUNKS] = (u8)job->slot; + s_audFreeHead++; + } } s_jobsDone++; } @@ -361,16 +388,12 @@ static void drainJobs(void) { // 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. -static void captureRaw(u16 *previewGfx) { - // Wait for previous transfer to finish - while(cameraTransferActive()) - swiWaitForVBlank(); - +static bool captureRaw(u16 *previewGfx) { u16 *yuv = NULL; Job *job = NULL; for(;;) { - if(!yuv) - yuv = (u16 *)malloc(RAW_SIZE); + if(!yuv) // cache line aligned: the camera DMA writes around the cache + yuv = (u16 *)memalign(32, RAW_SIZE); if(!job) job = (Job *)malloc(sizeof(Job)); if(yuv && job) @@ -379,10 +402,13 @@ static void captureRaw(u16 *previewGfx) { swiWaitForVBlank(); } - cameraTransferStart(yuv, CAPTURE_MODE_CAPTURE); - while(cameraTransferActive()) - swiWaitForVBlank(); - cameraTransferStop(); + // 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. @@ -402,6 +428,7 @@ static void captureRaw(u16 *previewGfx) { while(!mailboxTrySend(&s_jobMailbox, (u32)job)) swiWaitForVBlank(); // queue full, wait for the worker s_jobsQueued++; + return true; } // --- Video playback: audio streams through a looping ring while frames are @@ -423,7 +450,8 @@ static bool vidReadChunk(FILE *f, u32 wantType, u32 *outIdx, void *buf, u32 bufS if(fread(hdr, sizeof(hdr), 1, f) != 1) return false; if(hdr[0] == wantType) { - if(hdr[2] > bufSz) // corrupt chunk of the type we want + // video chunks are fixed size; anything else is corruption + if(hdr[2] > bufSz || (wantType == CHUNK_VIDEO && hdr[2] != VID_FRAME_SIZE)) return false; *outIdx = hdr[1]; return fread(buf, hdr[2], 1, f) == 1; @@ -435,7 +463,9 @@ static bool vidReadChunk(FILE *f, u32 wantType, u32 *outIdx, void *buf, u32 bufS // Reads a video's first frame into gfx (which is also its display bitmap). static bool vidReadFirstFrame(FILE *f, u16 *gfx) { u32 hdr[10]; - if(fread(hdr, sizeof(hdr), 1, f) != 1 || memcmp(hdr, VID_MAGIC, 8) != 0) + if(fread(hdr, sizeof(hdr), 1, f) != 1) + return false; + if(memcmp(hdr, VID_MAGIC, 8) != 0 && memcmp(hdr, VID_MAGIC_OLD, 8) != 0) return false; u32 idx; return vidReadChunk(f, CHUNK_VIDEO, &idx, gfx, VID_FRAME_SIZE); @@ -450,7 +480,15 @@ static void playVideo(u16 *gfx, int num) { return; } u32 hdr[10]; - if(fread(hdr, sizeof(hdr), 1, fv) != 1 || memcmp(hdr, VID_MAGIC, 8) != 0) { + if(fread(hdr, sizeof(hdr), 1, fv) != 1) { + fclose(fv); + uiStatus("BAD VIDEO FILE"); + return; + } + // DSIVID02 stamps each video chunk with its capture time in ms; the older + // DSIVID01 used a frame index paced at a fixed fps. + bool timed = memcmp(hdr, VID_MAGIC, 8) == 0; + if(!timed && memcmp(hdr, VID_MAGIC_OLD, 8) != 0) { fclose(fv); uiStatus("BAD VIDEO FILE"); return; @@ -481,21 +519,23 @@ static void playVideo(u16 *gfx, int num) { armDCacheFlush(s_playRing, sizeof(s_playRing)); // Show the first frame immediately; stage the next one. - u16 *stage = (u16 *)malloc(VID_FRAME_SIZE); - u32 vIdx = 0, stageIdx = 0; + u16 *stage = (u16 *)malloc(VID_FRAME_SIZE); + u32 vIdx = 0; + u32 stageMs = 0; bool videoMore = vidReadChunk(fv, CHUNK_VIDEO, &vIdx, gfx, VID_FRAME_SIZE); + bool haveFrame = videoMore; bool stageFilled = false; if(videoMore) { u32 next; if(vidReadChunk(fv, CHUNK_VIDEO, &next, stage, VID_FRAME_SIZE)) { - stageIdx = next; + stageMs = timed ? next : (u32)((u64)next * 1000 / fps); stageFilled = true; } else { videoMore = false; } } - if(!videoMore && totalSamples == 0) { + if(!haveFrame && totalSamples == 0) { uiStatus("EMPTY VIDEO"); fclose(fa); fclose(fv); @@ -518,10 +558,12 @@ static void playVideo(u16 *gfx, int num) { timerStart(0, ClockDivider_1024, 0, NULL); // free-running counter timerElapsed(0); // zero the baseline - u32 durSec = totalFrames / fps; + u32 durMs = timed && hdr[5] > 1 ? hdr[5] : (u32)((u64)totalFrames * 1000 / fps); + u32 durSec = (u32)(((u64)durMs + 500) / 1000); if(totalSamples / rate > durSec) durSec = totalSamples / rate; - int lastSec = -1; + int lastSec = -1; + bool audioStopped = false; for(;;) { swiWaitForVBlank(); @@ -543,13 +585,14 @@ static void playVideo(u16 *gfx, int num) { } } - // Show the staged frame once its pacing slot is due. - if(stageFilled && (u64)played * fps >= (u64)stageIdx * rate) { + // Show the staged frame once its capture time is due. + u32 playedMs = (u32)((u64)played * 1000 / rate); + if(stageFilled && playedMs >= stageMs) { memcpy(gfx, stage, VID_FRAME_SIZE); stageFilled = false; u32 next; if(vidReadChunk(fv, CHUNK_VIDEO, &next, stage, VID_FRAME_SIZE)) { - stageIdx = next; + stageMs = timed ? next : (u32)((u64)next * 1000 / fps); stageFilled = true; } else { videoMore = false; @@ -557,13 +600,19 @@ static void playVideo(u16 *gfx, int num) { } bool audioDone = !audioMore && played >= (u64)fedChunks * PLAY_RING_HALF; - if(!videoMore && !stageFilled && audioDone) + if(audioDone && !audioStopped) { + // the looping channel would otherwise repeat the last half for as + // long as the video outlasts the audio + soundStop(BIT(4)); + audioStopped = true; + } + if(!videoMore && !stageFilled && audioDone && playedMs >= durMs) break; int sec = (int)(played / rate); if(sec != lastSec) { lastSec = sec; - char msg[32]; + char msg[40]; sprintf(msg, "PLAYING %d:%02d / %lu:%02lu", sec / 60, @@ -583,8 +632,9 @@ static void playVideo(u16 *gfx, int num) { } // Records video + mic audio to a .VID container until L/R is tapped again (or -// the lid closes / power is tapped). Frames are paced to VID_FPS on the wall -// clock; if the SD card falls behind, video frames are dropped (never audio). +// the lid closes / power is tapped). Frames are taken at the camera's own pace, +// throttled to VID_FPS, and each one is stamped with its capture time; if the +// SD card falls behind, video frames are dropped (never audio). static void recordVideo(u16 *gfx, int num) { char path[40]; vidPath(path, num); @@ -600,7 +650,7 @@ static void recordVideo(u16 *gfx, int num) { hdr[2] = VID_W; hdr[3] = VID_H; hdr[4] = VID_FPS; - hdr[5] = 1; + hdr[5] = 0; // clip length in ms, patched in at stop (was the fps denominator) hdr[6] = MIC_RATE_HZ; hdr[7] = 1; // s16le mono fwrite(hdr, sizeof(hdr), 1, f); @@ -613,13 +663,20 @@ static void recordVideo(u16 *gfx, int num) { s_vidFreeHead = s_vidFreeTail = 0; s_audFreeHead = s_audFreeTail = 0; s_audBlockIdx = s_audDropped = 0; - u32 framesKept = 0, framesDropped = 0, frameIdx = 0; + u32 framesKept = 0, framesDropped = 0; + + // Timestamps come off the same free-running clock playback uses, so frame + // times can't drift against the audio the way a vblank count does. Start it + // before the mic so audio can't lead video t=0. + timerStart(0, ClockDivider_1024, 0, NULL); + timerElapsed(0); + u32 recTicks = 0; // Start the ARM7 mic recorder (it NDMA-drains MICEX into the shared ring). pmMicSetAmp(true, PmMicGain_80); armDCacheFlush(s_micRing, sizeof(s_micRing)); s_micLastDone = 0; - u32 micAddr = (u32)s_micRing; + u32 micAddr = (u32)s_micRing; pxiSendAndReceive(PXI_CAMERA, CAM_MIC_ADDR_LO); pxiSendAndReceive(PXI_CAMERA, micAddr & 0xFFFF); pxiSendAndReceive(PXI_CAMERA, CAM_MIC_ADDR_HI); @@ -627,40 +684,65 @@ static void recordVideo(u16 *gfx, int num) { pxiSendAndReceive(PXI_CAMERA, CAM_MIC_START); pxiSendAndReceive(PXI_CAMERA, CAM_LED_BLINK); // recording indicator - // Paced by vblank count (~59.8Hz): keep a frame every keepEvery vblanks. - u32 vbl = 0; - u32 keepEvery = 60 / VID_FPS; - u32 lastKeep = 0; - int lastSec = -1; - bool stop = false; - time_t recTime = time(NULL); // watermark clock: start + elapsed seconds + // Use the viewfinder stream that is already running. Restarting it here + // costs a CAM_CNT flush and leaves the first frames blank, which shows up + // as a freeze right at the start of the clip. + u32 ovStart = cameraStreamOverruns(); + streamStart(); + + u32 keepEvery = 1000 / VID_FPS; + u32 nextKeep = 0; + u32 lastFrameMs = 0; // newest camera frame, for the worst-gap readout + u32 maxGapMs = 0; + bool firstFrame = true; + int lastSec = -1; + bool stop = false; + time_t recTime = time(NULL); // watermark clock: start + elapsed seconds while(!stop) { swiWaitForVBlank(); - vbl++; scanKeys(); if(keysDown() & (KEY_L | KEY_R) || (keysHeld() & KEY_LID) || pmShouldReset()) stop = true; - if(!cameraTransferActive()) { - if(vbl - lastKeep >= keepEvery) { - lastKeep = lastKeep ? lastKeep + keepEvery : vbl; - // frameIdx counts pacing slots (not kept frames), so dropped - // frames leave index gaps that playback/conversion can - // duplicate over — A/V sync survives drops. + recTicks += timerElapsed(0); + u32 nowMs = (u32)((u64)recTicks * 1000 / PLAY_TIMER_HZ); + + // The camera hands over whole frames; copying one to the screen keeps + // the viewfinder live, and the throttled copy goes into the ring. + u16 *frame = cameraNextFrame(); + if(frame) { + memcpy(gfx, frame, VID_FRAME_SIZE); + // Worst hole in the stream, including the wait before the first + // frame: a frozen head shows up here, not in D/O. + if(!lastFrameMs) { + if(nowMs > maxGapMs) + maxGapMs = nowMs; + } else if(nowMs - lastFrameMs > maxGapMs) { + maxGapMs = nowMs - lastFrameMs; + } + lastFrameMs = nowMs; + + if(firstFrame || nowMs >= nextKeep) { + firstFrame = false; + // Fixed schedule, not "100ms since the last kept frame": at a + // sensor rate just above VID_FPS that would skip every second + // frame and halve the recorded rate. + nextKeep += keepEvery; + if((s32)(nowMs - nextKeep) > 2 * (s32)keepEvery) + nextKeep = nowMs + keepEvery; // fell behind; don't burst if(s_vidFreeTail == s_vidFreeHead + VID_SLOTS) { framesDropped++; - frameIdx++; } else { int slot = s_vidFree[s_vidFreeTail++ % VID_SLOTS]; - memcpy(s_vidRing[slot], gfx, VID_FRAME_SIZE); + memcpy(s_vidRing[slot], frame, VID_FRAME_SIZE); // Stamped on the ring copy, never on gfx: the viewfinder // stays clean and the camera DMA can't race the text. if(s_timestamp) - watermarkFrame(s_vidRing[slot], recTime + vbl / 60); + watermarkFrame(s_vidRing[slot], recTime + nowMs / 1000); Job *job = &s_vidJobs[slot]; job->type = CHUNK_VIDEO; - job->aux = frameIdx++; + job->aux = nowMs; // capture time, ms into the clip job->slot = (u32)slot; job->size = VID_FRAME_SIZE; job->buf = s_vidRing[slot]; @@ -673,12 +755,11 @@ static void recordVideo(u16 *gfx, int num) { } } } - cameraTransferStart(gfx, CAPTURE_MODE_PREVIEW); // re-arm viewfinder } micDrain(); - int sec = (int)(vbl / 60); + int sec = (int)(nowMs / 1000); if(sec != lastSec) { lastSec = sec; char msg[24]; @@ -687,19 +768,26 @@ static void recordVideo(u16 *gfx, int num) { } } + timerStop(0); pxiSendAndReceive(PXI_CAMERA, CAM_MIC_STOP); pxiSendAndReceive(PXI_CAMERA, CAM_LED_OFF); pmMicSetAmp(false, 0); - micDrain(); // pick up the last completed buffers - while(cameraTransferActive()) - swiWaitForVBlank(); - cameraTransferStop(); + micDrain(); // pick up the last completed buffers + streamStop(); // no waiting on a possibly wedged DMA // Let the worker finish the remaining chunks, then patch the totals. uiStatus("SAVING..."); while(JOBS_PENDING) swiWaitForVBlank(); - hdr[8] = frameIdx; // timeline length in frames (incl. dropped slots) + u32 durMs = (u32)((u64)recTicks * 1000 / PLAY_TIMER_HZ); + u32 fps10 = durMs ? (framesKept * 10000 + durMs / 2) / durMs : VID_FPS * 10; // tenths + if(fps10 == 0) + fps10 = 1; + hdr[4] = (fps10 + 5) / 10; // measured fps, for the header + if(hdr[4] == 0) + hdr[4] = 1; + hdr[5] = durMs; // exact length; frames/fps is rounded and reads short + hdr[8] = framesKept; hdr[9] = (s_audBlockIdx * MIC_BUF_BYTES) / 2; // total samples fseek(f, 0, SEEK_SET); fwrite(hdr, sizeof(hdr), 1, f); @@ -718,11 +806,26 @@ static void recordVideo(u16 *gfx, int num) { fclose(f); } - char msg[36]; - sprintf(msg, "SAVED VID_%04d%s", num, framesDropped ? " (DROPPED FRAMES)" : ""); + // fps and drop counts are the quickest way to see how the capture went. + // uiCameraScreen() clears the status strip right after this returns, so + // stash it and let the caller re-print it. + u32 gapS = maxGapMs / 1000; + if(gapS > 999) + gapS = 999; + char msg[48]; + snprintf(msg, + sizeof(msg), + "VID_%04d %lu.%luFPS D:%lu A:%lu O:%lu G:%lu.%lus", + num, + (unsigned long)(fps10 / 10), + (unsigned long)(fps10 % 10), + (unsigned long)framesDropped, + (unsigned long)s_audDropped, + (unsigned long)(cameraStreamOverruns() - ovStart), + (unsigned long)gapS, + (unsigned long)((maxGapMs / 100) % 10)); uiStatus(msg); - if(s_audDropped) - uiStatus("SAVED VID (DROPPED AUDIO)"); + snprintf(s_savedMsg, sizeof(s_savedMsg), "%s", msg); uiSpace(); } @@ -1619,6 +1722,7 @@ int main(int argc, char **argv) { Camera camera = CAM_OUTER; s_camera = camera; cameraActivate(camera); + streamStart(); // continuous viewfinder uiCameraScreen(camera, fatInited); @@ -1636,30 +1740,23 @@ int main(int argc, char **argv) { scanKeys(); // Lid closed: shut the camera off and sleep until it reopens. if(keysHeld() & KEY_LID) { - while(cameraTransferActive()) - swiWaitForVBlank(); - cameraTransferStop(); - cameraDeactivate(camera); - drainJobs(); // don't sleep with photos half-written - pmEnterSleep(); - cameraActivate(camera); + drainJobs(); // don't sleep with writes half-finished + lidSleep(); continue; } - if(!cameraTransferActive()) - cameraTransferStart(gfx, CAPTURE_MODE_PREVIEW); + // Blit whatever the camera has produced since the last vblank. + u16 *frame = cameraNextFrame(); + if(frame) + memcpy(gfx, frame, VID_FRAME_SIZE); pressed = keysDown(); } while(!pressed); if(pressed & KEY_A) { - // Wait for previous transfer to finish - while(cameraTransferActive()) - swiWaitForVBlank(); - cameraTransferStop(); - // Switch camera camera = camera == CAM_INNER ? CAM_OUTER : CAM_INNER; s_camera = camera; cameraActivate(camera); + streamStart(); uiCameraScreen(camera, fatInited); } else if(fatInited && pressed & KEY_Y) { @@ -1673,14 +1770,17 @@ int main(int argc, char **argv) { } else if(fatInited && pressed & (KEY_L | KEY_R)) { if(s_videoMode) { // Tap L/R to record, tap again to stop. - while(cameraTransferActive()) - swiWaitForVBlank(); 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 } 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); @@ -1688,15 +1788,15 @@ int main(int argc, char **argv) { // 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(); uiSpace(); // refresh the free-space line after the burst } } else if(fatInited && pressed & KEY_SELECT) { // Stop the live preview and browse photos. - while(cameraTransferActive()) - swiWaitForVBlank(); - cameraTransferStop(); + streamStop(); drainJobs(); // so the newest shots are in the list viewer(gfx, camera); + streamStart(); } else if(pressed & KEY_START) { // Disable camera so the light turns off cameraDeactivate(camera); diff --git a/tools/convert.sh b/tools/convert.sh index 5a9710e..715b78a 100755 --- a/tools/convert.sh +++ b/tools/convert.sh @@ -23,44 +23,83 @@ for f in VID_*.VID; do [ -f "$f" ] || continue mp4="vid/${f%.*}.mp4" [ -f "$mp4" ] && continue - python3 - "$f" "$mp4" <<'EOF' -import struct, subprocess, sys, os, tempfile + if python3 - "$f" "$mp4" <<'EOF' +import math, struct, subprocess, sys, os, tempfile src, dst = sys.argv[1], sys.argv[2] d = open(src, 'rb').read() -if len(d) < 40 or d[:8] != b'DSIVID01': +MAGICS = (b'DSIVID01', b'DSIVID02') +if len(d) < 40 or d[:8] not in MAGICS: print(f'{src}: empty or not a dsi-camera video, skipping') sys.exit(0) +timed = d[:8] == b'DSIVID02' # chunk index is a capture time in ms w, h, fps, den, rate, fmt, frames_total, samp_total = struct.unpack('<8I', d[8:40]) +duration_ms = den if timed and den > 1 else 0 +fps = fps or 10 -# Walk chunks; duplicate the previous frame over index gaps (dropped frames). -off, frames, pcm, lv = 40, [], b'', -1 +# Walk chunks, then lay frames out on a constant-rate timeline: DSIVID02 chunks +# carry the real capture time (so a slow or jittery capture still plays at the +# right speed), DSIVID01 chunks carry a frame index. +off, frames, stamps, pcm = 40, [], [], b'' while off + 12 <= len(d): t, idx, sz = struct.unpack('<3I', d[off:off+12]) off += 12 if t == 1: - if frames and idx > lv + 1: - frames.extend([frames[-1]] * (idx - lv - 1)) - lv = idx - frames.append(d[off:off+sz]) + chunk = d[off:off + sz] + if len(chunk) == w * h * 2: # fixed-size frames; anything else is bad + frames.append(chunk) + stamps.append(idx) elif t == 2: pcm += d[off:off+sz] off += sz -tmp = tempfile.mkdtemp() -v = os.path.join(tmp, 'v.rgb') -a = os.path.join(tmp, 'a.pcm') -open(v, 'wb').write(b''.join(frames)) -open(a, 'wb').write(pcm) -subprocess.run([ - 'ffmpeg', '-loglevel', 'error', '-y', - '-f', 'rawvideo', '-pix_fmt', 'bgr555', '-s', f'{w}x{h}', '-r', str(fps), '-i', v, - '-f', 's16le', '-ar', str(rate), '-ac', '1', '-i', a, - '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', dst, -], check=True) -os.remove(v); os.remove(a); os.rmdir(tmp) +if not frames: + print(f'{src}: no video frames, skipping') + sys.exit(1) + +if timed and len(stamps) > 1 and stamps[-1] > stamps[0] + 50: + # Real rate of this clip, from its own timestamps. Clamped so a two-frame + # clip can't produce a nonsense rate. + fps = max(1.0, min(60.0, (len(stamps) - 1) * 1000.0 / (stamps[-1] - stamps[0]))) + +slots = [round(s * fps / 1000.0) for s in stamps] if timed else stamps +out, lv = [], None +for slot, fr in zip(slots, frames): + if lv is None: + # audio starts before the first frame; hold that frame so the two + # tracks stay lined up (clamped: a corrupt stamp shouldn't eat ram) + out.extend([fr] * min(max(0, slot), 600)) + elif slot <= lv: + continue # two frames in the same slot: keep the first + else: + out.extend([out[-1]] * min(slot - lv - 1, 600)) # hold the last frame over a gap + lv = slot + out.append(fr) +# Hold the last frame through stop, including a stalled camera at the end. +end_slot = math.ceil(duration_ms * fps / 1000.0) +out.extend([out[-1]] * min(max(0, end_slot - len(out)), 600)) +frames = out + +with tempfile.TemporaryDirectory() as tmp: + v = os.path.join(tmp, 'v.rgb') + open(v, 'wb').write(b''.join(frames)) + cmd = [ + 'ffmpeg', '-loglevel', 'error', '-y', + '-f', 'rawvideo', '-pix_fmt', 'bgr555', '-s', f'{w}x{h}', '-r', f'{fps:.3f}', '-i', v, + ] + if pcm: + a = os.path.join(tmp, 'a.pcm') + open(a, 'wb').write(pcm) + cmd += ['-f', 's16le', '-ar', str(rate), '-ac', '1', '-i', a] + cmd += ['-c:v', 'libx264', '-pix_fmt', 'yuv420p'] + if pcm: + cmd += ['-c:a', 'aac'] + cmd.append(dst) + subprocess.run(cmd, check=True) EOF - echo "$f -> $mp4" - new=$((new + 1)) + then + echo "$f -> $mp4" + new=$((new + 1)) + fi done echo "$new new video(s) converted."