Mobile engineering · 9 min read
Stamping video on the phone without putting the recording at risk
How Wherecam burns a map and address stamp into recorded video on Android and iOS, and why the original file is never opened for writing.
Published · By Kumar, QuantumPlug Technologies LLP

Wherecam stamps photos and videos with the map, address, date, time and weather. For a photo the work is contained: render the stamp over the image, snapshot it, save the copy. Video is a different problem. The stamp has to appear on every frame, which means re-encoding minutes of footage on a phone that may be low on storage, may be sent to the background by a phone call and may be killed by the operating system half-way through. The recording is also often the only copy of something that happened. The working conventions for the project put it plainly: offline reliability beats every other feature, and a capture must never be lost. This is how we built video stamping around that rule.
Start with what can go wrong
The obvious design is to record, re-encode the file with the stamp drawn on it, and replace the original. Each step of that design has a way to lose the video. So we split the work into two jobs that do not depend on each other. First, the recording is moved into durable storage and added to the library, exactly as the camera wrote it. Then, separately, a background job makes a stamped copy. The comment on saveCapture states the contract: a video’s stamped copy is a background job started only once the video is in the library, so a failed copy never costs the recording.
Every decision below follows from listing the failures first and making sure each one ends with the original intact.
- The camera writes to the operating system’s cache, which can be purged at any time.
- The process can be killed mid-recording or mid-export.
- iOS stops an export when the app leaves the foreground.
- The phone can run out of space, since a re-encode briefly needs room for a second copy.
- A codec or file layout can turn out to be unsupported on a particular device.
Getting the footage out of the cache while the camera is still rolling
We use Vision Camera, which writes each recording to a file in the cache. Recorders are created with maxDuration: DEFAULT_SEGMENT_SECONDS, set to 15 minutes. That is long enough that almost every video is a single ordinary MP4 with no gap in it. A longer video is still recorded, as several camera files one after another.
createVideoArtifact folds each segment, as soon as it closes, into one durable file under the app’s Documents directory, while the camera is already recording the next one. The copy runs in 512 KB chunks, and every eight chunks, about 4 MB, it waits on a setTimeout rather than a resolved promise. The comment explains why: a resolved promise only drains microtasks, which would leave the stop button unanswered for the length of a segment, while a timer lets native callbacks through too. Once a segment’s bytes are inside the artefact, the camera’s own file is deleted, because a long recording is large enough that keeping both copies can fill the device.
After every fold the app writes a small journal next to the artefact, holding the stamp readings frozen when recording started. If the process dies, startup recovery in recovery.ts finds media under captures/ that has no library row and adopts it, using the journal when there is one. Recovery never deletes anything. Even an iOS recording that ended with an error because a call came in is kept, since the file written up to then normally plays and it is the only copy of that footage.
Cutting the recording back into playable files
A long video is now several MP4 files written end to end, which no player can open past the first. Before stamping, the job has to find where each camera file starts. splitConcatenatedMp4 does this by walking the top-level MP4 boxes. Every box begins with a length and a four-character type, and every file the camera writes opens with an ftyp box, so reading box headers alone finds each boundary without touching the media in between. A long recording needs only a few dozen header reads, made through a random-access file handle.
The walker refuses anything it cannot be sure of. A box with a declared size of 1 carries a 64-bit size in the next eight bytes, and a size that is impossible or not a safe integer is an error. A size of 0 means the box runs to the end of the file, which is only honest for the last box of the last segment, so it is accepted there and nowhere else. Every type must be four printable ASCII characters, no box may run past the end of the file, and every segment must contain a moov box. Any failure throws Mp4LayoutError, which the job classifies as unsupported. As the comment puts it, a wrong cut produces a corrupt copy, and the original is always there to fall back on.
There is a second check above the walker. The capture records how many camera files went into it, and the runner compares that segmentCount with the number of ranges the walk found. A different count means the walk found something else, and the job stops rather than stamp a copy cut from it.
Drawing the stamp once, in React
The stamp itself is a React Native component. The same StampCard draws the live preview on the camera and the stamp burned into a saved photo, across all 12 templates. We wanted video to carry exactly the same pixels, not a second implementation in Kotlin and a third in Swift that would drift apart over time.
So the native side never draws the stamp. VideoStampHost mounts StampBurnIn off screen, 20,000 points above the visible area, on a transparent canvas the shape of the video frame, sized by the same stampCanvasSize function the photo copy uses, which caps the long edge at 2,048 pixels. The stamp can include map tiles and a logo, which load asynchronously. A count gate waits for each image’s own load event, for up to five seconds; past that, the stamp says the map is unavailable rather than snapshot blank tiles. The host then waits two animation frames and captures the view to a PNG, which keeps everything outside the stamp transparent so the video shows through.
Because only a mounted view can draw, the host registers itself as the renderer while it is mounted and unregisters when it is not. A job that runs with no renderer is treated as interrupted, not failed. The readings on the stamp are the ones frozen when recording started, and the style is frozen into the job when the video is saved, so a video and the photos taken in the same session carry the same stamp.
Compositing on Android with Media3
The native module has two calls. prepare copies each segment’s byte range out of the recording into a scratch file, using FileChannel.transferTo and forcing the result to disk, and returns the upright frame size. Decoded frames reach the effects already rotated for display, so the size is read with MediaMetadataRetriever and width and height are swapped when the rotation is 90 or 270 degrees. The recording itself is only ever opened for reading.
compose builds a Media3 Transformer on its own HandlerThread. Transformer must be built, started and called back on one looper, and that cannot be the JavaScript or main thread, because a two-minute export runs for tens of seconds. Each segment gets the same two effects: Presentation.createForWidthAndHeight with LAYOUT_SCALE_TO_FIT, so a segment with a different size is letterboxed to the first rather than failing the export, and an OverlayEffect holding a static BitmapOverlay. The PNG was drawn at screen density, and a BitmapOverlay draws at its own pixel size, so the bitmap is scaled to the frame before it is used. Declaring an audio track on the sequence makes Transformer fill a silent segment with silence, which means a recording whose microphone permission changed part-way still exports.
Quality needed explicit attention. The stamped copy replaces the recording in the gallery, but Media3’s default bitrate is about half of what a phone camera writes at 1080p, which visibly softens detail. We read the source’s video bitrate, frame rate and audio bitrate, falling back to the whole file’s rate when the video track does not state one, and request the larger of the source bitrate and a floor of 0.2 bits per pixel per frame: about 12 Mbps at 1080p30 and 50 Mbps at 4K30, clamped between 4 and 80 Mbps. Audio gets at least 192 kbps, up to 320. Encoder fallback is enabled, so an encoder that cannot reach the requested rate lowers it rather than fails.
Compositing on iOS with AVFoundation
On iOS the segments are joined in an AVMutableComposition, inserting each one’s video time range at a running cursor. Audio is inserted at the same cursor but clipped to the video’s duration, because an audio tail that runs past it would push every later segment’s sound out of sync.
The camera’s preferredTransform can carry a translation that assumes a different origin. We apply the transform to the frame’s bounds and translate by the resulting origin, which keeps the rotated frame inside the render area. The stamp is a CALayer whose contents are the PNG, stacked over the video layer through AVVideoCompositionCoreAnimationTool, and the export uses the highest-quality preset at the source’s own frame rate.
The same errors on both platforms
The Kotlin and Swift modules declare exception classes with the same names, which Expo turns into the same JavaScript error codes: ERR_VIDEO_UNSUPPORTED, ERR_NO_SPACE and, on iOS, ERR_STAMP_INTERRUPTED. Android walks the cause chain of an error looking for ENOSPC, and maps Media3’s decoder and encoder errors to unsupported. iOS maps AVError codes: a full disk to no space, an interrupted session or reset media services to interrupted, a missing decoder to unsupported. On the JavaScript side, classifyFailure reduces all of this to four outcomes: unsupported, no space, interrupted or failed. Anything unrecognised is a plain failure, which is retried.
A job that is allowed to fail
Each stamped copy is a small record stored in the app’s key-value table rather than a table of its own: a stamped copy is a convenience that can always be made again, so it does not earn a schema migration. The state machine around it is a set of pure functions with their own tests, and the rules are deliberate.
- An attempt is counted when it starts, not when it fails. An export that crashes the app never reaches the failure handler, and counting up front is what stops such a video from crashing every launch.
- An interruption is refunded, because leaving the app stops an iOS export and is nobody’s fault. A crash is not.
- Retries wait 30 seconds, five minutes and then 30 minutes, short because attempts only run while the app is open. After three automatic attempts, or at once for an unsupported video, the job waits for the person to ask again, which resets the budget.
- On launch, a job still marked as running belonged to a process that has died, and goes back to pending or, if its budget is spent, to failed.
- Before starting, the job checks that free space is at least 2.2 times the recording, since segment copies and the output exist alongside the original.
- When gallery saving is on, the save is held back until the job settles, then made once: with the stamped copy, or with the original if stamping gave up.
- Paths are stored relative to Documents, because the iOS container path changes across updates, reinstalls and restores, and a job can wait across one.
- If the video is deleted while its copy is being made, the finished copy is removed, or startup recovery would adopt it as a new video.
None of this is exotic. The recording is made durable before anything is derived from it, the file is never opened for writing, ambiguity is refused rather than guessed at, the stamp is drawn by one component everywhere, and every failure is sorted into a kind the app knows how to handle. The native code is about 670 lines across Kotlin and Swift, and the logic that decides what is safe sits in small TypeScript functions we can test without a phone. That split, native code for the codec work and plain functions for every decision about safety, is the pattern we bring to mobile work where the data on the device matters more than the feature.
Common questions
Does Wherecam change the original video when it adds the stamp?
No. The native code copies each camera file’s bytes into a scratch folder and re-encodes those copies with the stamp drawn on every frame. The recording itself is only ever opened for reading, and it stays in the app whether or not stamping succeeds.
Why is the video stamp drawn in React Native rather than natively?
So that a video carries exactly the same stamp as the live preview and the saved photos. The stamp component is drawn off screen to a transparent PNG the size of the video frame, and the native side only composites that image onto each frame with Media3 on Android or AVFoundation on iOS.
What happens if stamping a video fails?
The job retries automatically after 30 seconds, five minutes and 30 minutes. If it still cannot make a copy, or the video is in a format the phone cannot re-encode, the gallery receives the untouched original, and the person can ask for the stamped copy again later.