Skip to content

feat(mobile-android): add the recording engine - #4764

Open
AatmanAJ wants to merge 362 commits into
CapSoftware:mainfrom
AatmanAJ:feat/mobile-android-recording-engine
Open

AatmanAJ wants to merge 362 commits into
CapSoftware:mainfrom
AatmanAJ:feat/mobile-android-recording-engine

Conversation

@AatmanAJ

@AatmanAJ AatmanAJ commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on the Live Updates PR (#4762), which sits on the earlier Android PRs. Only the top 18 commits are new here, from "model a recording job and name its segments" onwards (5a3343fbf to 7b1906f1e), then a merge of the Live Updates PR (5270d95dc), two fixes after review (8b18d1242, 9965ee960), a second merge of the Live Updates PR (9a37a6b22) and three more fixes after review (17a845b4c to f449d3e69). Once the PRs below merge this shows only its own diff.

This PR adds the recording engine: the segment writer that turns frames and sound into fragmented MP4 segments, and the recording job that uploads those segments while a recording is made and completes the Cap. There is no recorder screen yet; the camera recorder follows in the next PR.

What is in it

A port of the iOS recording pipeline. A recording is written as 2 second fragmented MP4 segments, each uploaded as soon as it is closed, so the Cap is close to ready when the recording stops. The job survives a crash or a relaunch and finishes from what reached disk.

  • Recording job (capkit). Recording.kt models a job and names its segments as iOS does (init.mp4, then segment_001.m4s onwards per track), plans which upload links to ask the server for, and checks a recording before completing it.
  • Uploads while recording (capkit). RecordingUploads creates the Cap when a recording begins, uploads each segment as it is written, retries what failed, and completes the recording once it has finished and every segment has reached storage. It asks for the Cap once per recording, even when segments arrive while the server is answering or a pump read the job before the Cap was stored. Jobs are saved under the app's no-backup directory, one root per server, so a local server and cap.so never share jobs.
  • Crash recovery. Each finished segment is saved to the job's record before add returns, so a job left unfinished by a crash or a relaunch is resumed at start-up and finished with every segment that reached disk. Signing out discards every job, as on iOS.
  • Media module. A new media Gradle module holds the writer: a fragmented MP4 writer, an H.264 encoder wrapper on MediaCodec that picks the best offered profile, an AAC encoder with the iOS silence-fill rules, and SegmentWriter, which cuts both tracks into 2 second segments and reports the first failure's reason from finish.
  • Upload worker. RecordingUploadWorker is long-running WorkManager work with a data sync foreground notification, "Uploading recording" with "Finishing up", built by the shared notifications builder on the uploads channel. It needs a network connection, runs as unique work, and keeps going until no job is unfinished. The app requests it at start when a saved job is unfinished.
  • Debug pattern recorder. A debug-only screen, PatternRecorderActivity, records a generated 720 by 1280 test pattern at 30 fps with a 440 Hz tone for 10 seconds, 2 minutes or 6 minutes, through the real writer and uploads, and shows the job's phase, bytes uploaded, segment count, duration and share link. Start it with adb shell am start -n so.cap.mobile.debug/so.cap.mobile.PatternRecorderActivity --es capApiBaseUrl <server> after signing in to that server.

Screenshots

The debug pattern recorder on the API 37 emulator, recording 10 seconds and uploading to a local fixture server. Taken at 13954befa, the screen recorder PR's tip, which contains this PR.

Idle Recording Finished
Light Pattern recorder idle Pattern recorder recording Pattern recorder finished, 10.0 s
Dark Pattern recorder recording, dark Pattern recorder finished, dark

ffprobe on the uploaded recording: video H.264 Main, 720x1280, yuv420p, 30 fps, 10.00 s; audio AAC LC, 48 kHz mono, 96 kb/s, 10.01 s. The full output is in ffprobe-pr10.txt.

Not captured here: the "Uploading recording" notification, which had already finished by the time the shade was opened, and the share page playing the recording, as no web app was running for this pass.

Where it differs from iOS, on purpose

  • No hand-over between processes. iOS can pass an unfinished recording from an extension to the app. Android records in one process, so aHandedOffRecordingIsFinishedByCapOnce is not ported.
  • WorkManager instead of a background session. Finishing uploads after the app leaves the screen is done by a foreground worker with a data sync notification, which Android needs for work that may outlast the activity.
  • A debug screen in place of the recorder. The engine is checked end to end through a generated pattern before any camera code exists, so problems in the writer show up here rather than behind the recorder.

Tests

  • capkit, :capkit:test: 271 tests, 39 of them new in RecordingTest.kt. RecordingTest (14) ports the iOS model and planner tests, and RecordingUploadTest (25) sends to a loopback storage server: four of the five iOS upload tests, resume after relaunch, completion validation, that discarding the last unfinished job ends the wait for unfinished jobs, and the two review fixes below.
  • JVM, :app:testDebugUnitTest: 462 tests on 7b1906f1e and 468 on the merge, none new in this PR.
  • media, :media:testDebugUnitTest: 30 tests, all new: Fmp4WriterTest 10, H264Test 6, VideoTimelineTest 7, AudioTimelineTest 5 and SegmentTest 2.
  • Instrumented, media, 13 new: VideoEncoderTest (3) checks that surface frames come out as length-prefixed H.264, the best offered profile is used and a requested sync frame arrives before the next interval; AudioEncoderTest (3) times packets by count from zero and applies the cut-off; SegmentWriterTest (7) turns 10 seconds of pattern and tone into 2 second segments, delivers the tail on finish, keeps the two tracks covering each other and the timeline moving forward, and reports a segment that could not be written.

Device pass

Pinned to one run at 13954befa, the screen recorder PR's tip, which contains this PR and the two above it. Both emulators ran headless against a local fixture server.

API 37 (cap_cam_37) API 29 (cap_cam_29)
App instrumented 93 run, 90 passed, 3 failed 93 run, 93 passed
Media instrumented 41 run, 37 passed, 4 skipped 41 run, 35 passed, 6 skipped

The 3 API 37 failures are the known Cap detail ones, listed separately because they are not in this PR's code: CapDetailTest.playAndPause and aShareLinkWithATimeOpensTheCapThere (Compose did not go idle while the emulator decoded the video) and aChosenSpeedIsKeptAfterTheAppIsOpenedAgain (touch input could not be injected). The skipped tests are all in CameraCaptureTest, which skips what the emulator's cameras cannot do: two cameras, a flip, or the frame rate it asks for. The crash buffers were empty after every suite.

Fixed after review

  • The recording upload worker asked to run in the foreground without being expedited, so a recording that finished while the app was in the background made setForeground throw ForegroundServiceStartNotAllowedException on Android 12 and later, and the work failed. The request is now expedited, falling back to ordinary work when out of quota, and a refused foreground start lets the uploads carry on without the notification (8b18d1242). RecordingUploadWorkerTest covers the refused start. On the API 37 emulator, a 10 second pattern recording finished with the app in the background. Before the fix the worker failed with that exception and the recording was not completed. After it, ActivityManager still refused the foreground start, but every segment uploaded, the recording was completed and the worker succeeded, with no exception in the app's log.
  • Signing out revoked the session before local recording jobs were removed, so the Caps created for unfinished or failed recordings could no longer be deleted and stayed in the library. Sign-out now discards those jobs and deletes their Caps before the revoke, best effort and limited to 2 seconds so sign-out never waits on the server (9965ee960). Three new AppModelTest cases on a loopback server check that the deletes reach the server before the revoke, and that sign-out still completes when a delete fails or never answers.
  • After a segment was added, it reached the job's saved record only after a 1 to 5 second delay, and recovery reads only that record. A process killed in that window lost footage already on disk, and a recording whose record had no video yet was deleted with its Cap on relaunch. add now saves the record before it returns; upload progress still coalesces its writes (17a845b4c). iOS coalesces these writes too and accepts losing the last few seconds, so Android differs here on purpose. aSegmentFinishedJustBeforeACrashIsKept kills the process right after two segments are added and has a fresh instance read the same directory: both segments are recovered, the recording completes with 2 seconds of video, and nothing is deleted. The existing test for a crashed recording with nothing saved now adds only the initialisation segment, which is the case its name describes.
  • A pump that read the job before the first create stored its Cap could claim the create once that create had released it, and send a second one, leaving the first Cap behind. The claim now checks the stored job's Cap in the same lock (3325ce7e3). aPumpHoldingTheJobFromBeforeTheCapWasCreatedDoesNotCreateAnother drives that interleaving on the loopback server without mocks: the server holds the create answer on a CompletableDeferred, a second thread's pump is held inside the currentUserId callback just after it reads the job, the first create is answered and stored, and the held pump is released. The test checks that it started nothing and that the server saw exactly one create.
  • CI ran neither the media module's JVM tests nor its lint. The Android job now runs :media:testDebugUnitTest and :media:lintDebug, and so does the standing check line in the README and the plan (f449d3e69).
  • Each new test fails with its fix reverted.

Checked

  • ./gradlew spotlessCheck :capkit:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleRelease :app:assembleDebugAndroidTest :media:testDebugUnitTest :media:lintDebug :media:assembleDebugAndroidTest passes on 7b1906f1e, on the merge, 5270d95dc, on 9965ee960 after the review fixes, with 268 capkit, 473 app and 30 media JVM tests, on the second merge, 9a37a6b22, with 269 capkit, 477 app and 30 media JVM tests, and on f449d3e69 after the second round of review fixes, with 271 capkit, 477 app and 30 media JVM tests.

Not checked

  • The gate for the camera recorder: pattern recordings of 10 seconds, 2 minutes and 6 minutes from the debug screen, completed against a real Cap server on the API 37 emulator and on a physical phone, each finalising and playing on the share page with the right duration and sound in sync. The 6 minute run uses a free account, to see the server's 403 and the client's message.
  • Killing the app mid-recording and relaunching it, to see the job finish with what reached disk.
  • The upload worker's notification on a device. The background run above had its foreground start refused, so it ran without one.
  • The pattern recorder on the API 29 emulator: it draws straight into the encoder's input surface, which the emulator's software encoder does not accept. API 37 and phones are not affected.
  • A debug build pointed at a local server resumes unfinished jobs only when the app is relaunched with the base URL extra, because a worker restarted after process death uses the production environment. Release builds use production only.
  • A physical phone.

Confidence Score: 5/5RetriggerView in Greptile

The changes appear safe to merge; no new blocking issue was found.

Summary

Adds the Android recording engine, saved recording jobs, segment uploads, crash recovery, and a debug pattern recorder.

Since the previous review:

  • Android recordings are saved in short segments and uploaded while they are made.
  • Android users can sign in and use Cap’s library, playback, editing, and settings.
  • Android sign-in callbacks now identify the browser sign-in that started them.
  • Android changes now run through their own CI checks and release build.

The five earlier, unnumbered findings were checked against the current code. Their fixes remain present: segments are saved immediately, Cap creation checks the stored job under the lock, CI includes media checks, and detail reads preserve fresh processing state and newer library sharing choices.

No new actionable issues were found. Tests were not run during this review.

Reviews (11) · Last reviewed commit: "Merge branch 'feat/mobile-android-live-u..." · Reviewed by Greptile

Adds the Summary section between Comments and Transcript, offered unless
the owner turns off both the summary and chapters or the Cap is a
screenshot. The summary sits in a card with selectable text and renders
bold and italic markdown; chapters list their start times, tint the one
being played with a waveform and play from their start when tapped.

With neither, it shows Generating summary while the Cap, its transcript
or its AI output is still processing, and No summary yet otherwise.
The video stepped aside whenever the page was shorter than the video
plus room for the list, which is always true on a phone in landscape,
so the player and timeline disappeared with no keyboard open and the
player surface was disposed, pausing playback. The video now steps
aside only while the keyboard is up, and a page wider than it is tall
puts the player and timeline beside the list instead of above it. The
full screen player sits outside both layouts, so turning the phone does
not close and reopen it.
If a refresh or poll brought the server's copy of a comment back while
its POST was still pending, the reply then missed the placeholder and
appended the same comment again, giving the list two items with one
key. The reply now replaces any copy with its id before taking the
placeholder's place.
The field stays editable while a comment sends, so a failure used to
overwrite whatever was typed since, along with the reply target and the
pinned moment. The failed text, its reply target and its moment now
come back only when the field is still empty and no reply was started.
Replies are drawn inside their thread's list item, so a link to a late
reply scrolled only to the top of the thread and left the reply below
the screen, and the thread folded again when the highlight faded. Once
the list has reached the thread, the highlighted row now brings itself
into view, and a thread that held a highlighted reply stays expanded.

CapSocialTest opens a link to the eighth reply of a thread, which the
test relay adds to the fixture's Cap.
A refresh or poll that left before a comment was deleted could answer
afterwards and put the comment and its replies back on the page until
the next refresh. The page now remembers the comments it has deleted
and leaves them, and their replies, out of later replies.
The 2,000 character limit counted UTF-16 units, so a comment cut at the
limit could end in half of a surrogate pair and send a broken character.
The field and the sent comment now stop before a pair the limit would
split.
A refresh or poll that left before a comment or reaction was sent could
answer afterwards and take the new comment off the page until the next
refresh, and any reply landing while a comment was still sending dropped
its placeholder. Each Cap request now notes how many comments the page
had created when it left, and applying its reply keeps the comments
created since that the reply lacks, along with the ones still sending.
…ving a Cap

Sending a comment or reaction, or deleting a comment, ran on the Cap
page's own scope, which is cancelled when the page leaves the back
stack. Sending and then going straight back could drop the request with
no message, and a delete or a failure was never reported. These now run
on the session's scope, like deleting a Cap and changing its sharing,
so they finish and report success or failure, and they update the page
only while it is still open.
The Cap page became a lazy list, so the section tabs, the reaction bar,
the sort button and comments below the video may not be composed until
the list reaches them, and the tests clicked or asserted on them without
scrolling. Each test now scrolls the list to a node before using it.
The late reply test waits for the relay's eighth reply itself rather
than for eight replies, since the fixture keeps replies earlier runs
left on the same thread.
…it returns

The poll was launched from inside the coroutine handling a reply, so
under an unconfined dispatcher it was queued until that coroutine had
finished and only then reached its first delay. A caller that waited for
the load and moved the clock straight away could do so before the poll
was waiting, leaving it asleep until the clock moved again; with the
poll's start held back on purpose, the three CapDetailModelTest cases
that poll hung every time. The poll now starts undispatched, so it is
waiting before the load completes. On the main dispatcher nothing
changes, as the launch already ran at once.
…it returns

The poll was launched from inside the coroutine handling a reply, so
under an unconfined dispatcher it was queued until that coroutine had
finished and only then reached its first delay. A caller that waited for
the load and moved the clock straight away could do so before the poll
was waiting, leaving it asleep until the clock moved again; with the
poll's start held back on purpose, the three CapDetailModelTest cases
that poll hung every time. The poll now starts undispatched, so it is
waiting before the load completes. On the main dispatcher nothing
changes, as the launch already ran at once.
…t lands

A comment, reaction or delete that was still on its way when the Cap
was left and opened again only updated the page that started it. The
new page could load before the server had the change and never hear of
it, and a finished Cap does not poll. The comments created and deleted
on a Cap are now shared by every page open for it in the session, so a
finished request updates the pages open now and a page loading later
keeps them.
Sending a reply highlighted the comment it answered, so in a thread
folded to its first replies the new reply stayed behind "Show more" and
the page scrolled to the parent. The reply itself is now highlighted,
which opens its thread and brings it into view. The iPhone app
highlights the parent, but it never folds replies, so the reply is
always on screen there.
…s late

A comment sent from one page and deleted on another before the send
answered came back when the answer arrived, because placing a sent
comment or reaction did not look at what had been deleted. The same
held for a reply whose parent was deleted while it was sending. Placing
a sent comment now drops it, along with its "Sending…" row, when it or
its parent has been deleted, as a refresh already did.
Three tests could not pass on an emulator.

The chapter test tapped the 0:38 chapter of cap_london, whose fixture
video is 12 seconds long, so the seek stopped at 12 and the wait for 38
never ended. It now taps the 0:48 chapter of cap_stress, which plays the
three minute video and has a chapter every 12 seconds.

The late reply test waited for the highlight to clear, but that happens
after a delay in an effect, and effects run on the test clock, which
does not move while nothing on screen is changing. It now moves the
test clock until the highlight clears.

The transcript search test checked that the matching line was on screen
while the keyboard was still opening and shrinking the list. It now
closes the keyboard before checking.
The relay read every upstream body into memory before replying. The
three minute cap_stress video needs allocations larger than the API 29
test heap allows, so the app process died with an OutOfMemoryError.
Non-JSON replies are now copied straight to the socket.
On API 30 and later the keyboard animates in while imePadding and the
compact layout move the composer, so a Send tap injected during the
animation could land beside the button and never send.
…r test

Revealing the 0:48 chapter can scroll the Chapters heading out of the
lazy list, so the heading check failed 2 of 20 runs on API 37. The
reveal already proves the chapter row is there.
When the player cancelled a media request, writing the reply headers
threw before the body was copied, so the upstream response and its
socket stayed open. The relay now closes the reply in a finally block.
The Cap page gets a Share button and a More menu in its top bar. The
menu offers Copy link, Copy link at m:ss once playback is past half a
second (not for screenshots), and Open in browser when the link is an
https link. Share sends the link with the title as its subject.

As in the library, the "Link copied" and "Link at m:ss copied" toasts
are shown below Android 13 only, because later versions show their own
confirmation.
The owner's More menu offers Make private or Make public, and for a
public Cap with a link access setting, "Limit to your organization" or
"Open to anyone with the link". The change shows at once on the page
and in every library, is undone if the server refuses, and one change
waits for the last to finish, as on iOS.

The session's visibility change now takes the link access, answers with
the server's Cap so the page can show it, and uses the iOS toasts for
link access: "Only your organization's emails can view" or "Anyone with
the link can view".

The page actions live in a small CapManagement class beside the detail
model, so the model itself only gains a way to show an updated Cap.
The owner's More menu offers Rename, which opens "Rename Cap" with a
Title field filled with the current title and Cancel and Save. The title
is trimmed, cut to its first 255 characters and not sent when it is
blank or unchanged, as on iOS. The new title shows on the page and in the
library, with the toast "Title updated".
The owner's More menu offers "Add password", or "Change password" when
the Cap is protected. It opens a sheet titled "Add password" or
"Password" with a Password or New password field, the iOS footer
"Viewers will need this password to watch. You and your organization can
still open it in Cap." and, when protected, "Remove password". The
password is trimmed; Save is off while it is blank. The sheet closes once
the server has saved it, with "Password set" or "Password removed", and
stays open with the error otherwise.

The password gate's field now takes its label, autofill type and
keyboard action, so the sheet reuses it.
The owner's More menu ends with Delete, which asks "Delete this Cap?"
with the same message and "Delete Cap" button as the library. Once the
server has deleted it the Cap leaves every library, "Cap deleted" is
shown and the page closes. A refusal keeps the page open with the error.

The session's delete now answers whether the server deleted the Cap, so
the page knows when to close.
On a Cap you don't own the More menu ends with "Report Cap". It asks
"Why are you reporting this Cap?" with the six iOS reasons, from
"Harassment or bullying" to "Other concern", and sends the chosen one.
The server's answer is shown as "Thanks. Cap Support will review this."
or as the error.
On a Cap you don't own that names its owner, the More menu offers
"Block owner". It asks "Block <owner>?" ("this user" when the name is
empty) with the message "You won't see their Caps or comments in Cap for
Android.", the wording PLAN.md section 2.8 gives for Android. Once the
server has saved the block the Cap leaves every library, the libraries
load again so the owner's other Caps go too, "User blocked" is shown and
the page closes. iOS marks the libraries stale instead; there is no
stale flag on Android, so they are refreshed straight away.
When the viewer may download a Cap (and it is not a screenshot), the
More menu offers "Save to device", off while saving or processing. It
asks the server for the download address, which must be https or the
Cap origin, downloads the video to the cache with its mp4, mov or m4v
extension (mp4 otherwise), and adds it to MediaStore under Movies/Cap,
pending until the copy has finished. The cached file is deleted
afterwards.

Android 10 and later need no storage permission for this, so none is
declared and there is no permission message. The toasts use the wording
PLAN.md section 2.8 gives for Android: "Saving to your device…", "Saved
to your device", and the iOS "The video couldn't be saved. Try again."
for any failure.
The owner's More menu shows Edit (not for screenshots, off while the Cap
is processing) and Analytics, in the places iOS puts them. Each opens a
placeholder page titled Edit or Analytics with the Cap's title, until
the editor and analytics land. The Edit entry does not ask the server
whether the Cap can be edited yet; that check belongs with the editor.
CapMenuTest opens Caps from the fixture server and goes through the More
menu: the three visibility toasts on a Cap with a link access setting,
rename trimming and keeping the first 255 characters (and renaming back),
setting and removing a password, delete closing the page and removing
the card from the list, Save to device adding one video under
Movies/Cap, and, on someone else's Cap, report and block.

