Skip to content

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

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

AatmanAJ wants to merge 880 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), three more fixes after review (17a845b4c to f449d3e69), eight more merges of the Live Updates PR (506c8289e to 8f34cc454), the media module's lint rule (e40bd7e38), another merge of the Live Updates PR (7905ff75e), a deadline for an encoder that never finishes draining (f7fb783d6) and the pattern recorder keeping what that deadline saves (077ea1786). 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: 32 tests, all new: Fmp4WriterTest 10, H264Test 6, VideoTimelineTest 7, AudioTimelineTest 5, SegmentTest 2 and DrainTest 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.

Saving that cannot finish

A segment writer told to finish waited for the video encoder, then the audio encoder, to return end of stream, with no limit. An encoder that stopped answering, as the Android 10 emulator's media codec service did under load, left the recording saving for ever with its codecs held. The wait now has a deadline that scales with the work still queued when the recording stops, measured in media time (f7fb783d6):

  • The backlog is the wall time since the writer started minus the video already drained, plus the audio queued minus the audio already drained.
  • The deadline is 2 s plus twice the backlog. An encoder keeps up with real time while it records, so its backlog drains in no more than its own length, and the factor of 2 lets a device drain at half real time. A recording that stops 3 s behind gets 8 s. The 2 s floor covers a writer with nothing queued: SegmentWriterTest.finishBeforeAnyFrameReportsNothingRecorded, which finishes a writer before any frame, takes 43 ms in all on the API 29 emulator and 34 ms on API 35.
  • When the deadline passes, the writer writes what it has drained as a last segment, releases its codecs and completes with a new UNFINISHED failure that carries the seconds it kept. The recorders in the PRs above keep that recording and say "Couldn't finish saving, N s kept". The debug pattern recorder here does the same: it finishes the upload with the seconds kept instead of discarding it, and other failures still discard the upload (077ea1786).

The deadline lives in Drain, which owns the completion, so it is tested on coroutine virtual time without a codec. DrainTest.aDrainThatNeverAnswersEndsWithWhatWasKept fails without the deadline, as the drain never completes, and checks that the codecs are released once and the kept seconds are reported. aSlowDrainWithinItsBacklogFinishes drains 3 s of frames at half real time, so it takes about 6 s, and fails with a flat 2 s limit. There is no device test of the writer giving up: it would need a real encoder that stops answering on demand, which cannot be arranged without replacing the codec. SegmentWriterTest still passes 7 of 7 with the deadline in place, on the API 29 and API 35 emulators at 276cfebaa, the top of the Android stack.

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, on f449d3e69 after the second round of review fixes, with 271 capkit, 477 app and 30 media JVM tests, and on f7fb783d6, after the drain deadline, with 272 capkit, 491 app and 32 media JVM tests. :app:testReleaseShrunkUnitTest comes later in the stack, so it is not part of the line here.

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: 4/5RetriggerView in Greptile

Fix the existing Loom cancellation issue before merging; Cancel upload currently hides the notification without stopping the import.

Findings

  1. P1 Cancel leaves Loom imports running ▶
Fix with agent prompt
### Issue 1
apps/mobile-android/app/src/main/kotlin/so/cap/mobile/app/Notifications.kt:101-106
`Notifications.upload()` now adds “Cancel upload” to Loom import notifications, but `UploadActionReceiver` only cancels jobs found in `pendingUploads`. Loom imports use a separate watcher, so tapping Cancel only hides the notification. The import keeps running and can post another notification.

Only show this action for jobs the receiver can cancel, or add cancellation for Loom imports.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds the Android recording engine, saved upload jobs, crash recovery, and a background upload worker.

  • Android users can sign in and manage their Cap library from a native app.
  • Android recordings are encoded and saved as short video and audio segments.
  • Recording jobs upload segments as they close and resume unfinished work after a restart.
  • Mobile sign-in callbacks keep their request state, and Cap owners can check sharing audiences.
  • CI checks and builds the Android app and media module.

No new actionable issues were established in the changes since the previous review.

Reviews (32) · Last reviewed commit: "Merge commit 'fe9bcc418d00f1eddc21882679..." · Reviewed by Greptile

@vercel

vercel Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@AatmanAJ is attempting to deploy a commit to the Cap Software Inc Team on Vercel.

A member of the Team first needs to authorize it.

Comment thread .github/workflows/ci.yml Resolved
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

2 similar comments
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

2 similar comments
@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

@AatmanAJ

AatmanAJ commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

1 similar comment
@AatmanAJ

AatmanAJ commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment on lines +237 to +242
CapRadioRow(
stringResource(R.string.cap_audience_organization),
selected = cap.isPublic && restricted,
onClick = {
management.setAudience(isPublic = true, LinkAccess.RESTRICTED)
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Organization-only choice makes recordings public

The share sheet offers “Only people in your organization” even when the organization has no email restriction. Choosing it for a private Cap publishes the recording. But LinkAccess.RESTRICTED only clears the link override; it does not add an organization check. Without allowedEmailDomain, anyone with the link can watch.

Hide this choice when the server cannot enforce it, or add a server operation that enforces the selected audience.

How this was verified: The organization choice sends a public sharing update, while the viewing policy applies the email check only when the organization has a nonempty allowed domain.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/cap/MoreMenu.kt
Line: 237-242

Comment:
**Organization-only choice makes recordings public**

The share sheet offers “Only people in your organization” even when the organization has no email restriction. Choosing it for a private Cap publishes the recording. But `LinkAccess.RESTRICTED` only clears the link override; it does not add an organization check. Without `allowedEmailDomain`, anyone with the link can watch.

Hide this choice when the server cannot enforce it, or add a server operation that enforces the selected audience.

**How this was verified:** The organization choice sends a public sharing update, while the viewing policy applies the email check only when the organization has a nonempty allowed domain.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +139 to +144
when {
showsDesignedEmpty -> {
LibraryEmptyState(Modifier.fillMaxSize())
}
loadedEmpty -> {
Box(Modifier.fillMaxSize(), Alignment.Center) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Empty libraries hide upload failures

The new empty-library branches skip UploadBanner. A first upload stays hidden while the phone prepares it. If preparation or createUpload fails, the library stays empty and the error stays hidden too. There is no other in-app banner, and notifications can be denied.

Keep the upload banner outside the empty-state branches so the user can see progress and failures.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/home/LibraryContent.kt
Line: 139-144

Comment:
**Empty libraries hide upload failures**

The new empty-library branches skip `UploadBanner`. A first upload stays hidden while the phone prepares it. If preparation or `createUpload` fails, the library stays empty and the error stays hidden too. There is no other in-app banner, and notifications can be denied.

Keep the upload banner outside the empty-state branches so the user can see progress and failures.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +107 to +111
val defaults by settings.recordingDefaults.collectAsState(initial = RecordingDefaults())
val appearance by settings.appearance.collectAsState(initial = Appearance.System)
val shareAnalytics by settings.shareUsageAnalytics.collectAsState(initial = false)
var confirmSignOut by remember { mutableStateOf(false) }
val context = LocalContext.current

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Settings misses plan upgrades

The rewrite removes both the plan refresh on resume and pull-to-refresh. The only remaining call to refreshPlan() runs once when the session starts. Someone who upgrades in the browser and returns still sees Free and the upgrade link until the app restarts or they sign in again.

Restore the refresh on return. It also lets a failed initial plan request recover.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/mobile-android/app/src/main/kotlin/so/cap/mobile/features/settings/SettingsScreen.kt
Line: 107-111

Comment:
**Settings misses plan upgrades**

The rewrite removes both the plan refresh on resume and pull-to-refresh. The only remaining call to `refreshPlan()` runs once when the session starts. Someone who upgrades in the browser and returns still sees Free and the upgrade link until the app restarts or they sign in again.

Restore the refresh on return. It also lets a failed initial plan request recover.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

…ttings

Notification rows drew the stock Material switch, which is a different
size and colour from the 44x26 design switch every other settings row
uses. They now show CapSwitchTrack. The two switch lines on Recording
defaults each drew a top and a bottom hairline, so the rule between them
was twice as thick as every other divider.
Keeps this layer's theme root, which already wraps Root in the picture
in picture box.

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