The fixture server answers 404 to the password, report and block
endpoints, so the relay answers them: the password reply is the
fixture's Cap with "protected" set from the request.
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

…age read

A page read that started before a change on the page sent the page's
title, password state and sharing to every library. If the Cap was made
private or public from the library while the read was out, the library
went back to the page's older choice. Such a read now updates the
libraries with the server's fields only and leaves the title, password
state and sharing each library already shows.
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

Storage answering 408, 429 or a 5xx was reported as a rejected upload,
and the upload worker only retried transport errors, so a busy or
throttled bucket deleted the staged file and failed the upload. An
upload error now says itself whether it can be retried, storage's
408, 429 and 5xx included, and the worker keeps the file and retries
those with its exponential backoff.
NewerVersionAvailable asks Maven Central for the latest version of each
dependency, and with warnings treated as errors the Android check fails
on the day a release lands, as it did for Kotlin 2.5.0 against the
2.4.21 the app pins. It is turned off so the check only depends on the
code. GradleDependency and AndroidGradlePluginVersion do not fire on
this project, so they stay on.
…one is checked

The test checked the library still showed the newer choice once the
older sharing request had finished, but the newer request starts as
soon as the older one frees the Cap's lock, and its refusal could land
before the check and roll the library back. The refusal is now held
until the older answer has been checked, then released.
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant