Property Walk — the manual

Last updated 26 November 2026, 19:30 (research system and first research round; this page is now online at propertywalk-docs.deskhand.ca). Covers the app as installed on the test phone (build 27) and the website on this laptop.

1. What Property Walk is

Property Walk lets a property agent make a walk-through tour of a home using only a phone, and lets a buyer open that tour from a link.

A tour is a set of points. A point is one place you stood, turned into a picture you can look around in every direction, including up at the ceiling and down at the floor. Points are joined by links, so a buyer in the entrance can tap the bedroom doorway and be standing in the bedroom. It works like Google Street View, inside one home.

There are two sides to it:

2. Making a tour, step by step

This is what the agent does. Every step below exists in the app today; section 5 says which ones have been checked on a real phone.

Step 1 — Start a tour

Open the app, tap New tour, and give it a title and address. You land on the tour's page, which is empty for now.

The tour page before any point is captured
The tour page before any point is captured

Step 2 — Capture the first point

Before you start (shown before every capture; tap I understand, start):

Why the instructions matter. Each photo is sharp and correct on its own. The trouble is joining them: when you turn, the phone moves along a small circle, so neighbouring photos are taken from slightly different places. Close to the phone, that makes things shift against what is behind them (like closing one eye and then the other), and the two photos no longer agree at the join. The further everything is, the smaller the shift, which is why the middle of the room gives the cleanest result. Only a camera turning exactly around its own lens, on a special tripod head, avoids it completely.

Stand where the tour should begin and tap Start: turn 360°.

Before the camera opens, the app shows how to hold the phone, with two small moving drawings seen from above:

Tap I understand, start and the camera opens.

The camera: aim ring, arrow to the next dot, and the direction in words
The camera: aim ring, arrow to the next dot, and the direction in words

After the last dot the phone joins the 24 photos into one picture. This takes about 13 seconds; a second version with the joins bent to meet is made in the background (about 46 seconds more). You see the result and choose Use this view or Retake.

The floor photos and the last photo. For the four dots pointing at the floor, keep the phone out in front of you and turn your whole body with it, as for the photos around; do not twist the phone in your hand. When the last dot is done the app asks for one more photo of the floor: take one big step back, hold the phone out over the spot where you stood, point it straight down and tap "Take floor photo". This keeps you out of the picture when a buyer looks down. You can skip it.

Step 3 — Name the point

The app asks you to name the point, with one-tap ideas such as Entrance, Kitchen, Bedroom. The name is what the buyer sees in the list of rooms, so every point should have one.

Naming a point
Naming a point

Step 4 — Mark where the next point is

You are now looking at the point you just made. Drag to look around, then tap the doorway (or the spot on the floor) where the next point will be. A marker appears there. Tap Walk there.

Step 5 — Walk there and capture the next point

Walk to the marker and capture again, exactly as in step 2. When it uploads, the first point now leads to the second: a buyer standing in the first point will see an arrow at that doorway.

Step 6 — Mark the way back

A link only goes one way, so the second point needs its own link back to the first.

Step 7 — Repeat, then publish

Repeat steps 4 to 6 for every room. When the tour is complete, tap Publish tour. The app gives you a link to share and an embed code for a website.

3. What the buyer sees

The buyer opens the link in any browser.

The tour page on a computer
The tour page on a computer

On a phone the list starts closed behind a Rooms button, so the room fills the screen.

The list of rooms opened on a phone
The list of rooms opened on a phone

4. How it works behind the scenes

How one point is made

  1. The phone takes 24 ordinary photos with its widest back camera.
  2. For each photo it records which way the phone was pointing, using its motion sensors.
  3. It lays the 24 photos onto the inside of an imaginary ball, each in the direction it was taken, and blends the overlaps.
  4. The ball is unrolled into one wide picture, 4096 by 2048 pixels. That flat picture is what gets stored; the viewer rolls it back into a ball when you look around.
A finished point, unrolled: the bedroom
A finished point, unrolled: the bedroom

All of this happens on the phone. Nothing is sent anywhere until you choose Use this view.

Where the camera part comes from

The camera screen and the joining of the photos were not written from scratch. They come from Photosphere, a free, open-source Android app for taking 360° photos, made by other people and published with a licence that lets anyone reuse it (MIT). We copied its code into our app on 25 November 2026 and changed it where it did not suit an agent. Their own documentation is kept, unedited, in docs/photosphere-upstream/.

How the camera part works, step by step

This is how their design works, with the numbers our app uses. The full technical version, with the formulas, is in the technical reference at the end of this page ("How it works, start to finish").

  1. Knowing where the phone points. The phone's motion sensors (the ones that notice turning and tilting) report which way the back camera faces, many times a second. They leave out the compass on purpose, because indoors a compass jumps near steel and wiring; turning is measured steadily, but "north" is not known.
  2. Knowing how wide the lens sees. The app asks the camera how wide its view is. On our test phone it is about 80 degrees across and 96 degrees up and down.
  3. Planning the dots. From that width it works out where photos must be taken so each one overlaps its neighbours by about a third. For our phone the lens alone would need 12 photos; we take 24 (16 around, 4 up, 4 down), because more photos around means the phone moves less between neighbours and near things line up better.
  4. Taking each photo. When the ring stays within 2 degrees of a dot for a third of a second, the phone takes two photos, keeps the sharper one, and writes down exactly which way it was pointing.
  5. Keeping the colours even. The camera sets brightness and colour once, right after the first photo, and keeps them for the rest, so all photos match.
  6. Laying the photos on the ball. Each photo is placed exactly where the sensors said it was pointing. The app does not try to match the photos to each other, because plain walls give nothing to match.
  7. Deciding the joins. Every spot of the ball is taken from the one photo that sees it closest to that photo's middle, where photos are sharpest. Only a thin strip at each join is mixed, so nothing shows through twice.
  8. Unrolling it. The ball is unrolled into the flat 4096 by 2048 picture, tiny gaps are filled in, and a tag is added so other apps know it is a 360° photo.

How they built it. Their team tried every idea first as a small test program on a laptop, scored the results out of 10, and only then put the winners into the app. Their notes show that the standard joining tools failed on rooms (2 out of 10), that placing photos by the motion sensors worked, and that matching photos to each other found nothing on plain indoor walls, which is why that step is off.

What we use as they built it

What we changed, and why

Theirs Ours Why
Brightness and colour fixed the moment the camera opens Fixed right after the first photo Fixing them at the start froze the preview white or green on our phone; fixing them after the first photo keeps all photos even
Focus set once, at the start Focus follows the scene, like the phone's own camera The single focus landed on the desk and every photo was soft
Joins blended smoothly by default Each spot taken from one photo ("Crisp") Their own notes name this as the fix for doubled furniture; it made the bed single
Photos read at a small size Read at twice the size The finished picture was soft and only 2760 wide
As few photos as the lens allows More photos around and at least 4 up and 4 down Fewer photos left thin overlaps and doubled edges
A faint dotted line to the next dot A bold arrow and words such as Tilt up Agents could not tell when to tilt
A "stitch" button after three photos Builds by itself after the last photo Agents read it as being told to stop early
A result screen with gallery, share and other buttons Just Use this view and Retake An agent pressed "Saved to gallery" thinking the point was saved

We also added a compass reading, which their app does not take, because the way back between two points needs to know which way north is.

What we left out

Their app also has a settings screen, saving to the gallery, sharing, a "little planet" picture, a night mode and a few experimental joining options. None of these help an agent make a tour, so they stay in the code but are never shown.

What their notes taught us

If something goes wrong with the camera

Everything the camera part can do is written down at the end of this page under Engine reference: every feature, every setting and its number, and the notes its makers left in their code and in all 310 of their changes. The technical reference has a short table, If something goes wrong with the camera — what to adjust, that starts from what you see (doubled furniture, light and dark patches, a soft picture, a stretched room, you in the floor) and lists the settings to try. Settings are always tried on saved photos first, never changed on a guess.

Their project is still being worked on. The app's helper checks it at most once a day and tells you about anything new, what it does, and whether we should take it.

Where things are kept

flowchart LR P[Phone app] -->|finished picture| S[(Picture storage)] P -->|tour, points, links| W[Website server] W --> D[(Database)] B[Buyer's browser] -->|opens the link| W B -->|loads pictures| S

A link is simply: in this point's picture, at this spot, there is a way to that other point. The spot is saved as a position in the picture, so the arrow appears on the real doorway for the buyer, in the same place the agent tapped.

How the way back is worked out

If the doorway to the bedroom is to the south of where you stood in the entrance, then from the bedroom the entrance must be to the north. So the app needs to know which compass direction each picture faces.

Audit of the first real test: the stored way back (right, on the doorway) and where the first version of the calculation put it (centre, on the wrong wall)
Audit of the first real test: the stored way back (right, on the doorway) and where the first version of the calculation put it (centre, on the wrong wall)

The first version got this wrong, and the test tour showed why: the sensor the camera uses to track the phone is smooth but has no compass in it. Its idea of "north" starts fresh with every capture. Build 18 reads the phone's real compass during capture and uses that instead. Compasses drift indoors, which is why the app shows you the marker and asks before trusting it.

5. Where we are

Working checked on the test phone or in the browser · Built, unchecked written, not yet checked for real · Not built not built · Problem known problem

Area State Notes
Capturing a full point (24 photos) Working 13 seconds to build (plus 46 for the bent version). Shooting took about 70 seconds with 16 photos; not yet timed with 24
Guidance on the camera (arrow, words, large dot) Working
"How to hold the phone" sheet before each capture Working Seen on the test phone; whether agents follow it is untested
Upright rule for the ceiling and floor dots Problem Built in build 23, then switched off: on the first real try those dots would not fire
Uploading a point and seeing it in the tour Working
Naming points Working Asked once per point; can be skipped
Marker, walk there, capture, link forward Working Used to make "Test tour 2"
Way back required before the next point Working Used to make "Test tour 2"
Way back placed automatically Problem First test landed on the wrong wall; fixed in build 18, not yet re-tested
Publishing and the share link Working "Test tour 2" was published from the app
Buyer page: list of rooms, bottom bar, restart Working On this laptop only; not yet on the live site
Picture quality: walls and ceiling Working Clean in 16-photo captures
Picture quality: near the floor and close objects Working Since build 27 each spot comes from one photo ("Crisp") with brightness locked after the first photo: the bed is single. Small stair-step edges remain where a join crosses something; your feet show when looking straight down
Keeping yourself out of the floor Working Turning your whole body with the phone for the four floor dots removed you from the floor (26 Nov). The extra floor photo was taken and fits: it replaces the jagged tiles under the spot with one clean floor (the first one was turned down by a check that was too strict, now relaxed; tried on the saved photos, not yet in a fresh capture). Still to improve: the patch is a little brighter than the floor around it, with faint double tile lines at its edge. The grey disc on the tour page was removed at your request
Photos kept for research Built, unchecked The app keeps the photos of its last 6 captures (about 75 MB each) in its own folder on the phone; python scripts/capture_test.py pull-all <label> saves them to this laptop
Tours tab on deskhand.ca Working Opens without a password and lists every tour, drafts included. Each card shows a normal photo (the view straight ahead from where the first point was started) instead of the stretched 360° picture. Edit changes the title, address, city, price, bedrooms, bathrooms, area and point names; saving asks for the password. Checked on this laptop; live after the 26 Nov push
Second walkthrough with bent joins Working Every capture makes two pictures on the phone (the bent one adds about 50 seconds) and uploads both by itself; tested end to end on 26 Nov. On the tour page Bent joins is the default view; the switch at the top right still offers Normal. A chair about 1.5 m away came out doubled before the 26 Nov setting change; now single
Research system Working One folder (research/) with the search keys found on this laptop (11 services; 9 work), one command per kind of search, and every search logged. The first round ran on 26 Nov; its findings and the ideas waiting to be tested are in the Research chapter
This page online Built, unchecked Published from GitHub on Render's free plan at propertywalk-docs.deskhand.ca (hidden from search engines); it updates by itself on every push. The screenshots stay on this laptop, so they are missing online
Sign-in for agents Not built The server runs with one shared account for testing
Payments, visitor statistics, first-run tutorial Not built
Other phones, other kinds of rooms Not built Everything so far: one phone, one home, at night

6. How we work on it

7. What we learned so far

What we saw What caused it What we did
Every test so far ran with a stronger "phone swings on your arm" correction than a finished app would use The camera part uses a different setting in test builds (it assumes the room is 3 m away) than in finished builds (10 m); we only ever install test builds Read from the code and confirmed in the phone's log. Before a finished build is made, the joins must be tested again with the finished setting
Photos of earlier captures disappear when the camera opens The camera part clears every older capture when it starts, which undoes our "keep the last 6 captures" rule Found by reading the code; not fixed yet. Until then, save photos with capture_test.py pull-all right after each capture
Joins still break even with full-size photos and a solved position for every photo Between photos the phone moves about 14 cm, so near and far things shift by different amounts; no single placement of a photo lines up both Laptop test: at each join, measure how the two photos disagree pixel by pixel and bend both half way. Fixed the wire, the left curtain rod and the bed headboard; small smudges on cluttered clothes. 12 photos around was clearly worse than 16. Not in the app yet
A wire and a curtain rod break on a far wall One photo's direction is off by 1–2°; the engine's extra matching step treats every photo pair as a pure turn of the phone, but the phone moves about 27 cm between photos, so it tilts photos wrongly (tested with small and large photos) Kept that step off; the real fix is a solver that allows the phone to move, not built yet
Screen turned green after going to the home screen and back mid-capture Coming back restarts the camera, and the brightness/colour lock from before was applied before the camera had measured anything On return the lock is released, the camera measures the room again, and the lock is set again after about a second
Camera preview all white, then green The capture engine locked brightness and colour too early, on whatever the phone was facing Left brightness, colour and focus automatic, like the phone's own camera
The picture was a narrow band with black above and below Only one circle of photos, taken with the narrow main lens Wide lens, plus photos tilted up and down, in every capture
Ceiling edges and lights doubled Only 2 photos tilted up and 2 down, so neighbours barely overlapped 4 up and 4 down: 16 photos in total
Soft, low-detail pictures Photos were shrunk too much before joining Photos are read at twice the size; the picture is now 4096 wide
Hard to know when to tilt up or down The hint was a faint dotted line Bold arrow, direction in words, bigger dot
The app asked to "stitch" after three photos The engine's own wording and early finish button Plain words; it finishes by itself after the last photo
Would other joining settings look better? — Tested seven on the same photos: none beat the current one
Doubling near the floor remains The phone moves in a small circle at arm's length, so close things shift between photos No setting fixes this; holding the phone closer to the body is the next thing to try
Automatic way back pointed at the wrong wall The tracking sensor has no compass in it Build 18 reads the real compass during capture
The photographer shows up when looking around, not just straight down For the four downward photos the phone was twisted in the hand while standing still, so one photo looks straight back at the body, and no photo shows that floor without it Two masking rules tested, neither can remove it from such a capture; next: the downward photos will only fire with the phone upright, so the agent turns the body instead
The bed edge sits in two places Measured: the phone moves about 27 cm between neighbouring photos; the engine corrects for that assuming everything is 3 m away, so things 1 m away end up about 100 pixels off On the laptop, working out where the phone was and how far things are, from the photos themselves, made the bed and floor single and sharp. Not in the app yet. The app now coaches the agent to keep the phone in one place
The fix that worked for the doubled bed The engine's authors document it: take each spot from one photo ("Crisp") and keep every photo at the same brightness. We had switched their brightness lock off while chasing the green preview, so Crisp showed patches Brightness and colour now lock right after the first photo; Crisp is the default. Tested 26 Nov: bed single, walls even
The engine's notes say photos are evened out in brightness, yet Crisp showed brightness patches before the lock Reading their code: the evening-out runs only together with photo matching, which is off (in their app too) Nothing to change now; the lock after the first photo does the job. Whether to make the evening-out work without matching is an open question
A door looked see-through in the Entrance point A pillar stood close to the phone; each photo saw past it from a slightly different place, and blending mixed the two Added a tip to keep the phone over one spot; the phone now keeps the photos of the last six captures so cases like this can be re-built with other settings

The see-through door, as an example

The Entrance point of the first test tour: the pillar on the left is close to the phone, and the door behind it shows through
The Entrance point of the first test tour: the pillar on the left is close to the phone, and the door behind it shows through

The phone was held at arm's length, so it moved in a circle about 70 cm wide while turning. For a wall three metres away that makes no visible difference. For a pillar one metre away it does: one photo sees the door beside the pillar, the next sees the pillar covering it. The photos are laid in the right directions, but they honestly disagree about what is there, and the smooth blend shows both at half strength.

Two things can reduce it: moving the phone less (turn around the phone, not the phone around you), and choosing one photo per area instead of blending where photos disagree. The second is one of the settings on the test bench; it was worse in the bedroom because of brightness steps, and has not yet been tried on a tight space.

8. Open questions

Research: what we tried, what we found, what is next

Every idea tried to make the pictures better, what the research rounds found, and the plan for the next round. It is the content of master_doc/research.md; the search tools and raw results are in research/.

Last updated 26 November 2026, 16:30 (research process set up; round 1 run).

This page is the record of every attempt to make the pictures better: what was tried and how it went, what the research rounds found, the ideas waiting to be tested, and how the next round will be aimed. The detailed test notes stay in capture-tests/RESULTS.md; the search tools and raw search results are in research/.

How a research round works

  1. Start from a problem in the list below (the one hurting the pictures most).
  2. Search wide with research/search.py (every source we have keys for) and, for big questions, a few parallel researchers, each given one problem area, what was already tried, and what is ruled out.
  3. Open and check every promising source before writing it down (no claims from titles or snippets).
  4. Write the findings here: link, licence, whether it can run on the phone or a cheap server, which of our problems it targets, and the bench test it calls for.
  5. Test the best idea on saved photos (scripts/capture_test.py on the phone, or a laptop script), never by changing the app on a guess.
  6. Record the verdict in "What we have tried" below and in capture-tests/RESULTS.md, then adjust the next round's questions to what we learned.

The research tools (keys checked 26 Nov)

The keys are gathered from the owner's own projects on this laptop into research/.env, which is never uploaded. python research/check_keys.py re-checks them and writes research/keys.md (which work, how much credit is left; never the keys themselves). Every search is logged in research/usage.jsonl.

source good for command state
Exa searching by meaning (papers, repos); "pages like this one" search.py web …, search.py similar <url> works
Tavily web search with a short written answer search.py web … 2 keys, ~1,900 credits
Firecrawl web search; any page turned into clean text search.py web …, search.py fetch <url> 6 keys, ~5,500 credits
TinyFish free web search and page fetch search.py web …, fallback for fetch works, free
GitHub (gh) code and projects, sorted by stars search.py github … works
Hugging Face papers and ready-made models search.py papers … works
Apify YouTube videos; Reddit (falls back to Firecrawl on reddit.com) search.py youtube …, search.py reddit … YouTube works; Reddit actor fails on all 4 free accounts
NVIDIA / Groq / DeepSeek summarising a fetched page against our problem search.py summarize <file> "<question>" works (free / cheap)
Anthropic (2 of 4 keys) judging pictures — sparingly, cost-checked — works
ScrapeGraph (5 keys) page extraction — unreachable

Not used for research: keys in client projects (Park Hotel, Hotel Nirvana, VLCC) and OpenAI (AI image route dropped).

The problems being researched (most harmful first)

  1. Near objects break at joins (bed edge ~1 m, chair ~1.5 m, curtain < 1 m beside a wall): the phone moves ~14 cm between photos, so near and far things shift by different amounts.
  2. The bending (second picture) can warp a wall next to a near object (switchboard beside a curtain).
  3. Brightness steps between photos on plain walls (mostly fixed by locking exposure; still visible in places).
  4. Build time on the phone: ~12 s normal + ~50 s bent per point.
  5. The agent in the floor: fixed by turning with the phone + floor photo; tile joins under the spot remain.

What we have tried

date idea how it was tested result verdict
25 Nov upstream settings (blend, refine, carve, warp, mask) 7 settings on one bedroom capture base blend best; carve blocky; refine matched 3/36 pairs keep blend (then)
25 Nov one photo per spot ("Crisp") without an exposure lock bench brightness patches on walls needs the lock
25 Nov depth-aware join: distances triangulated from the photos, positions solved laptop depth_aware_join.py bed single and sharp; tears at distance jumps; only 430 distances right direction, unfinished
26 Nov upstream's fix: Crisp + exposure locked after the first photo phone capture bed single, walls even shipped
26 Nov eye-level-first seam rule bench first helped, then black smudges + cut bed at 12/24 around dropped
26 Nov narrower lens angle (fov 94/96) bench doubled edges dropped
26 Nov photos around: 8 / 12 / 16 / 24 full-size bench 16 cleanest shipped 16
26 Nov photo matching (ORB / SIFT, larger photos) as a pure turn phone + laptop photos tilted 3–4°, worse dropped
26 Nov full solve of directions + positions + distances at native size laptop bundle adjustment froze, then diverged (turn vs slide ambiguous at 14 cm) dropped
26 Nov bending each join by optical flow (DIS), 4° / 7° / 12° / 18° zones laptop then phone 7° fixes wire/headboard; 12° fixes chair, kinks wire; 18° breaks shipped as second picture (zone 7°, shifts ≤ 12°)
26 Nov guard on the bending (flow both ways / only where it helps) laptop also cancelled the good bends dropped
26 Nov turning with the phone for the floor photos + holder-side rule phone capture agent gone from the floor shipped
26 Nov floor photo from a step back, fitted as a flat floor phone clean floor under the spot; raised bed edge blurred → limited to matching floor shipped
26 Nov grey disc over the floor on the tour page browser owner: remove removed
26 Nov Careful seams (graph cut) + bending phone bench chair still doubled, smudges dropped
26 Nov AI image editing (gpt-image) of joins / whole views laptop strips: no change; views: ghosts or broken wardrobe dropped (owner)

Round 1 — 26 November 2026

Searches: 27 through research/search.py (web ×9 across Exa/Tavily/Firecrawl/TinyFish, GitHub ×12, Hugging Face ×4, Exa "similar" ×2, Reddit ×2, YouTube ×1) — raw results in research/rounds/2026-11-26_r1/. Four parallel researchers: stitching methods, how other apps do it, hardware and market, depth / exposure / floor.

1. Stitching methods that tolerate the phone moving (researcher 1)

2. How other apps and projects handle it (researcher 2)

how the agent turns lens distance from the turning axis error at 1 m at 1.5 m
turns their body, phone at arm's length (today) ~0.35 m ~102 px ~43 px
walks around the phone, lens kept over one spot ~0.05 m ~9 px ~4 px
phone on a selfie-stick tripod, lens over the stick ~0.01–0.03 m ~3–5 px ~2 px

3. Hardware and market route (researcher 3)

4. Distance, exposure and floor methods (researcher 4)

Ideas waiting to be tested

idea targets effort status first test
"Walk around the phone" handheld (lens kept over one spot, body walks around it) + a check after capture ("the lens moved X cm, retake?") + capture setting with a ~5 cm lever arm near objects at every join (error ~102 px → ~9 px at 1 m) small–medium top capture walking around the phone vs turning the body, same bedroom spot
Tripod-stick mode (selfie-stick tripod) near objects small ruled out by owner 26 Nov: no selfie stick —
Overlap-based brightness gains (today they are always 1) + "start facing the brightest part of the room" brightness bands small next brightness bench on a plain-wall capture
Depth Anything 3 reprojection with our camera directions (server) near objects, near/far mixes medium (Python + GPU job) next laptop/Modal on …floorphoto-1 and …3bhk-16ring vs wta / bent / 25 Nov solved
Depth-predicted guard for the bending (DA2-Small on the phone) switchboard-type warps medium next laptop with DA2-Small ONNX; then time it on the M36
LPAM: repair only failing seam stretches thin lines, local warps medium (Python port exists) queued flat neighbour pairs vs seam_flow_join.py --band 7
Accept 360-camera photos (Insta360 X3/X4) via the existing upload near objects small ruled out by owner 26 Nov: no 360 camera —
Lens corner-darkening (vignetting) calibration for the M36 wide lens brightness bands small proposed 5 white-wall photos → radial fit → bench (a)–(d) on a plain-wall capture
Overlap-based per-channel gains (+ block gains in release) brightness bands small–medium proposed same brightness bench
Second floor photo + median of three tile joins / agent under the spot small proposed one capture with two floor photos

Next steps and how the research will be adjusted

What round 1 changes: the owner ruled out extra hardware (no selfie stick, no 360 camera, 26 Nov), so the phone in the hand stays the only capture tool. The biggest remaining lever is how the agent turns: walking around the phone with the lens kept over one spot cuts the near-object error about ten times, with no new equipment. The depth route (Depth Anything 3) is the best software answer for whatever error remains.

  1. Owner test (no code): capture the same bedroom spot two ways — body turn (today) and walking around the phone — and compare the bed edge, chair and curtain.
  2. Laptop test: Depth Anything 3 with our camera directions on the saved bedroom photos.
  3. Brightness bench: overlap gains and lens-darkening correction on a plain-wall capture.
  4. Each result goes into "What we have tried". - New captures for testing must include the hard cases: a curtain or chair within 1 m of the phone beside a wall. - The release app now keeps the last 6 captures' photos, so every problem a capture shows can be re-run. - Next round's questions follow from the tests: if distance-based reprojection works, research fast on-phone depth; if not, research seam placement around near objects.

Rounds log

round date questions sources used outcome
r1 26 Nov 2026 near-object joins; other apps; hardware route; depth / exposure / floor 29 searches: Exa (11), Tavily (9), Firecrawl (9 + 2 page fetches), TinyFish (9), GitHub (12), Hugging Face (5), Apify YouTube (1), Reddit via Firecrawl (2); DeepSeek summaries (2); 4 researchers (~200 pages opened) tripod stick / walk-around = biggest lever; Depth Anything 3 = best software route; 360 camera via upload = best guaranteed-quality route; brightness gains are off today (owner later ruled out the stick and the 360 camera: phone in the hand only)

Tool notes from round 1: GitHub search needs short queries (every word must match — the tool now retries with fewer words); Apify's Reddit scraper fails on all 4 free accounts (falls back to Firecrawl on reddit.com); ScrapeGraph unreachable; for summaries NVIDIA and Groq did not answer with the chosen models, DeepSeek did.

Technical reference

The detailed reference used when working on the code: file locations, server routes, the formula for the way back, commands. It is the content of master_doc/master.md.

Open the technical reference

property walk — master doc

how the whole thing is built and how it works, as it actually is in the code today. the .html next to this file is the same content for the browser — never edit the html, edit this file and run python scripts/build_master_doc.py.

last updated: 2026-11-26, 11:05 (engine reference in master_doc/engine/ — every feature, switch, number and note of the borrowed engine; "if something goes wrong with the camera" guide; what the full read turned up (debug builds use a 3.0 m pivot scene, old captures deleted on camera open); "keeping up with their repo" + scripts/check_upstream.py)

this file is the technical reference (for engineers and ai). the human manual is manual.md; master.html is built from both.

see it on this laptop: http://127.0.0.1:4174/master.html (run python -m http.server 4174 --bind 127.0.0.1 --directory master_doc).

what it is, in plain words

  • an android app for a property agent: stand in a room, turn on the spot, the phone takes 24 photos and joins them into one 360° view (a "point").
  • in that view the agent taps a doorway ("the next point is there"), walks there, and captures the next point.
  • the two points get linked both ways, so a buyer can walk between them like google street view.
  • "publish" gives a web link (and an embed code) the buyer opens on any phone.

where things stand (honest)

part state
capture a full 360° point on the phone (24 photos: 16 around + 4 up + 4 down; ~13 s to build, +46 s for the bent picture) working, checked on the samsung m36
upload a point, see it in the tour working
tap a doorway to place a marker, walk there, capture, link A → B built; walked through earlier builds, not re-walked since build 13
way back B → A required before the next point built (build 16), not walked on the phone yet
way back placed automatically from compass built (build 17 + server), never tried on a real second point
publish, buyer page /tour/<slug>, embed /embed/<slug> built; publish itself last checked before the capture rewrite
buyer page: directory of named points, bottom control bar, restart working on localhost (desktop chrome + the m36's chrome); not deployed until pushed
naming every point (prompt in the app, tap the name to change) working, checked on the m36
sign-in off — the server runs with one stub agent (ALLOW_AUTH_BYPASS_IN_PROD), fine for testing, not for customers
payments, analytics, onboarding not built
tested on other phones / other rooms no — one phone, one small bedroom

the agent's flow

flowchart TD A[tours list] --> B[new tour: title + address] B --> C[tour page] C --> D[start: turn 360°] D --> E[camera: follow the arrow to each dot, 24 photos] E --> F[phone builds the 360° view, ~13 s + bent picture ~46 s] F --> G[use this view → upload] G --> H[point page: tap a doorway = marker for the next point] H --> I[walk there] I --> D G --> J{arrived from a marker?} J -->|yes, compass known| K[way back added for you: looks right / move it] J -->|yes, no compass| L[mark the way back: required] K --> H L --> H C --> P[publish → link + embed code]

the three pieces

flowchart LR subgraph phone[android app · apps/mobile] F[flutter screens] --- N[native capture · photosphere module] end subgraph server[next.js on render · apps/web] API[api routes] --- V[buyer pages /tour /embed] end F -->|https json| API F -->|photo upload, presigned url| R2[(cloudflare r2 · images)] API --> DB[(neon postgres)] API --> R2 Buyer[buyer's browser] --> V V --> R2
piece what where
app screens flutter 3.27, riverpod, dio, go_router apps/mobile/lib/
capture engine photosphere-android (MIT, vendored, changed by us): kotlin + compose + camerax + opencv apps/mobile/android/photosphere/
bridge one platform channel propertywalk/capture360 MainActivity.kt ↔ lib/services/capture360.dart
server next.js 14 app router + prisma apps/web/
database neon postgres, project hidden-pine-35466713 apps/web/prisma/schema.prisma
images cloudflare r2 bucket property-walk-assets apps/web/lib/r2.ts
hosting render web service property-walk-web, auto-deploys branch feature/photosphere-capture https://property-walk-web-2a4s.onrender.com

the app, screen by screen

route file (under lib/features/) what it does
(wraps everything) server/server_wake_gate.dart waits for the free render server to wake (15–30 s cold)
/ properties/properties_list_screen.dart list of tours, new tour, server url override
/properties/new properties/new_property_screen.dart title, address, details
/properties/:id properties/property_detail_screen.dart points of a tour, publish, share, embed code
/properties/:id/upload-panorama upload/upload_panorama_screen.dart "turn 360°": opens the camera, then uploads
/properties/:id/upload-cover upload/upload_cover_image_screen.dart cover photo
/spots/:id/arrows viewer/arrow_placement_screen.dart the 360° view with markers; way-back rules live here
/spots/:id/walk/:connectionId viewer/walk_to_marker_screen.dart "walk to the marker" → create view

the 360° view inside the app is photo sphere viewer 5.14.1 in a webview, the same viewer the buyer page uses, so a marker sits in the same place for both.

capture — how a point is made

sequenceDiagram participant A as agent participant C as camera screen participant S as phone sensors participant B as builder (opencv) A->>C: hold phone up C->>S: wait until aimed at the room + exposure settled loop 24 targets C->>A: arrow + "tilt up / turn right" to the next dot A->>C: aim, hold still C->>C: take 2 photos, keep the sharper S->>C: direction of this photo (yaw/pitch/roll) end C->>B: 24 photos + their directions B->>C: one 4096×2048 image (~13 s) + the bent picture (+46 s) C->>A: preview → "use this view" / "retake"
piece choice now why later / alternative
lens widest back lens (m36: 80°×96° in portrait) full sphere in 12 photos by the lens alone; we take 24 (see the dot plan below) main lens is sharper but needs ~33 photos
photo plan HORIZON_RING_FRAMES around + 4 up (75°) + 4 down (75°). around: 8 in build 27, 24 in the test build, 16 since 2b1795c (26 nov bench winner) = 24 photos per point 2 up/down left thin overlap → doubling; denser eye level = less phone movement between neighbours —
exposure, white balance automatic until the phone faces the room, then locked right after the first photo every photo the same brightness, which crisp joins need; locking at start froze the m36 preview green/white —
focus continuous autofocus upstream's single focus at start locked on the desk —
positions of photos phone motion sensors only photo matching finds almost nothing on plain walls revisit in textured rooms
joining crisp: one photo per spot (SeamMode.WinnerTakeAll) no doubled near objects; upstream's documented fix see capture-tests/RESULTS.md
size photos read at 2000 px long edge → 4096×2048 sharp enough, 13 s on the m36 6144 wide on stronger phones
guidance bold arrow, direction words, big dot, plain words (no "stitch") agents couldn't tell when to tilt up/down —
finish builds by itself after the last photo no asking mid-capture —

capture rules added by us: features/upload/capture_howto.dart (sheet before every guided capture); upright rule in SphereCaptureCoordinator (marker tilted >45°, aim within 8°, roll >45° → no shot) — switched off (UPRIGHT_RULE_ENABLED = false): on the first real try the ceiling and floor dots would not fire. engine assumption to revisit: PivotModel lever arm 0.35 m — wrong once the phone stays put; DebugRestitch flags arm0 / arm10 / arm20 exist to test it; nadir = StitchTuning.maskBehindNadir (on since eff5cd1; it only acts in Balanced/blend — Crisp uses holderSidePenalty instead, Careful uses neither).

what we took from photosphere, what we changed, and what we left out: next section.

the capture engine we borrowed (photosphere-android)

  • source: theclumsypirate/photosphere-android, commit b5796d7 (pushed 2026-11-23), MIT; original author n30dyn4m1c/360-photo-app. vendored 2026-11-25 as the android library apps/mobile/android/photosphere/.
  • their docs, copied unedited: docs/photosphere-upstream/ (readme, known issues, build, capture, stitching, viewer, design, lab, status, three tool readmes). all read 2026-11-26 for this section.
  • how much is still theirs: all 64 of their kotlin source files are vendored; 51 are unchanged, 13 carry our edits, 3 files are ours (CaptureActivity, sensor/CompassProbe, diagnostics/DebugRestitch). re-check with diff -r --strip-trailing-cr <their app/src/main/java/com/n30dyn4m1c/photosphere> <ours>.
  • careful when reading their docs: they describe features their own code ships switched off (photo matching, focal refinement, lens correction, and with them the brightness evening). the tables below go by the code.
flowchart TD A[motion sensors · game rotation vector]:::theirs --> B[dot plan from the lens]:::changed B --> C[aim ring, arrow, words]:::changed C --> D[auto shutter 2° for 300 ms · 2 shots, sharper kept]:::theirs D --> E[exposure + white balance lock after photo 1]:::changed E --> F[photos + direction in exif]:::theirs F -.-> G[photo matching + brightness gains]:::off F --> H[paint onto the sphere · pivot 0.35 m · multi-band]:::theirs H --> I[joins: crisp]:::changed I --> J[gpano jpeg 4096×2048]:::theirs J --> K[review: use this view / retake]:::ours M[compass probe]:::ours --> L K --> L[CaptureActivity → flutter → upload]:::ours classDef theirs fill:#e8f0fe,stroke:#4a6fa5 classDef changed fill:#fff4d6,stroke:#b8860b classDef ours fill:#e6f4ea,stroke:#3c8c50 classDef off fill:#eeeeee,stroke:#999,stroke-dasharray:4 3,color:#777

blue = theirs as built · yellow = theirs, changed by us · green = ours · grey dashed = in the code, switched off.

how it works, start to finish (read from our code at 16eb526)

their design, with the numbers our build actually runs. their own words for each step are in docs/photosphere-upstream/docs/capture.md and stitching.md; this is the same story checked against the code.

1. where the phone points — sensor/OrientationTracker.kt

  • listens to TYPE_GAME_ROTATION_VECTOR (gyro + accelerometer, no magnetometer) on its own HandlerThread.
  • getRotationMatrixFromVector gives device → world (z up); the lens looks down the device's −z, so that column is the camera's forward.
  • yaw = bearing of forward (zero is arbitrary, different every capture), pitch = height above the horizon, negative when aimed up (their convention, used everywhere), roll = tilt of the picture measured against the screen's top.
  • why no magnetometer: indoors a still phone's compass heading jumps degrees near steel; the game vector drifts only a fraction of a degree a minute. cost: no north — which is why we added CompassProbe for the way back.
  • the screen is locked to portrait, so one capture never mixes two picture orientations.
  • two streams: raw samples decide the shutter and stamp poses; OrientationSmoother (snap-limited, median on compass-only phones) only steadies the dots on screen.

2. how wide the lens is — camera/CameraOptics.kt

  • read from the camera camerax actually bound (its camera2 id + stream size), not a guess.
  • two estimates: LENS_INTRINSIC_CALIBRATION (precise) and sensor size ÷ focal length; if they disagree by more than 25 % the calibration is thrown away.
  • preview and stills both pinned to 4:3 so one field of view describes both.
  • m36, widest lens, portrait: about 80° across × 96° up-down.

3. the dot plan — camera/SphereTarget.kt (createForFieldOfView)

planned fov      = real fov × 0.9                     (FIELD_OF_VIEW_SAFETY_FACTOR)
step around      = planned h-fov × (1 − 0.35)          (35 % overlap)
step up/down     = planned v-fov × (1 − 0.35)
top ring         = min(75°, max(step, 90 − v-fov/2 + step/2))     mirrored for the bottom ring
photos on a ring = round(360 / (step around / cos(elevation)))
                   at least 16 at eye level (ours), at least 4 on a tilted ring (ours)
order            = eye level, then up, then down; each ring swept opposite to the last;
                   the whole plan turned to start where the agent is facing

worked through for the m36 (80° × 96°):

lens alone (theirs) ours
step around 72° × 0.65 = 46.8° → 8 photos forced to 16 (22.5° apart)
rings step up 86.4° × 0.65 = 56.2°; top ring at 74.9° same: 0°, +74.9°, −74.9°
tilted ring 46.8° / cos 74.9° = 180° → 2 photos forced to 4
total 12 24

4. dots on screen and which one is live — SphereProjection, TargetSelection, TargetOverlay

  • a dot's direction is turned into the camera's frame and divided by depth with the lens's focal length (the same projection the lens does), so the dot sits on the pixel that photo will cover.
  • roll turns the dots with the scene, but is left out of "how far off am I" (turning the phone in its own plane does not change where it aims).
  • any dot can be taken: aim within 6° of an untaken dot and it becomes live (1.5° hysteresis); after each shot the nearest untaken dot is next, with the plan's next one given a 12° head start.
  • our overlay on top: bold arrow, "tilt up / turn right", bigger dot.

5. the shutter — AlignmentGate, SphereCaptureCoordinator, PhotoSphereCameraScreen

  • fires when the aim stays within 2° of the live dot for 300 ms; one sample outside resets the timer.
  • the pose stamped is the mean of the last 20 samples of the hold (OrientationMean), not one reading.
  • burst of 2 shots; each records the pose at its own shutter; the kept shot gets the hold's mean only if it is within 0.4° of it, otherwise its own pose.
  • the sharper shot is judged on the middle half of the picture at 2000 px (SharpnessSelection), where hand-shake shows.
  • capture, undo and restart go through one lock, so an undo during a shot can't leave the run pointing at a dot that was never taken.
  • ours before the first shot: wait until the phone faces the room (pitch under 40° for 1.5 s) and exposure + white balance have settled (12 s fallback); lock both right after photo 1.

6. the photos on disk — storage/ImageBufferManager.kt

  • each photo is a jpeg in cacheDir/sphere_sessions/<session>/, its yaw/pitch/roll written into exif UserComment.
  • pixels stay on disk (a sphere's worth decoded would be hundreds of mb of memory).

7. building the sphere — stitching/PhotoSphereStitcher.stitchPhotos

flowchart TD A[24 photos + pose in exif] --> B[decode upright · long edge ≤ 2000 px] B --> C[fov check: square pixels, else swap the two angles] C --> D[canvas 4096×2048 · centred on the first dot's bearing] D --> E[positions = sensor poses · gains all 1 · no lens model] E --> F[seam map 512×256: each cell → the photo that sees it nearest its own centre] F --> G[paint every pixel: direction → each photo's pixel · lanczos · 6-level pyramid · 128-row bands] G --> H[fill pinholes if ≥ 95 % covered] H --> I[gpano xmp spliced in · jpeg] G -.-> J[ours: bent picture — SeamBend shift field, same paint again]
  • decode: each photo read upright from its exif rotation (fallback: the camera's portrait rotation), scaled so the long edge is ≤ 2000 px (m36 3264×2448 → 2000×1500).
  • fov check: a lens has square pixels, so the focal length the across-angle implies must match the up-down one; if not, the two angles are swapped and a warning logged.
  • canvas size: width = min(360 × photo width ÷ h-fov, 4096), even; height = width ÷ 2. m36: 360 × 1500 ÷ 80 = 6750 → capped at 4096. no wider than the photos' own detail allows.
  • positions: PoseRefiner (photo matching) is off, so every photo sits exactly where the sensors said; with it off the brightness gains are never solved (all 1) and focal lengths are not corrected. lens distortion is off too.
  • seam map (crisp = SeamMode.WinnerTakeAll, SeamFinder.computeWinnerSeams): a 512-wide grid (one cell = 8×8 output pixels at 4096). for each cell centre, every photo that sees it gets a penalty 1000 × (1 − across × down), where across/down = 1 − distance from the photo's centre ÷ half its size (0 in the middle, 1000 at the edge). lowest penalty owns the cell. SeamFeather then gives the losing photo weight 0.5 on the boundary, fading to 0 over FEATHER_FULL_RES_PIXELS = 12 output pixels, rounded to whole cells (1 cell = 8 px at 4096).
  • paint (EquirectangularRenderer.render): every output pixel is a direction; for each photo that direction is turned into the photo's frame, the pivot correction applied, divided by depth → the pixel that saw it; remap samples it (lanczos at full size, linear on the coarser levels). photos and their seam weights are split into a laplacian pyramid (up to 6 levels) and blended per level, so fine detail switches across a few pixels and broad brightness across the whole overlap. built in 128-row bands so the float buffers stay tens of mb, not hundreds.
  • pinholes: if ≥ 95 % of the sphere is covered, the leftover tiny gaps are filled with opencv inpaint (telea, radius 8); below that, black is left where nothing was shot.
  • sharpening: the default profile's unsharp mask is 0 (off).
  • out: gpano xmp spliced into the jpeg header without re-encoding (GPanoXmpInjector).
  • ours, after: for crisp/careful seams the bent picture is rendered too (SeamBend, see "files and routes").
  • time on the m36: normal picture 13 s; bent picture +46 s (capture-tests/RESULTS.md, 26 nov 03:25).

the geometry, as the code does it:

column → longitude   lon = start_yaw + (col + 0.5) / W × 360 − 180
row    → latitude    lat = 90 − (row + 0.5) / H × 180
direction            d = (sin lon · cos lat,  cos lon · cos lat,  sin lat)          z up
in one photo         lateral = d · right,  vertical = d · up,  depth = d · forward − k
                     k = lever arm ÷ scene distance, capped at 0.25 (PivotModel)
                       release build: 0.35 m ÷ 10 m = 0.035
                       debug build (what our phone runs — we install `flutter build apk --debug`):
                       SphereDeviceProfile.debugTuned swaps the scene to 3.0 m → 0.35 ÷ 3 = 0.117
                       (phone log 26 nov 10:32: "Debug pivot tuning: scene distance 10.0 -> 3.0 m")
                     depth ≤ 0 → this photo can't see it
pixel                pinhole: column = cx + fx · lateral / depth, row from vertical the same way

the pivot term k: nobody turns around the lens; a phone held out and turned with the body swings on a ~0.35 m arm. the lever points down the lens axis, so it only changes depth. their release value (10 m) is deliberately far so it can't over-correct; their debug value (3.0 m) is what their room tests liked (their python: 3.5 m). every capture and bench result we have was made with the debug value, so a release build would join differently until re-tested.

how they built it (their own experiments, from their tool readmes)

flowchart TD A[stock opencv stitcher on a room: 2/10 as a sphere] --> B[place photos from sensor poses instead] B --> C[all36 v1: plain averaging 5.5/10] C --> D[v2: pivot lever 0.35 m + feather weights 7.5] D --> E[v3: room-scale scene + wrap-seam blend 8.5] E --> F[v5: steep photos give only their sharp centre 9/10] F --> G[winner-takes-all + lever: 8.5 — sharper, seams move] G --> H[restitch v11: graph-cut seams + multi-band 9/10 → SeamFinder 'careful'] H --> I[v13: orb/sift refinement 0 inliers indoors → refinement off]
  • origin: n30dyn4m1c/360-photo-app (mit) → forked and rebuilt as theclumsypirate/photosphere-android.
  • prototype first, port second: every idea was tried in python (tools/pano_proto, restitch_other, offline_stitch), scored out of 10 on contact sheets of viewer-style views, and only then written in kotlin.
  • stock stitchers: cv2.Stitcher crashed on 7 plain frames and made a flat mosaic of the rest (2/10 as a sphere); openstitching kept only the biggest matched row. both read pixels only, and plain walls give them nothing → the whole engine places photos from the sensor instead.
  • the 37-photo room ("all36"): plain averaging 5.5 → pivot lever + feather 7.5 → room-scale scene + wrap blend 8.5 → steep photos only paint near their centre 9.
  • seams: opencv's own graph-cut seam finder crashed (addEdges w>=0); pairwise seams and dp cuts sliced objects (3–5.5); their own global α-expansion over the horizon photos + multi-band finish reached 9/10 (v11) and became SeamFinder / SeamSolver (dinic max-flow, pure kotlin).
  • matching: content-only matching chained the plain turquoise walls wrongly ("the exif seed is what makes the difference"); v13 orb/sift refinement found 0 inliers on every pair indoors → the kotlin default ships refinement off.
  • viewer check: view360.py re-renders a panorama the way a 360 viewer does, which caught "flat looks fine, 360 looks deformed" (a strip is not a sphere).
  • what this means for us: their numbers come from one 37-photo room on their phone; ours (capture-tests/RESULTS.md) come from our bedroom on the m36. where they disagree, ours decide the settings.

capture (their docs/capture.md)

their piece us why
permission gate RequirePermissions (camera + sensors + storage, handles a dismissed dialog) replaced by CameraGate in CaptureActivity: camera only, single-permission request (so their empty-map-means-granted trap can't happen) their gate lives in their MainActivity, which we don't register
WRITE_EXTERNAL_STORAGE (android ≤ 9) dropped we never export to the gallery; our min is android 10
OrientationTracker: game rotation vector, no magnetometer, yaw from an arbitrary zero used as is steady between photos is what a sphere needs
— added sensor/CompassProbe (TYPE_ROTATION_VECTOR) beside it the way back needs a real bearing; their yaw has none (build 17 bug)
portrait lock, one display rotation per run kept (CaptureActivity is portrait) same reason as theirs
orientation debug screen not reachable (it is in their MainActivity) logs cover it
SphereTargetPlan: rings from the lens's field of view, 35 % overlap, planned on 90 % of the fov, outer ring reaches the poles, starts where you face used, two edits in SphereTarget.kt: tilted rings ≥ 4 photos (MIN_TILTED_RING_FRAMES); eye-level ring forced to HORIZON_RING_FRAMES ultrawide gave 2 per tilted ring → doubling at the sides; more photos around = less phone movement between neighbours
ring / sphere toggle; debug builds forced a 36-photo plan hidden, always the full sphere; the debug plan is disabled (if (false)) one way to capture; test builds must behave like release
any-order dots (TargetSelection: aim within 6° at any dot, 12° head start for the planned next) used as is
where a dot sits on screen, fov from the lens actually bound (SphereProjection, CameraOptics) used as is
overlay TargetOverlay: reticle, faint dashed guide line, chevron off-screen changed: bold arrow, "tilt up / turn right" words, bigger dot, always a hint line agents couldn't tell when to tilt up or down
SphereCaptureCoordinator (the shutter rule; undo / restart under one lock) used; our upright rule added and off it blocked the ceiling and floor dots
AlignmentGate: within 2° for 300 ms used as is
burst per dot, sharpest judged on the centre at ~2000 px, each shot keeps its own pose used as is (default profile: 2 shots)
tap to focus, then locked for the run replaced by continuous autofocus (SphereCaptureProfile) their one focus at start landed on the desk → every photo soft
exposure + white balance locked "for consistency": at bind (stills request) and on the preview once exposure settles (6 s fallback) changed: nothing locked at bind; the first shot waits until the phone faces the room (pitch < 40° for 1.5 s, exposure + white balance settled, 12 s fallback); lock right after the first photo; unlock if lowered before the first photo or the run is cleared camerax merges the stills lock into the preview, which froze the m36 white/green; but crisp needs equal brightness and nothing else in the engine provides it (gains, below)
brightness slider, tap-focus square, night / torch menu hidden camera as is
photos to cache with direction in exif, undo button used as is
save frames to gallery hidden agents took "saved" to mean the point was saved
SphereDeviceProfile default: widest lens, stills ≤ 4000 px, 2 shots, read at 1024 → 4096 wide used, read at 2000 at 1024 the m36 sphere came out 2760 wide and soft
galaxy s23 profile (main lens, 6144 wide, 3 shots) in the code, fires only on an s23 not our test phone

stitching (their docs/stitching.md)

their piece us why
no cv::Stitcher (missing from android opencv); place photos from the sensor poses same approach their prototype: stock stitcher 2/10 as a sphere
PoseRefiner: orb matches, rotation ransac, pose graph, focal-length refinement off (refinementEnabled = false, their default too) plain walls give nothing to match — their known issue "matched 0 edges", their restitch_other v13 (0 inliers indoors), our logs
ExposureCompensation (per-photo brightness gains) not running: gains are only solved inside PoseRefiner, so with matching off every gain is 1 their doc reads as if it always runs. this is why the exposure lock is what keeps photos even
radial lens distortion off (their default too) our 00:51 bench: lens correction made it worse
PivotModel: lever arm 0.35 m, scene 10 m (release) / 3.0 m (debug builds, DEBUG_SCENE_DISTANCE_METERS) used as is — our phone runs the debug 3.0 m to revisit — the how-to now keeps the phone in place; bench flags arm0/arm10/arm20
footprint walking, equirect by construction, banded memory, fov self-check used as is
feather weight (cubic) used; StitchTuning.featherPower test hook (3 = theirs) bench only
MultibandBlender used; WEIGHT_EPSILON 1e-6 → 1e-12 1e-6 darkened areas with small but real weights
seam modes: Blend "Balanced" (their default), Carve "Careful", WinnerTakeAll "Crisp" Crisp by default their own known-issues fix for ghosting; 26 nov: bed single, walls even
SeamFinder used; our tiltPenalty (eye-level rule) added, off on the 32-photo bench it pulled dark edge pixels into the bed
renderer used; our maskBehindNadir added, on since eff5cd1 (Balanced only) first version could not remove the holder from a twisted capture; now paired with the floor photo step
"finish & stitch" from 3 photos; partial spheres allowed changed: finish only when every dot is done, and it builds by itself agents read "stitch" after 3 photos as being told to stop
c++ backend (StitcherBackend, OpenCv360Stitcher) not used: release builds force kotlin and our module doesn't build the native opencv_360_stitcher library —
night merge, block exposure, local warp, frame-graph subset, moving-object mask, perceptual seam cost in the code, all off (toggles hidden) not proven; not in their docs

the finished sphere, design, build, lab (their viewer, design, build, lab docs)

their piece us why
gpano xmp spliced into the jpeg (no re-encode) still applied harmless; the server marks it 360 from source=capture360, photo sphere viewer doesn't need gpano
result screen: flat preview, export, share, new photo, save frames, restitch styles replaced by our review: sphere preview + "use this view" / "retake" an agent tapped "saved to gallery" thinking it saved the point (25 nov)
MediaExporter (gallery), share through FileProvider not used (the provider is still declared) the sphere is copied to cacheDir/pw_captures, handed to flutter, uploaded
confirm before throwing away an unsaved sphere not kept: retake / back discards at once decision below
import photos (ImportPhotosScreen) used: "use photos I already took" on the turn 360° screen (mode=photos) fallback
little planet, gpano editor, orbit, settings, material you not reachable not needed
dark theme, green/amber signals used in the camera; our review screen uses the app's dark + lime
accessibility (one spoken progress sentence) kept where unchanged; guided capture still needs sight (their open issue too)
their app start (PhotoSphereApplication.onCreate) replaced by ensureInitialized() (logs, report, opencv; no cache pruning) called from CaptureActivity embedded, their application class never runs; CaptureActivity.onDestroy does the cleanup
toolchain: agp 9.3.1, gradle 9.5, kotlin 2.2.10, compileSdk 37, minSdk 26 ours: agp 8.7.3, gradle 8.10.2, kotlin 2.1.21, compileSdk 35, minSdk 29 one gradle build with flutter; their code uses nothing newer than 35
opencv org.opencv:opencv:4.12.0 from maven same
LensModel.kt at b5796d7 fixed: five missing kotlin.math imports (it did not compile)
unit tests (app/src/test: plan, projection, gate, coordinator, gpano) not vendored decision below
one log tag PhotoSphere same: adb logcat -s PhotoSphere:*
tools/photosphere_lab.py, python prototypes not vendored; our version is scripts/capture_test.py + DebugRestitch (rebuild saved photos on the phone)
bug report from settings (Report) installed at start, no screen to send it

their known issues, against our app

their issue (KNOWN_ISSUES.md) their advice us
ghosting, sliced near objects (parallax) crisp; keep people out; step back crisp + lock; how-to "phone stays put"; scripts/depth_aware_join.py goes past their "no 2d stitcher can" (laptop only)
exposure patches lock after the first frames, gains; start facing the brightest part lock after photo 1; gains don't run; "start facing the brightest part" is not in our how-to
blurry or dark stitches reshoot steadier, more light same
refinement finds nothing expected on plain walls why it is off
wrap seam behind you start facing the least important direction our picture is centred on where the agent starts, so the join is behind them; the how-to doesn't say so
compass accuracy "unknown" (mediatek) only the label is missing CompassProbe doesn't read the label; untested on mediatek
old or odd lenses debug: distortion off off anyway
dot drifts on phones without a gyroscope median smoother (OrientationSmoother) used as is
samsung full sensor not exposed — irrelevant: we read 2000 px

what their experiments already settled (their tool readmes)

  • stock opencv stitcher and openstitching both fail on a multi-row indoor sphere → don't chase them.
  • matching without sensor poses chains plain walls wrongly; "the exif seed is what makes the difference".
  • winner-takes-all vs feather: neither wins everywhere; the graph-cut carve ("careful") is their principled middle — we measured crisp best in our bedroom, carve stays a bench option.
  • the pivot lever helps even under winner-takes-all (their python used scene 3.5 m; their app ships 10 m in release and 3.0 m in debug builds — ours are debug builds).

the full engine reference (every feature, switch, number and note)

read on 2026-11-26: every file of our copy against theirs, their tests, their laptop tools and all 310 of their commit messages. five files, built into the html as "engine reference":

file what's in it
master_doc/engine/1-capture.md sensors, lens field of view, the dot plan, dot selection, shutter, burst, focus/exposure profiles, device profiles (s21, s23, default), overlay, CaptureActivity
master_doc/engine/2-camera-screen-and-app.md the camera screen (every toggle and hidden button), their app shell, settings, result screen, viewer, import, storage, gpano, logging, DebugRestitch flags, debug-only screens (extended capture, orbit), manifest, build file, their tests
master_doc/engine/3-stitching-core.md the path every capture takes: stitcher, renderer, geometry, multi-band, seams, pivot, lens model, restitch styles
master_doc/engine/4-stitching-optional-and-their-tools.md the extras (photo matching, brightness gains, block exposure, local warp, frame graph, night merge, c++ backend, SeamBend) and their tools (pano_proto, restitch_other, offline_stitch, lab), ci, versions
master_doc/engine/5-their-commit-history.md lessons by area from their commits, what they tried and threw away, the 5 commits newer than our copy

each entry: status (on / off / debug-only / unreachable / ours), what we changed, a table of every lever with our value, theirs, what it does and where to change it, and their notes (why, past bugs, device quirks). all of it was read from the code, not tried on the phone. the full commit messages: docs/photosphere-upstream/history/commits.md.

if something goes wrong with the camera — what to adjust

start here; details and line numbers are in the engine reference. test any change on saved photos first (scripts/capture_test.py run <capture> <variants>, flags joined with +), never on a guess.

symptom their notes say levers (where) bench flags
near things doubled or cut at a join (bed, chair, wire) parallax from the phone moving; no 2d stitcher can fully fix it; crisp + keep the phone in place joins: SeamMode (crisp/careful/balanced); pivot PivotModel (ours runs scene 3.0 m in debug builds, 10 m in release); photos around HORIZON_RING_FRAMES 16; bend SeamBend.BAND_DEGREES 7°; seam fade SeamFinder.FEATHER_FULL_RES_PIXELS 12 wta, carve, arm0/arm10/arm20, ringN, bend, eyelevel
light/dark patches or steps at joins auto exposure drifting; lock early; start facing the brightest part of the room exposure gate in PhotoSphereCameraScreen (6 s, 40°, 1.5 s, 12 s fallback); brightness gains ExposureCompensation (MAX_GAIN 1.6) only run with photo matching on; block exposure BlockExposure (debug) block, refine
everything soft reshoot steadier; photo size into the build stitchMaxInputDimension 2000, stitchMaxOutputWidth 4096 (6144 on s23), unsharpAmount 0 (0.3 on s21/s23), burst 2 (3 on s21/s23), focus mode SphereCaptureProfile sharpN (blend weights)
room looks stretched / bands bent / photos don't overlap field of view wrong; the lens actually bound must be measured CameraOptics (calibration vs sensor size, 25 % rule); safety factor 0.9; DebugFovCalibration (s23 only) fovNN (e.g. fov96)
photos placed wrongly (whole strip twisted) sensor drift; matching only helps on textured scenes PoseRefiner (refinementEnabled, ≥ 12 inliers, ≤ 6° from the sensor) refine, sift, detN
the agent or the holder at the bottom nadir is never shot cleanly floor photo step + FloorPatch; StitchTuning.maskBehindNadir (balanced only); holderSidePenalty (crisp only); tour-page nadir cover floor, nadir
a step behind the start direction wrap seam sits behind the start; it gets the least overlap start facing the least important direction (not in our how-to yet) —
the dot drifts while the phone is still phones without a gyroscope (compass-only) OrientationSmoother median window —
a dot won't fire 2° for 300 ms, or the upright rule AlignmentGate; UPRIGHT_RULE_ENABLED false —
green / white preview camerax merged the stills lock into the preview ours: no lock at bind, lock after photo 1, re-meter after a rebind (022767a) —
stitch crashes on memory big canvas banded rendering (128 rows); input / output size above —

what the full read turned up (fix or keep in mind)

  • debug builds join differently from release: SphereDeviceProfile.debugTuned sets the scene to 3.0 m (pivot 0.117 instead of 0.035). we install debug builds, so every result so far used 3.0 m; a release build must be re-benched.
  • old captures are deleted when the camera opens: PhotoSphereCameraScreen calls pruneStaleSessions(), which deletes every other session folder, undoing our "keep the last 6 captures" in CaptureActivity — the bench can only pull the latest capture. not fixed yet.
  • bench base is not what the app ships: DebugRestitch defaults to blend; add wta (and nadir, which the app has on) to match the phone.
  • careful (carve) gets neither holder rule: holderSidePenalty and tiltPenalty only apply in crisp; the nadir mask only in balanced.
  • the seam fade is narrower than its comment: at 4096 wide the losing photo peaks at weight 0.25 over one 8-px cell (not 0.5).
  • brightness gains never run in normal captures: only with photo matching on (careful restitch forces it).
  • misleading log line: "AE/AWB locked" at bind locks nothing; the real lock logs "Exposure and white balance locked after the first photo".
  • comments that contradict the code: the eyelevel flag says "now the default" (it's 0.0, off); SphereTarget says "12 around" (it's 16); FrameGraphQuality says it drops the deepest ring (it drops the first in order).
  • built but unreachable: night mode, torch, brightness slider, save frames, ring/sphere toggle, the nine a/b stitch toggles, restitch styles on our review screen, the 62-target "extended capture" screen (debug apk, open by intent), orbit capture. each is one switch away (engine reference, file 2).
  • dead: the c++ backend (no native library in either repo); StitchStatus.AlignmentFailed / CameraEstimationFailed are never thrown.
  • their tests (pure jvm: plan, projection, gate, coordinator, rotation maths, seam solver, geometry, exposure, lens, gpano) were not vendored; they look reusable as regression checks — not compiled yet.

keeping up with their repo

  • tracked automatically: python scripts/check_upstream.py lists their commits after the last one we reviewed (docs/photosphere-upstream/tracking.json), tagged ENGINE / docs/tools / debug/test only / their app only.
  • the project's session-start hook (.claude/settings.json) runs it at most once per 20 h; anything new is explained to the owner with advice (take it / try it on the bench / ignore).
  • after reading: write the verdict in the table below, then python scripts/check_upstream.py reviewed <sha> "<note>"; python scripts/check_upstream.py history refreshes the saved commit messages.
their commit what it does touches what we run? advice
3035b6e 25 nov removes the fisheye / LensProjection groundwork our copy carries yes (renderer, seam finder, geometry, pose refiner) — same picture try on the bench: it drops a small per-pixel allocation in the paint and seam loops, may cut the 13 s / +46 s; keep only if the picture is identical and faster. NB our SeamBend.fillMaps calls intrinsics.projection.project — switch it to the plain pinhole + radial maths when taking this
d68a1c4, 997af42, b5b95a4 25 nov a debug "harness" that stitches one capture 30+ ways and auto-scores them no idea only; our bench does this with the owner judging; the scoring could pre-sort variants
524e864 25 nov little-planet editor crash fix no ignore

reviewed up to 524e864 on 2026-11-26.

linking — markers and the way back

  • a marker is a row in Connection: which point it's in, where in the image (arrowTextureX/Y in pixels), and where it leads (toSpotId, empty until the agent captures that point).
  • capturing the next point from a marker fills in toSpotId (A → B is now real).
  • way back (B → A):
  • every capture sends the compass bearing of its image's middle column (Spot.headingDegrees).
  • the capture's own yaw comes from TYPE_GAME_ROTATION_VECTOR (sensor 15, no magnetometer): its zero is arbitrary and differs per capture, so it is NOT a compass (build 17 sent it raw → way back ~170° off on the first test tour). build 18+: sensor/CompassProbe.kt listens to TYPE_ROTATION_VECTOR and averages (camera bearing − capture yaw) while the phone is level; heading = plan start yaw + that offset; null if fewer than 10 samples → manual way back. logged as Sphere heading: start yaw … + compass offset …. not yet verified on a real pair.
  • if both points have one, the server places B → A opposite the marker the agent arrived by, and the app turns to it and asks "looks right / move it".
  • if not, the app says "now mark the way back" and won't let a new point be added until it's placed.
  • the server reports missingReturnTo for a point, so the rule holds even when the point is reopened later.
bearing of the marker in A = A.heading + (x / A.width − 0.5) × 360
way back in B (as a fraction of width) = wrap((bearing + 180 − B.heading) / 360 + 0.5)
height = same fraction of the image height as the marker in A

the buyer page

what a buyer sees at /tour/<slug> (and inside an iframe at /embed/<slug>):

  • directory (left): the tour title and every point by number, thumbnail and name; tap one to jump there. open on wide screens with a close button; on phones it starts closed behind a "Rooms" button and closes again after a jump.
  • top: where you are ("Kitchen · 3 of 8") and a restart button (back to the first point, view reset).
  • bottom bar: previous / next point, turn around slowly (play/pause), look left / right (and up / down on wide screens — on a phone you drag), zoom in / out, full screen.
  • floor arrows in the panorama still walk to the linked point.
  • names: a point the agent hasn't named shows as "Point N". the app asks "name this point" (with one-tap ideas like Kitchen, Bedroom) the first time an unnamed point is opened, and the name at the top of the point page is tappable.

code: components/tour-chrome.tsx (everything around the panorama), components/tour-viewer.tsx (the panorama, transitions, and the handlers the bar calls). colours are the app's dark ground + lime (tour.* in tailwind.config.ts).

local preview without publishing: npm run dev in apps/web, then http://localhost:3002/tour/<slug>?preview=1 (works only on a development build, never on the deployed site).

server

route job
GET/POST /api/properties, GET/PATCH/DELETE /api/properties/[id] tours
POST /api/properties/[id]/spots/upload-panorama create a point + a presigned upload url
POST /api/spots/[id]/confirm-panorama after upload: normalise, thumbnail, mark ready, link the marker, place the way back
GET/PATCH/DELETE /api/spots/[id] one point (+ pending markers, missingReturnTo, resolvedConnections)
POST /api/properties/[id]/connections, PATCH/DELETE /api/connections/[id] markers
POST /api/connections/[id]/auto-resolve ai guess: does this marker lead to a point already captured
POST /api/properties/[id]/publish · unpublish make the tour public
GET /api/public/tours/[slug] what the buyer page loads (ready points + real links only)
/tour/[slug] · /embed/[slug] buyer page · the same without chrome, for iframes
GET /api/health · GET /api/mobile/latest-build wake check · update banner

database (prisma): Agent, Property, Spot, Connection, TourView. schema changes are applied to neon by hand (sql through the neon tool) and saved as a migration file — the render build does not run migrations.

server secrets live in render's environment (names only): DATABASE_URL, R2_*, GEMINI_API_KEY, REPLICATE_API_TOKEN, NEXT_PUBLIC_APP_URL, AUTH_ENABLED, ALLOW_AUTH_BYPASS_IN_PROD.

working on it

task how
change a screen (dart) python scripts/devloop.py --device RZCY90B4N4F --apk apps/mobile/build/app/outputs/flutter-apk/app-debug.apk --define API_BASE_URL=https://property-walk-web-2a4s.onrender.com, then curl localhost:18766/reload — about 2 s
change the camera (kotlin) flutter build apk --debug --dart-define=API_BASE_URL=… in apps/mobile (~3 min), then restart the dev loop
change the server commit + push the branch → render redeploys (allowed without asking for this project)
measure a capture's misalignment python scripts/capture_alignment_check.py <capture> → alignment.txt (movement vs direction error)
agent out of the floor (1) TargetOverlay hint on targets with pitch > 45° "Turn your whole body with the phone"; StitchTuning.maskBehindNadir = true; SeamFinder.holderSidePenalty (+HOLDER_SIDE_PENALTY 3000 when the direction's bearing is on the photo's holder side, i.e. against its horizontal up, for photos with forwardZ < −0.7; fades over cos 0.15). (2) tour-viewer.tsx nadir cover (OFF: SHOW_NADIR_COVER = false, owner 2026-11-26): THREE.Mesh(CircleGeometry) at y = −0.9R, NADIR_COVER_DEGREES 18 + 6 fade, renderer.addObject; three declared in apps/web/package.json (same version PSV brings), types/three-shim.d.ts. (3) PhotoSphereCameraScreen: on completion floorStep → FloorPhotoDialog → takePictureTo(session/floor.jpg) (+floor_pose.txt) → stitchPhotos(floorShot=); FloorPatch.plan (gnomonic down view 1400 px, ±62°; SIFT 5000; ratio 0.75; findHomography RANSAC 4 px; ≥25 inliers; ring NCC ≥ 0.35 on 22–40° from nadir, or ≥60 inliers and NCC ≥ 0.2; per-channel gain) and FloorPatch.apply (bottom 32°, 10° fade, Lanczos; × Plan.keep: blurred grey difference < 22 after gain, open/close, always within 16°, soft edge) on the normal and bent canvases before sharpening. DebugRestitch flag floor; capture_test.py pushes floor.jpg / floor_pose.txt
before-capture sheet upload_panorama_screen.dart _confirmHowTo() (modal bottom sheet, not dismissible): middle of the room / ≥1.5 m from things, phone at one height and distance + turn the body, up/down dots tilt only, floor photo; "I understand, start" opens the capture, Cancel returns. Not shown for "photos already on the phone"
R&D photo copy RndArchive.keep(context, sessionDir) (CaptureActivity.kt), called from startStitch on IO: copies the session (frames, floor.jpg, floor_pose.txt) to getExternalFilesDir/rnd_captures/<session>, keeps 6. Works in the release build (no run-as): capture_test.py pull-all falls back to adb pull /sdcard/Android/data/in.propertywalk.property_walk/files/rnd_captures
deskhand Tours tab explainer/tours.html = Always_Aware/rental_app_tours.html (deskhand.ca/rental_app/tours). No password to view: GET /api/owner/tours (list + draft embed key + fields + pointList; POST {password} kept for old copies). Card picture: coverImageUrl, else GET /api/owner/preview/<firstSpotId> → flat 800×500 view (80° fov, pitch −6°) of the panorama's middle column = the first photo's bearing, made once with sharp, cached in R2 previews/<spotId>.jpg, 302 to it. Edit button → dialog (title, address, city, price ₹ digits, bedrooms, bathrooms, area, point names) → POST /api/owner/tours/edit {password, propertyId, …, points[{id,name}]} (zod; password = TOURS_PAGE_PASSWORD; points must belong to the tour; one transaction; revalidateTour). CORS: lib/owner-cors.ts. Public in middleware: /api/owner/tours/edit, prefix /api/owner/preview/
bent joins on the phone stitching/SeamBend.kt: per pair of photos meeting on the seam grid (SeamWeights.labelMap), box = join cells ± 7° (shortest arc on the wrapping canvas; >60% canvas wide = skipped), both photos remapped alone (Lanczos, gains) → gray → DISOpticalFlow PRESET_MEDIUM (A(x)≈B(x+F)) → H = F/2 · (1 − d/band) on pixels owned by A or B within the band (BAND_DEGREES 7),
bent-joins second walkthrough python scripts/upgrade_tour.py <tour id|slug> (phone on USB, debug build): pull-all → match capture to point by time → seam_flow_join.join_capture(band 7, ref = live panorama) → align_to turns it to face like the live picture (arrows / initialYaw / headings stay valid) → apps/web/scripts/set-enhanced.mjs <spotId> bent.jpg → Spot.panoramaEnhancedUrl. Viewer switch label Normal ⇄ Bent joins (tour-viewer.tsx); default variant 'enhanced' and tour nodes load panoramaEnhancedUrl ?? panoramaUrl first. Remove: set-enhanced.mjs <spotId> --clear; replace the main picture: set-enhanced.mjs <spotId> <jpg> --main. Server tier-1 Real-ESRGAN no longer writes that slot unless ENHANCE_TIER1=on
seam bending (best laptop join so far) python scripts/seam_flow_join.py <capture> --band 7 [--around N] → runs/<date>_<capture>_seamflow_<tag>/ plain.jpg (app-style crisp join from native photos) / bent.jpg (DIS optical flow per join, each photo pulled half way, fades to 0 at 7°); ~75 s laptop at 4096 px. Not in the app yet
full-size bundle adjustment (failed) python scripts/full_res_join.py <capture>: directions + positions + depths solved together from native SIFT; ill-posed at 14 cm steps (turn vs slide look the same), diverges or freezes — kept for the record
depth-aware join experiment python scripts/depth_aware_join.py <capture> → runs/<date>_<capture>_depth/ flat / depth / solved (laptop only: opencv + scipy)
test capture settings python scripts/capture_test.py pull <label> / pull-all <label> / run <capture> [settings] → capture-tests/
keep a record of tours python scripts/archive_tours.py → capture-tests/tours/<slug>/<date>/ (tour.json + panoramas + notes.md); run before deleting a tour
rebuild the html python scripts/build_master_doc.py (manual.md → chapters, research.md → Research chapter (ids res-), master.md → technical reference; noindex meta)
research research/ — .env (gitignored, PROVIDER_KEYS= per provider, owner's own projects only, no client keys) · python research/check_keys.py → keys.md (which keys answer, credits) · python research/search.py web|similar|github|papers|reddit|youtube|fetch|summarize … --round <id> (Exa, Tavily, Firecrawl, TinyFish, gh, HF, Apify YouTube; Reddit via Firecrawl site:reddit.com; summaries DeepSeek) → research/rounds/<id>/, every call in research/usage.jsonl. Findings + ideas + tried table: master_doc/research.md
hosted docs Render static site property-walk-docs srv-dc40kc3l550s73fra3i0 (free; the workspace of RENDER_API_KEY in Desktop/Park Hotel/.env, same as deskhand.ca; edge cache up to 5 min), branch feature/photosphere-capture, publish master_doc, rewrite /*→/master.html only for /, auto-deploy. https://property-walk-docs.onrender.com + custom domain propertywalk-docs.deskhand.ca (Cloudflare CNAME, DNS only). master_doc/img/ is not in git → screenshots missing online

things that bite:

  • hot reload hangs if the phone is locked; the dev loop says so.
  • never run two android builds at once — it corrupts the apk (missing camera classes).
  • a push redeploys render and the next request is a cold start.
  • this laptop has 8 gb ram; one build at a time, nothing else heavy.

folders

folder what
apps/mobile/ the app
apps/web/ server + buyer pages
scripts/ devloop.py, capture_test.py, build_master_doc.py
capture-tests/ capture test bench + RESULTS.md (photos stay on this laptop)
master_doc/ manual.md (human manual), research.md (research chapter), master.md (this technical reference), master.html (built from all), img/ (screenshots, not in git)
research/ research tools, key check, rounds, usage log (.env gitignored)
planning/ research notes
docs/photosphere-upstream/ the borrowed engine's own docs, copied unedited (commit b5796d7) — see "the capture engine we borrowed"
explainer/ the localhost explainer page
human_response/ per-reply work log

decisions to talk about

  • sign-in is off: when do we turn clerk on, and does each agent get their own tours then?
  • the root CLAUDE.md still describes the old plan (arcore, server-side stitching, 25 dots, modal) — rewrite it to match this doc, or keep it as the "original vision"?
  • the free render server sleeps; pay for always-on before showing it to agents?
  • other phones: nothing is tested beyond the m36.
  • the leftover ghosting near the feet: accept, or try a "hold the phone close to your chest" instruction?
  • borrowed engine: add their two capture tips to our how-to sheet — "start facing the brightest part of the room" and "start facing the least important direction" (the join lands behind you)?
  • borrowed engine: brightness gains only run with photo matching on — solve gains from the overlaps without matching, so a lock that misses (window light, bulbs) is still evened out?
  • borrowed engine: vendor their unit tests (plan, projection, shutter gate, gpano) so our edits to those files are checked?
  • borrowed engine: "retake" throws the finished view away without asking — keep it, or add their "are you sure"?
  • borrowed engine: they are still pushing (last 23 nov) — check their commits now and then for fixes worth taking?

Engine reference

Everything in the camera engine we borrowed (photosphere-android): every feature, switch and number, with the notes its makers left in their code, docs and commit history, and what we changed. Start with "if something goes wrong with the camera" in the technical reference. These are the files in master_doc/engine/.

capture: sensors, lens, dot plan, shutter, CaptureActivity

engine reference — capture: sensors, lens, dot plan, shutter, CaptureActivity

part of the engine reference (master_doc/engine/). written 2026-11-26 by reading every file of our copy (commit 16eb526) against theirs (b5796d7), plus their docs, tests, tools and commit history. line numbers point at our code at 16eb526; the floor-photo commits after it (eff5cd1, 022767a) shift a few. levers were read from the code, not tried on the phone. start at master.md -> "if something goes wrong with the camera".

Sources: OURS = apps/mobile/android/photosphere/src/main/java/com/n30dyn4m1c/photosphere/ (committed state, scratchpad copy). THEIRS = theclumsypirate-photosphere-android-b5796d7/app/src/main/java/com/n30dyn4m1c/photosphere/. Line numbers are OURS unless marked "theirs". "Screen" = camera/PhotoSphereCameraScreen.kt (ours, committed). Diffed with diff --strip-trailing-cr (ours has CRLF line endings, theirs LF; files with no listed changes are byte-identical apart from line endings).

Context facts used for the status column (read from code, not inferred): - Upstream MainActivity is NOT registered in our library manifest (photosphere/src/main/AndroidManifest.xml comment + only .CaptureActivity declared), so upstream's SettingsScreen is unreachable in our app. - Screen L1818 passes showDebugDropdown = false (theirs L1564 passes true), so the capture HUD's debug dropdown (night mode, torch, plan type) is hidden in our app in every build. - Screen L1098: if (false) DebugTargetPlans.fullSphere(...) — the debug 36-frame plan is disabled; every build uses SphereTargetPlan.createForFieldOfView. - BuildConfig.DEBUG is the photosphere library module's own flag (buildConfig = true in photosphere/build.gradle.kts L39); true in debug APK builds (project builds flutter build apk --debug), false in release. Debug-gated levers below therefore ARE active in our usual test APKs. - Our dev phone is a Samsung Galaxy M36 (not S23/S21), so it gets the DEFAULT device profile.


AlignmentGate.kt — turns "aim held inside N degrees for M ms" into a shutter trigger; also holds the reticle state class

  • status: shipped-on
  • our changes vs theirs:
  • added AlignmentState.needsUpright: Boolean = false (L18-22) for the upright rule (which is switched off, see SphereCaptureCoordinator) — so it is always false at runtime.
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
DEFAULT_THRESHOLD_DEGREES 2f same max angle between aim and target that counts as "aligned"; also the reticle warm-up base (TargetOverlay L516) AlignmentGate.kt L81, or pass thresholdDegrees to AlignmentGate(...)
DEFAULT_DWELL_MILLIS 300L same how long the aim must stay inside the threshold before the shutter fires; dwell arc fill time AlignmentGate.kt L84, or pass dwellMillis
ctor thresholdDegrees / dwellMillis defaults same per-instance override caller is SphereCaptureCoordinator(gate = AlignmentGate()) (Coordinator L112), constructed as SphereCaptureCoordinator() at Screen L342 — pass a custom gate there
dwell <= 0 progress = 1 instantly same dwellMillis <= 0 makes it fire on first aligned sample L65
AlignmentState.needsUpright false (always, rule off) n/a (ours) shows "Hold the phone upright" notice set by Coordinator L242 only when UPRIGHT_RULE_ENABLED
  • authors' notes:
  • The dwell exists so a frame is never taken while the phone is still swinging through the target; at walking pan speed the reticle crosses a 2° window in well under 300 ms (L30-33).
  • No leniency: any single sample outside the threshold resets the timer, because a mid-swing frame is a blurred frame the stitcher would reject later (L33-35).
  • Clock is supplied by the caller and must be monotonic (SystemClock.elapsedRealtime()) so a wall-clock change cannot fire the shutter (L37-39).
  • The trigger is consumed on firing, otherwise it would fire again on the very next sample while the user is still holding still (L67-68).
  • 2° is "tighter than the stitcher needs, loose enough to hold by hand" (L80).
  • AlignmentState is kept separate so the overlay can be previewed without a sensor (L3-7).
  • features unused / off:
  • needsUpright path is dead while UPRIGHT_RULE_ENABLED = false.

CameraOptics.kt — works out the bound lens's on-screen field of view, radial distortion and portrait rotation

  • status: shipped-on
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
DEFAULT_SENSOR_FIELD_OF_VIEW 66f x 52f (sensor/landscape frame) same fallback FOV when the camera refuses to describe itself L28-31
MAIN_LENS_DIAGONAL_FOV_DEGREES 78f same on a logical multi-camera, the focal length whose diagonal FOV is nearest this is taken as "the main lens" L41
MAX_ESTIMATE_DISAGREEMENT 1.25f same if intrinsics-based FOV and geometry-based FOV differ by more than this ratio, the intrinsics are discarded and the geometry used L48
fallback sensorOrientation 90 same assumed sensor mounting when not queryable L153, L165
array choice SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, else SENSOR_INFO_ACTIVE_ARRAY_SIZE same which array the intrinsic focal length is measured against L167-170
rememberSphereOptics(cameraId, streamAspectRatio) Screen L358 passes boundCameraId, streamAspectRatio; ImportPhotosScreen L100 passes none (null, 0f) same which lens and stream crop the FOV is computed for; 0f = "same shape as sensor" callers
focal-length pick when preferWidest shortest focal same lens identification on multi-camera ids selectFocalLengthMm L285-299; driven by SphereDeviceProfile.preferWidestCamera
focal-length pick without sensor size longest focal same safe default (too narrow costs frames, too wide loses the run) L294
FOV clamp 1f..179f same all computed angles degreesFromTanHalf L376
radial distortion 3 radial terms of LENS_DISTORTION (API 28+), dropped unless isSignificant same lens edge correction handed to the stitcher; tangential terms ignored L231-242 (RadialDistortion.isSignificant lives in stitching/)
portraitRotationDegrees (sensorOrientation - displayRotation) mod 360 same stitcher's fallback rotation when a frame's EXIF orientation is missing L251, L265
DebugFovCalibration.apply called on every estimate same debug-only rescale (see DebugFovCalibration) L258
  • authors' notes:
  • Pass the bound camera id: a phone with three rear lenses will happily describe one while streaming another, and everything downstream (plan spacing, overlay rectangles, stitched-frame angle) scales by these numbers (L75-80).
  • A 16:9 stream off a 4:3 sensor is a crop, not a squeeze; passing the real ratio keeps the overlay honest about what a frame contains (L82-86, L331-340).
  • Two independent FOV estimates are made because either alone misleads on some phone; intrinsics are quoted against the pre-correction array, and using an array from another sensor mode is a factor-of-two error (L106-119).
  • A FOV overestimated by a third spaces the plan a third too wide and the first symptom is a run that will not stitch (L120-123).
  • Bug history: taking the first focal length of a logical multi-camera can hand back the ultrawide's 2.2 mm while the main lens streams — FOV nearly twice the truth, frames that do not overlap at all (L125-130).
  • The intrinsics-vs-geometry warning is logged specifically because "this is the case that used to space the capture plan past any overlap at all" — first thing to check on a run that will not stitch (L202-212).
  • Preview FILL_CENTER crop is handled downstream in SphereProjection.focalLengthPx, which expects the uncropped max FOV (L134-137).
  • Distortion coefficients are focal-normalized so carry no resolution; only radial terms are kept, tangential ones are negligible on phone lenses (L226-230).
  • A camera that will not describe itself still previews; markers ride on the default optics (L244-247).
  • Debug-only rescale exists because the reported active array covers more of the world than the cropped stills do (L254-257).
  • reconcileFieldOfView is deliberately framework-free so it can be unit-tested (L316-317).
  • features unused / off:
  • none in this file beyond the debug rescale (inactive on our M36, see next).

DebugFovCalibration.kt — debug-only per-axis FOV rescale solved from real Galaxy S23 runs

  • status: debug-only; unreachable on our phone (only Samsung SM-S911 / SM-S916 / SM-S918)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
SOLVED_HORIZONTAL_DEGREES 39.730f same content-solved horizontal FOV L32
SOLVED_VERTICAL_DEGREES 51.444f same content-solved vertical FOV L35
CLAIMED_HORIZONTAL_DEGREES 49.297f same what the camera reported L38
CLAIMED_VERTICAL_DEGREES 62.918f same what the camera reported L41
scale solved/claimed per axis, result clamped 1..179 same multiplier applied to the estimated FOV L44-45, L65-70
device gate MANUFACTURER "samsung" + MODEL prefix SM-S911/S916/S918 same which phones get the rescale isSolvedDevice L52-56
build gate BuildConfig.DEBUG same release builds pass through L63
  • authors' notes:
  • Matched features of a full run solved the focal to 1186 px on an 857x1142 decode (39.730 x 51.444°) versus the camera's own 49.297 x 62.918°: the camera reports the whole sensor's active array but guided-capture stills are cropped output, so every frame covers less than claimed and the plan leaves less overlap than intended (L10-18).
  • It rescales by ratio rather than replacing, so the stream crop still applies on top and another orientation keeps its own proportion (L20-23).
  • Gated to one phone and debug because the solved numbers belong to one phone's main lens; release capture/stitch behaviour must not move (L25-27).
  • features unused / off:
  • To get the same correction on the M36: solve its FOV from a real run and add its model prefix and numbers here (or generalise to a per-model table). Not done today.

GuidanceFeedback.kt — non-visual guidance: distance beeps, dwell haptic tick, spoken next-target cue

  • status: shipped-on but default OFF: guidanceEnabled starts as context.isScreenReaderActive() (Screen L333-335); a speaker toggle top-right of the HUD (Screen L2042-2064) turns it on.
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
BEEP_MAX_DISTANCE_DEGREES 40f same beyond this angle from the target, no beeps L29
beep interval range 90 ms (at 2°) to 900 ms (at 40°), linear same beep rate = distance cue L58-62 (the 2f floor is hard-coded, not linked to AlignmentGate.DEFAULT_THRESHOLD_DEGREES)
dwell milestone 0.5 of dwell progress same when the haptic tick fires L73-74
target-relation thresholds ±0.12 on camera-frame unit vector x/y same "above/below/left/right/centre" wording for announcements L88-97
TONE_VOLUME_PERCENT 60 same beep loudness (0..100) L203
BEEP_TONE_MILLIS 60 same length of each beep L206
tone stream / tone AudioManager.STREAM_MUSIC, TONE_PROP_BEEP same which volume slider controls beeps; tone type L129, L159
haptic EFFECT_TICK (API 29+), else 20 ms one-shot same dwell tick L167-171
TTS locale / queue Locale.US, QUEUE_FLUSH same announcement language; new cue replaces old L149, L189
caller loop delays 250 ms (out of beep range), 40 ms (dwell poll), 150 ms (idle) same guidance loop cadence Screen L644, L659, L664
announcement settle 600 ms same only a target the aim stays on is spoken Screen L681
first target not announced skip when buffer empty same — Screen L677
  • authors' notes:
  • Beyond 40° a slow tick from a target behind you reads as noise; the spoken announcement on target change is the cue that far out (L23-28).
  • Purpose: guided capture is entirely visual, so a blind or low-vision user had no way to find the target or feel the dwell (L35-42).
  • Announcement thresholds are deliberately wider than the aim tolerance: they exist to get the user facing the right way, not to fine-tune the last degree (L82-85).
  • Phrases are English-only for now, so the TTS locale is pinned to US English (L146-148).
  • Announcements queued while TTS warms up are kept, because a missed cue means turning around blind (L180-181).
  • The KDoc of crossedDwellMilestone is garbled in the source ("The crossing is also marked by dwell haptics. of the end") — a broken sentence upstream (L69-71).
  • features unused / off:
  • Whole feature off by default for sighted users; tap the speaker icon on the capture HUD. To default it on, change Screen L334 to mutableStateOf(true).

NightCaptureExtensions.kt — night-mode burst: N stills at one pose, merged on-device by NightFrameMerger

  • status: unreachable in our app (only toggle lives in the HUD debug dropdown, which our Screen hides with showDebugDropdown = false at L1818; debugNightEnabled defaults false, Screen L347)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
nightConfig.framesPerTarget from device profile (DEFAULT 8) same stills fired per target SphereDeviceProfile NIGHT_DEFAULT / per-device config
nightConfig.minFramesForMerge DEFAULT 4 same fewer successful frames than this fails the target same
activation debugNightEnabled && profile.nightMode != null && profile.nightModeSupported same (but dropdown visible upstream) whether saveNightBurst is used instead of saveFrame Screen L1148
merge thread Dispatchers.IO same — L76
log TAG "NightCapture" same logcat tag (not the shared Logging.TAG) L19
  • authors' notes:
  • Captures N frames at the same pose, merges on device, commits one merged frame (L21-26).
  • All burst requests are fired back-to-back with no spacing (L41-59); failure deletes the burst files (L67, L84).
  • The currentOrientation parameter is accepted but never used in the body; the committed pose is the dwell mean dwellOrientation (L32, L89).
  • features unused / off:
  • To turn on: pass showDebugDropdown = true at Screen L1818 (exposes the night toggle), or set debugNightEnabled default true at Screen L347. Requires nightModeSupported (see SphereDeviceProfile checkNightModeSupport).

OrientationSmoother.kt — display-only smoothing of the attitude stream so the overlay doesn't tremble

  • status: shipped-on (TargetOverlay L140, default parameters)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
SMOOTHING_ALPHA 0.3f same EMA weight per sample (~60 ms time constant at 50 Hz) L132, or ctor alpha
SNAP_DEGREES 3f same per-sample jump larger than this is passed straight through (pan, not tremor) L138, or ctor snapDegrees
NOISY_ALPHA 0.25f same heavier EMA for non-gyro (magnetometer-only) samples L146
MEDIAN_WINDOW 3 same median-of-3 prefilter for non-gyro samples; "must stay three" L149
ctor call OrientationSmoother() same — TargetOverlay L140
  • authors' notes:
  • Attitude arrives ~50 Hz with ±0.5-1° noise/tremor; drawn raw the overlay trembles (L10-13).
  • Bug history: phones without a gyroscope are magnetometer-only and their yaw jitters several degrees per sample, past the snap threshold every frame, so every jitter passed through and the target marker wandered; those samples now go through a median + heavier average (L18-25).
  • Display only: capture decisions and frame poses must stay raw, a smoothed pose would smear the dwell mean and the stitch start guess (L27-29).
  • The median only runs once the window is full; fewer than three would pass the newest noisy value through (L78-79).
  • Wrapped median takes the short way round the ±180° seam so markers don't swing the long way (L119-123).
  • features unused / off:
  • Non-gyro path only runs when the tracker falls back to TYPE_ROTATION_VECTOR (no game vector), i.e. not on phones with a gyroscope.

SamsungHighRes.kt — Samsung-only full-sensor (64/108 MP) still capture via a raw Camera2 session, plus an "ultrawide preferred" pref

  • status: unreachable in our app. probe/captureStill/setUltrawidePreferred are only called from upstream SettingsScreen (not reachable: MainActivity unregistered). isUltrawidePreferred IS read at Screen L322 (debug + Samsung) but can only return its default false.
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
HIGH_RES_TIMEOUT_MILLIS 45_000L same max time for one full-res still L252
JPEG_QUALITY 95 same full-res still JPEG quality L185
min SDK 29 same probe refuses below Android 10 L64
PREFS / KEY_ULTRAWIDE "samsung_highres" / "prefer_ultrawide", default false same when true (debug+Samsung), Screen forces preferWidestCamera = true L254-260; Screen L322-323
session SESSION_REGULAR, one ImageReader (maxImages 1), TEMPLATE_STILL_CAPTURE same — L140-186
  • authors' notes:
  • CameraX only walks getOutputSizes, so its stills top out at the binned 12-17 MP; the full sensor is in getHighResolutionOutputSizes and needs its own Camera2 session — documented AOSP path, no vendor key (L31-41).
  • Preview must be released first; callers unbind CameraX or call from a screen holding no camera (L42-44).
  • Takes seconds on 64 MP sensors; call off the main thread, camera permission required, no other session open (L104-108).
  • openCamera has no cancel; the callback guards completion (L247-249).
  • features unused / off:
  • Full-res stills are not part of capture at all (SphereDeviceProfile L138-142 says the S21 64 MP mode deliberately lives behind the Settings test button).
  • To force the ultrawide on a debug Samsung build without Settings: call SamsungHighRes.setUltrawidePreferred(context, true) once — but our DEFAULT profile already has preferWidestCamera = true, so it changes nothing on the M36.

SharpnessSelection.kt — picks the sharpest of a burst by variance of the Laplacian

  • status: shipped-on (DEFAULT burstPerTarget = 2 → Screen L3076-3080 calls sharpestIndex)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
SCORE_FULL_FRAME_LONG_EDGE 2000 same resolution the score is computed at (meant to equal stitch input) L35 (note: matches our stitchMaxInputDimension = 2000; upstream DEFAULT used 1024)
SCORE_CENTER_FRACTION 0.5f same centred fraction of each axis decoded and scored L38
luma weights 0.299 / 0.587 / 0.114 same grey conversion L96
tie rule first file wins same — L41, L53 (strict >)
burst size SphereDeviceProfile.burstPerTarget (DEFAULT 2) same how many candidates per target SphereDeviceProfile L83
  • authors' notes:
  • Assumes a burst is shot at the same locked exposure/focus/colour so frames differ only by handheld motion (L14-16). In our build the AE/AWB lock is applied only after the first photo lands (Screen L1174-1185), so the first target's burst is not exposure-locked (code fact; effect on scoring unverified).
  • Scored at stitch resolution, not a thumbnail: a few pixels of shake smear on 12 MP is visible at 2000 px and vanishes at a few hundred px, where every candidate scores the same and the pick is a coin toss (L20-24).
  • Region decode of the centre keeps scoring to tens of ms per candidate (L24-26).
  • EXIF rotation is irrelevant to the score; centre crop is the same either way (L109-110).
  • Falls back to a whole-frame decode if the region decoder refuses the file (L125-127).
  • Bug guard: dimensions are read before recycle(), because a recycled bitmap's accessors are undefined and would silently pick the wrong frame (L129-131).
  • features unused / off: none.

SphereCaptureCoordinator.kt — the capture loop's decision maker (target choice, accuracy gate, dwell, pose mean, undo/reset race safety)

  • status: shipped-on
  • our changes vs theirs:
  • added the "upright rule" block (L225-245) and its four constants (L386-396); switched off (UPRIGHT_RULE_ENABLED = false).
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
DEFAULT_POSE_WINDOW_SIZE 20 same max samples averaged into the pose stamped on a frame (window is emptied whenever the aim leaves the gate) L12, or ctor poseWindowSize (Screen L342 uses default)
ctor gate AlignmentGate() (2°, 300 ms) same dwell rule L112
accuracy gate orientation.accuracy.allowsCapture (refuses only Unreliable) same no shutter while the fused sensor says it is unreliable L217; rule in OrientationTracker.kt L123
canTrigger Screen passes hasLockedOnce same param holds the shutter until the session's AE/AWB has locked at least once Screen L1087
isStitching Screen passes stitchJob != null same holds the shutter during a stitch Screen L1081
UPRIGHT_RULE_ENABLED false n/a (ours) require phone roll within limit for tilted targets L387
UPRIGHT_RULE_MIN_TILT_DEGREES 45f n/a targets with abs(pitch) above this are subject to the rule L390
UPRIGHT_RULE_NEAR_DEGREES 8f n/a rule only applies once aim is within this of the marker L393
UPRIGHT_RULE_MAX_ROLL_DEGREES 45f n/a max abs(roll) still counted as upright L396
  • authors' notes:
  • Why a class with one Mutex and not a LaunchedEffect: bug history — an undo tapped during the hundreds of ms a capture takes to write read/wrote activeIndex between the capture's read and write; last writer won and the reticle pointed at a target never shot (L97-106).
  • Undo during a shutter is refused outright; the caller also disables the button, this is the backstop (L342-346).
  • CaptureToken/epoch: a frame landing after a reset or undo is discarded rather than advancing a plan it was not aimed at (L50-59, L288-291, L365-368).
  • Pose mean window is all deliberate stops; anything ending a dwell empties it so a mean never spans two aims (L118-125, L257-260).
  • captured is read under the lock so a sample queued behind an undo sees the post-undo buffer; a stale set would steer the reticle straight off the undone target (L149-154).
  • canTrigger false because a still fired mid-convergence is pinned to a half-converged (on a dark scene near-black) exposure; the gate re-dwells until exposure lands (L155-158, L265-268).
  • Shutter blocked during a stitch: a frame landing mid-stitch would not be in the stitched set and would be deleted with it (L146-148).
  • A new active target restarts the dwell so old samples do not leak into the new pose mean (L203-204).
  • Only Unreliable blocks: an unreliable magnetometer drifts aim by degrees even when still; merely uncalibrated is fine (L212-216).
  • Upright rule history: first test tour 2026-11-25 showed rolls of -76, 163 and 74° on tilted shots — agents twisted the phone so one photo looked back at their body; rule forced turning the whole body. Switched off after the first real try because ceiling/floor dots refused to fire; owner accepts feet visible looking down (L225-234, L386).
  • A failed capture keeps the run on the same target so it is retried, not skipped (L320-321).
  • features unused / off:
  • Upright rule: set UPRIGHT_RULE_ENABLED = true (L387); the overlay already draws the "Hold the phone upright" notice when needsUpright is set (TargetOverlay L186-188).

SphereCaptureProfile.kt — per-lens focus/AE/AWB/OIS policy and back-camera selection

  • status: shipped-on
  • our changes vs theirs:
  • FOCUS_POINT now sets CONTROL_AF_MODE_CONTINUOUS_PICTURE (L253-260); theirs CONTROL_AF_MODE_AUTO (theirs L258).
  • applyStillImageOptions no longer sets CONTROL_AE_LOCK/CONTROL_AWB_LOCK (L285-291); theirs set both when supported (theirs L284-289). Our Screen instead locks AE/AWB once the first photo lands (Screen L1174-1185).
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
AF mode for focusable lens CONTROL_AF_MODE_CONTINUOUS_PICTURE CONTROL_AF_MODE_AUTO whether the lens keeps refocusing during the sweep L257-260
AF mode for fixed-focus lens CONTROL_AF_MODE_OFF same — L246-251
fixed-focus test LENS_INFO_MINIMUM_FOCUS_DISTANCE <= 0 (null → FOCUS_POINT) same picks FIXED_FOCUS vs FOCUS_POINT resolveFocusMode L86-91
AE/AWB lock on stills not set set when aeLockSupported/awbLockSupported still requests re-meter vs pinned L285-291
resolveLockSupport null → true same unknown lock capability treated as supported L101
OIS LENS_OPTICAL_STABILIZATION_MODE_ON on stills when lens lists it same optical stabilisation on captures (not preview) L292-297, resolveOpticalStabilization L104-105
MIN_WIDE_SENSOR_PIXELS 6_000_000L same smallest pixel array accepted as a real "wide" lens (excludes depth/macro) L199
logical multi-cameras skipped in widest search (API 28+, physicalCameraIds non-empty) same — L178-182
widest lens rule smallest min focal length among back cameras same which lens preferWidestCamera binds widestBackCameraId L166-196
main lens rule first back-facing id in cameraIdList same fallback / preferWidestCamera = false defaultBackCameraId L202-210
profile resolve with no characteristics FOCUS_POINT, locks true, OIS false same conservative profile L119-153
  • authors' notes:
  • Seams on a sphere are exposure/colour seams; per-frame AE/AWB gives three brightnesses and colour temperatures no blend can hide — hence "lock exposure and focus, then sweep" (L19-27).
  • Bug history: locking from the stream's first frame pins the HAL's bright-scene start-up defaults, leaving a dark scene permanently black; locks must come after 3A converges (L29-37).
  • Ours: CameraX merges a use case's Camera2Interop options into the session's repeating request, so upstream's "stills-only" AE/AWB locks froze the live preview from frame one — blown-out white (morning test) and a green cast on the Galaxy M36 (A/B vs Samsung camera: ours 231/242/213, stock neutral); exposure/WB left automatic until the first photo, stitcher gain compensation evens the seams (L285-291).
  • Ours: upstream AUTO + one centre trigger at bind focused the M36 main lens on whatever it faced at that moment (often the desk) and never refocused — every frame soft (L253-256).
  • The class KDoc (L41-48) and FocusMode.FOCUS_POINT doc (L69-75) still describe upstream's AUTO tap-to-focus lock; stale in our build.
  • Note (code fact): Screen L1065-1066 still calls lockFocusAt(0.5f, 0.5f) (a FocusMeteringAction AF trigger, Screen L3144-3145) at bind for FOCUS_POINT, now on top of continuous AF; how the HAL combines them is unverified.
  • Widest lens wins upstream because a wider frame roughly halves the frame count — on a Galaxy S23 the 12 MP ultrawide rather than the 50 MP main (L159-162).
  • Logical multi-cameras report their widest physical lens but are not individually bindable, so they are skipped (L162-164).
  • Unknown lock characteristic = supported; an unsupported key is just ignored by the HAL (L96-100).
  • OIS belongs on the capture not the preview (L268).
  • features unused / off:
  • AE/AWB-locked stills (upstream behaviour): restore L282-291 to theirs (not recommended per the M36 finding).
  • aeLockSupported/awbLockSupported are still computed but not read by applyStillImageOptions any more.

SphereDeviceProfile.kt — per-phone tuning: lens choice, still size, burst, stitch resolution, sharpening, pivot, night config

  • status: shipped-on (DEFAULT on our M36)
  • our changes vs theirs:
  • DEFAULT stitchMaxInputDimension 2000 (theirs 1024, theirs L78).
  • added comments explaining preferWidestCamera = true was briefly switched to main lens on 2026-11-25 and put back (L75-80).
  • levers:
lever value in OUR build (DEFAULT) value in THEIRS what it controls how to change it
preferWidestCamera true same widest back lens vs main lens L81
captureMaxLongEdgePx 4000 same cap on still capture size L82
burstPerTarget 2 same stills per target, sharpest kept L83
stitchMaxInputDimension 2000 1024 long edge frames are decoded to for stitching L86
stitchMaxOutputWidth 4096 same finished sphere width cap (height = half) L87
unsharpAmount 0f same unsharp mask on finished canvas (0 = off) L88
pivot PivotModel.HandheldBodySwivel (= lever arm 0.35 m, scene 10 m; stitching/PivotModel.kt L71) same parallax correction for swinging around the body L89
nightMode NIGHT_DEFAULT same night burst config L90
NIGHT_DEFAULT framesPerTarget 8, maxExposureTimeMs 250, maxIso 1600, WeightedAverage, ECC, minFramesForMerge 4, alignDownscale 0.5, medianTileSize 512 same night merge L57-66
SAMSUNG_S23 (SM-S911/S916/S918) widest false, 4000, burst 3, input 2000, output 6144, unsharp 0.3, HandheldBodySwivel; night 16 / 500 ms / ISO 6400 / Median / ECC / min 6 / 0.5 / 512 same S23 tuning L115-133, detect L237-241
SAMSUNG_S21 (SM-G991/G996/G998) widest false, 4000, burst 3, input 2000, output 6144, unsharp 0.3, HandheldBodySwivel; night 12 / 333 ms / ISO 3200 / Median / ECC / min 5 / 0.5 / 512 same S21 tuning L144-162, detect L243-247
DEBUG_SCENE_DISTANCE_METERS 3.0f — overrides pivot scene distance (10 m → 3 m) for EVERY profile in debug builds same pivot correction strength in debug APKs L235, applied L175 / L222-232
nightModeSupported true if any back camera is HW level 3 or EXTERNAL, or lists BURST_CAPTURE same gates night mode checkNightModeSupport L182-210
Screen override debug + Samsung + isUltrawidePreferred → preferWidestCamera = true same — Screen L317-327
  • authors' notes:
  • Single place a phone is tuned; detection keys off the model so a new flagship is a few lines here (L15-23).
  • Widest trades sharpness for speed — far fewer frames (L28-30).
  • DEFAULT KDoc still says "compact 1024 → 4096 profile" (L69-73); stale in ours (2000).
  • Ours: ultrawide looked green on the M36, briefly swapped to main lens 2026-11-25; real cause was the AE/AWB locks merged into the preview; ultrawide ~96°x80° covers a full sphere in ~11 frames vs a 360°x86° band in 12 on main (L75-80).
  • Ours: at 1024 the M36's 3264 px stills were decoded at 816 px and the sphere came out 2760 wide (L84-85).
  • S23: 50 MP main is sharper (better glass, OIS, bigger sensor) at ~33 frames instead of ~11; stills capped at 12 MP binned because 50 MP only slows the burst; stitch 2000 → 6144 (Google Photo Sphere standard is 5376); burst 3 + light sharpen without haloing unshot parts (L96-113).
  • S21: same shape; the 64 MP tele mode needs its own session so lives behind Settings (L138-142).
  • Debug pivot: pilot runs used 3.5 m scene distance and the test room is that close, while shipped nominally assumes 10 m; the pose refiner absorbs the rest (L212-221). The constant is 3.0 m, not 3.5 m (L235) — comment/value mismatch upstream.
  • Night support check treats INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL as "supports night mode" (L194-195) — code as written.
  • features unused / off:
  • Night mode (UI hidden, see NightCaptureExtensions).
  • unsharpAmount is 0 on DEFAULT; S23/S21 use 0.3 — set DEFAULT L88 to enable sharpening on our phone.
  • No M36-specific profile exists; add one with an isSamsungGalaxyM36() check in forDevice (L165-176) to tune it without touching DEFAULT.
  • Release builds use pivot scene distance 10 m, debug builds 3 m — a debug/release behaviour difference to keep in mind when promoting.

SphereProjection.kt — pinhole projection of targets into the camera frame; angular distance used by the trigger

  • status: shipped-on
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
TargetView.MIN_FORWARD_COMPONENT 1e-3f same depth below which a target counts as behind the camera L53
FieldOfView valid range 1f..179f (both axes, require) same throws outside L22-23
focalLengthPx max of horizontal/vertical candidates same single focal for FILL_CENTER preview L79-83
roll in distance ignored same trigger distance depends only on aim, not roll L141-147
elevation -pitchDegrees same sign convention L186
  • authors' notes:
  • FOV here is in screen axes; on a portrait phone vertical is the wider one (L13-15).
  • Plain rectilinear model = what the lens does, so "centre the reticle on the dot" lands on the real pixel (L60-64).
  • The larger focal keeps both axes inside the FOV with the other cropped — what fill does (L74-77).
  • Camera axes built once per draw: a few hundred markers at display rate, nine multiplies each (L92-95).
  • Roll deliberately ignored: demanding a level device would make the sphere far more tedious (L141-144).
  • features unused / off: none.

SphereTarget.kt — the capture plan: rings of targets, spacing from the lens FOV, boustrophedon order

  • status: shipped-on (via createForFieldOfView, Screen L1101-1105)
  • our changes vs theirs:
  • ring frame count now coerceAtLeast(minimum) where minimum = HORIZON_RING_FRAMES (16) for the 0° ring and MIN_TILTED_RING_FRAMES (4) otherwise (L262-271); theirs coerceAtLeast(1) (theirs L262).
  • added constants HORIZON_RING_FRAMES = 16 (L292) and MIN_TILTED_RING_FRAMES = 4 (L295).
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
HORIZON_RING_FRAMES 16 (22.5° apart) n/a (lens-derived count) minimum frames on the eye-level ring (also the only ring in Ring scope) L292
MIN_TILTED_RING_FRAMES 4 n/a (min 1) minimum frames on any tilted ring L295
DEFAULT_TARGET_OVERLAP_FRACTION 0.35f same fraction of each frame its neighbours overlap; sets yaw spacing and ring step L156; or pass targetOverlapFraction (Screen doesn't)
FIELD_OF_VIEW_SAFETY_FACTOR 0.9f same fraction of reported FOV the plan spends (both axes) L170
MAX_RING_ELEVATION_DEGREES 75f same highest ring centre L283
yaw spacing hFOV*0.9*(1-0.35) at the equator, widened by 1/cos(elevation) same frames per ring before minimums L225, L258-261
pole guard cos(elev) <= 1e-3 → spacing 360 same — L261
ring step vFOV*0.9*(1-0.35) same spacing of rings L313
top-ring cap min(75, max(step, 90 - vFOV/2 + step/2)) same how high the top ring sits L317-320
intermediate ring cutoff only while elevation < cap - step/2 same avoids near-duplicate zenith ring L327
ring order 0°, up rings ascending, then the same down (negated) same capture order L336
boustrophedon every odd ring reversed same sweep direction alternation L245
RING_ELEVATIONS (Ring scope) [0f] same single eye-level ring L230
createForFieldOfView params caller passes startYaw, fov, scope only; ringElevations null, overlap default same manual ring list / overlap override L202-208, Screen L1101-1105
startYawDegrees bearing at first fix (kept across config changes) same plan anchor Screen L1093-1095
DEFAULT_RING_ELEVATIONS [0, 30, 60, -30, -60] same only used by create() (previews/tests) L130
DEFAULT_EQUATOR_SPACING_DEGREES 30f same only used by create() L138
  • authors' notes:
  • Spacing widens by 1/cos(elevation) so neighbours stay a constant angular distance apart; bunched frames cost time and buy the stitcher nothing (L81-85).
  • Boustrophedon so each ring ends where the next begins, no spinning back through 360° (L87-89).
  • Rings are tracked so the screen can say "horizon done" at the moment a ring closes; a run stopped mid-ring has a gap (L91-95).
  • 35% overlap is what the feature-based pose refinement needs; it used to be 50% when the FOV was a guess; now the FOV is read off the bound camera, so ~a third fewer frames per ring (L141-155).
  • Safety factor was "a fifth" (0.8) when the FOV was a guess, now "a tenth"; overestimating FOV eats the overlap first (L159-169).
  • Anchoring on the current bearing avoids asking the user to find north (L175-177).
  • Ours: minimum 4 on tilted rings because on an ultrawide upstream gives only 2 frames at ±75°, leaving the sides (90° from both) with almost no overlap against the horizon ring around 46-50° elevation (L262-265).
  • Ours: horizon count chosen on the bench 2026-11-26 — one 24-around capture re-joined at 8/12/16/24: only 16 was clean on the chair, door/AC and fridge; 12 doubled the chair back, 24 doubled the AC and fridge edge (more joins, more chances) (L285-291).
  • Stale comment: the inline comment at L266-269 still says "12 around at eye level ... 30° apart (~18 cm) ... lens alone would allow 8 (45° apart, ~27 cm)"; the constant is 16.
  • The horizon test is exact float equality elevationDegrees == 0f (L270); the horizon ring is always laid at exactly 0f, so it matches.
  • The intermediate-ring cutoff exists because an ultrawide (step ~70°, cap ~72°) would otherwise produce a near-duplicate zenith ring (L322-325).
  • Up rings first then down rings, not interleaved, so the user isn't swung between ceiling and floor every ring pair (L332-335).
  • Ring scope output is still equirectangular with sky/floor black (L65-71).
  • MAX_RING_ELEVATION_DEGREES: going higher breaks the constant-overlap guarantee of the 1/cos widening (L276-282).
  • features unused / off:
  • Manual ring lists (ringElevations) and per-call overlap are supported but never passed.
  • create() with fixed 30° spacing / fixed 5 rings is unused in the shipped path.

TargetOverlay.kt — the viewfinder HUD: reticle, dwell arc, target dots, guide arrow, edge chevron, text hints, focus box

  • status: shipped-on
  • our changes vs theirs:
  • dashed guide line replaced by a bold pulsing arrow drawGuideArrow (L463-473, L583-631); arrow also drawn alongside the edge chevron when the target is behind or off screen (L414-419, L440-445).
  • direction words "Tilt up/down / Turn left/right" (L163-174, L633-659).
  • floor hint "Turn your whole body with the phone" for targets with pitch > 45° (L176-183) and "Hold the phone upright" notice for needsUpright (L185-188), drawn by drawNotice (L661-680).
  • chevron length 22dp (theirs 14dp, theirs L524); ACTIVE_RING_BASE_DP 24dp (theirs 16dp); ACTIVE_CORE_RADIUS_DP 10dp (theirs 5dp).
  • new constants OFFSCREEN_ARROW_REACH_FRACTION, FLOOR_HINT_PITCH_DEGREES, DIRECTION_LABEL_MIN_DEGREES; text measurer imports.
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
FOCUS_TRANSITION_MILLIS 350 same grow-in of a newly active marker L43
PULSE_PERIOD_MILLIS 1600 same pulse of active ring and arrow bead L46
colours reticle white 0.9 alpha; aligned = theme primary; active = theme secondary; pending white 0.32; guide white 0.24 same HUD colours (Material You aware) L66-83, themed() L76
RETICLE_RADIUS_FRACTION 0.16f of short side same reticle ring size L753
reticle warm-up fully warm at threshold (2°), cold at threshold + 6° same white→green as aim closes L513-518 (comment says "~4x the threshold")
reticle strokes ring 3dp, centre dot 2.5dp, ticks 10dp, halo +8dp 1.5dp alpha 0.10+0.18·closeness, dwell arc 1.5x stroke same look L508-558
EDGE_MARGIN 28dp same inset of the visible area for dots L743
EDGE_HYSTERESIS 48dp same how far past the margin the active dot slides before turning into a chevron L750
COMPLETED_DOT_RADIUS_DP / PENDING_DOT_RADIUS_DP / PENDING_DOT_STROKE_DP 5dp / 7dp / 1.5dp same dot sizes L756-762
ACTIVE_RING_BASE_DP 24dp 16dp active target ring radius L765
ACTIVE_RING_BREATH_DP 6dp same ring pulse amplitude L768
ACTIVE_CORE_RADIUS_DP 10dp 5dp active target solid core L771
active ring alpha (1-pulse)*0.6*focus same — L479
edge chevron length / alpha 22dp / 0.55+0.45·focus 14dp / same off-screen pointer L569, L422
guide arrow (ours) head 16dp, shaft 6dp over 10dp black 0.45 shadow, white bead 4dp, starts reticle+10dp, skipped if shorter than 1.5 heads dashed 1dp line (6dp dash / 8dp gap) on-screen "move this way" cue L590-631
guide arrow cutoff separation > reticle radius + 24dp same cutoff for the dashed line when the arrow appears L464
OFFSCREEN_ARROW_REACH_FRACTION 0.40f of short side n/a arrow length when target is behind/off screen L683
DIRECTION_LABEL_MIN_DEGREES 12f n/a direction words only while target is at least this far L689
FLOOR_HINT_PITCH_DEGREES 45f (pitch positive = below horizon) n/a floor targets that show the "turn your whole body" notice L686
label/notice text 22sp bold (+16sp white detail), bg black 0.6 / 0.7, corner 18dp, top = reticle radius + 150dp below centre n/a words under the reticle L644-680
hint strings "Turn your whole body with the phone" / "keep it out in front of you, don't twist it"; "Hold the phone upright" / "and turn your body to face the dot" n/a hard-coded English, not string resources L182, L187
focus box 44dp, grows 1.35x while working, 240 ms appear, 14dp corners, 2.5dp stroke, 0.10 wash same tap-to-focus square L235-282
  • authors' notes:
  • Orientation/alignment are lambdas read inside the draw so a 50 Hz sensor never triggers recomposition (L94-97).
  • Bug history: a full-screen white shutter flash was removed because it read as flicker on slow HALs (burst + preview stall); sound + haptic confirm instead (L136-139).
  • Overlay draws a smoothed pose; capture decisions stay raw (L132-135).
  • Edge hysteresis: a target on the margin flipped dot↔chevron every sample because ±0.5° of noise moves the projection tens of px out there (L428-432, L745-749).
  • Without the chevron fallback the first frame of a new target would leave an empty viewfinder and no idea which way to go (L395-398).
  • Ours: the faint dashed line was replaced because agents could not tell which way (or when) to tilt up and down (L465-466).
  • Ours: floor hint exists because floor photos keep the agent out only if they turn with the phone instead of twisting it in the hand (L176-178).
  • Reticle warm-up distance is taken from the smoothed pose so colour and markers agree; dwell progress stays raw because it is capture truth (L700-708).
  • Y is negated in the pinhole divide because camera up is screen down (L720-722).
  • Dead-ahead/dead-behind has no direction; picks (1,0) (L736-737).
  • Code fact: the direction label and the floor notice are drawn at the same top (L650 and L668), so on a floor target more than 12° away both boxes overlap.
  • Code fact: with the upright rule off, the "Hold the phone upright" notice can never appear; the floor hint shows for every floor target.
  • features unused / off:
  • needsUpright notice (needs UPRIGHT_RULE_ENABLED).
  • TargetOverlayColors.Default is only used by previews; runtime uses themed(primary, secondary) (L113-116).

TargetSelection.kt — which target is active when markers may be shot in any order

  • status: shipped-on
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
CLAIM_DEGREES 6f same aim within this of another uncaptured dot makes it active L28
CLAIM_HYSTERESIS_DEGREES 1.5f same the other dot must be this much nearer than the active one L38
SUCCESSOR_BIAS_DEGREES 12f same head start for the plan's next target after a shot L48
  • authors' notes:
  • Like Street View, any marker can be shot: fill a visible gap, dodge a person in the next frame, or shoot in whatever order your feet prefer (L8-14).
  • 6° is outside the gate's 2° (claim happens before a dwell could start) and far inside neighbour spacing "25°+" (L24-26). In our build the horizon ring is 22.5° apart (16 frames), still well above 6° (arithmetic fact).
  • Hysteresis stops ±0.5° sensor noise flipping the active index between two dots, which restarted the focus animation and dwell and read as flicker (L34-36).
  • Successor bias: after a shot both ring neighbours are about equally far, and choosing on a fraction of a degree would flip sweep direction at random (L43-46).
  • A user already on the active target is never pulled off it (L79-82).
  • features unused / off: none.

OrientationTracker.kt (sensor/) — fused attitude source (game rotation vector), camera-frame angles and basis matrix

  • status: shipped-on (rememberOrientationTracker() with defaults, Screen L295)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
samplingPeriodUs SensorManager.SENSOR_DELAY_GAME (~50 Hz) same sensor delivery rate ctor L200 / rememberOrientationTracker(samplingPeriodUs=) (OrientationState L27); Screen L295 uses default. Manifest declares HIGH_SAMPLING_RATE_SENSORS but the default never asks for it
reference OrientationReference.Camera same camera-frame vs Android screen-frame angles ctor L201
attitude sensor TYPE_GAME_ROTATION_VECTOR, fallback TYPE_ROTATION_VECTOR same gyro+accel only vs magnetometer-fused L222-224
accuracy for game vector always Unknown (never published) same game vector can never block the shutter L235, L433, L473
accuracy rule callback wins; event accuracy can only raise; event "unreliable" ignored if callback silent same what reaches allowsCapture on the fallback sensor L432-438
isGyroAssisted true for game vector, false for fallback same drives smoother's noisy path L397
INFO attitude log once per 1000 ms; VERBOSE every sample same logcat volume L399-412
malformed event < 3 values dropped; > 4 truncated to quaternion same vendor quirks L348-359
thread dedicated HandlerThread("orientation-sensor") same — L32, L301
  • authors' notes:
  • Game vector is what Street View and Google Camera Photo Sphere use: a sphere needs frame-to-frame consistency, not north; a magnetometer can make a still phone's heading jump by degrees (steel beam, laptop, rebar), each jump a frame off target; gyro-only drift is a fraction of a degree per minute, absorbed by overlap (L207-221).
  • Game vector accuracy is never published because a HAL that reports it "unreliable" would hold the shutter for a calibration the sensor does not use (L229-234).
  • Many HALs never fire onAccuracyChanged, even the first time; reading event.accuracy avoids sitting at Unknown forever; a zero default must not look like "unreliable" (L415-431).
  • allowsCapture only refuses Unreliable: indoors near steel a phone can sit at Low indefinitely while tracking perfectly, so blocking on Medium+ was a dead end (OrientationAccuracy KDoc L108-122).
  • Screen reference frame puts an upright phone at pitch ≈ -90°, the gimbal-lock pose; camera frame moves the singularity to straight up/down (L143-162).
  • Leaving the listener registered in background keeps the gyro powered and drains battery (L181-184).
  • Some vendors append a fifth element (heading accuracy) to the vector (L350-351).
  • The camera basis is carried because Euler angles collapse at the zenith; pose averaging needs the rotation (L64-75, L371-374).
  • Up column is mirrored to make a proper rotation; unmirrored it silently corrupts the refinement (a 90° error through the quaternion conversion) (L526-529).
  • anglesFromCameraBasis must be the exact inverse of CameraBasis.of, else frames land "aligned but all at odd angles", unrecoverable by stitching (L598-602).
  • quitSafely so a queued event finishes its matrix conversion (L334-335).
  • features unused / off:
  • OrientationReference.Screen (levelling-UI convention) is never used.
  • Higher sampling (SENSOR_DELAY_FASTEST or a microsecond period) is possible via the param; permission already declared.

OrientationState.kt (sensor/) — Compose wrappers that bind the tracker to lifecycle and display rotation

  • status: shipped-on
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
rememberOrientationTracker defaults SENSOR_DELAY_GAME, Camera same see tracker L26-29
lifecycle start on STARTED, stop on STOP/dispose same sensor power L41-44
display rotation fallback Surface.ROTATION_0 same when no display (app context API 30+, preview) L75-82
  • authors' notes:
  • Configuration is a new instance after rotation, so display rotation is re-read exactly when it can change (L35-36).
  • Our CaptureActivity is locked to portrait in the manifest (android:screenOrientation="portrait"), so rotation handling is effectively always ROTATION_0 in our app (manifest fact).
  • features unused / off:
  • rememberOrientationData (State helper) is not used by our capture screen.

OrientationMean.kt (sensor/) — averages the dwell's samples into the pose stamped on a frame

  • status: shipped-on (Coordinator L271)
  • our changes vs theirs: none
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
weighting equal (1.0 each) same quaternion mean weights L67
method rotation (quaternion) mean when every sample has a basis, else unwrapped Euler mean same — L32-52
window up to 20 samples (Coordinator DEFAULT_POSE_WINDOW_SIZE) same — Coordinator L12
  • authors' notes:
  • Averaging the dwell rather than taking the last sample removes the jitter that shows up as softness in stitch overlaps; equal weights because the window is one deliberate stop (L8-14).
  • Euler averaging near the zenith smears poses (yaw and roll collapse, frames land rotated about their own axis) — hence the rotation mean (L15-22).
  • Linear quaternion mean is the Karcher mean to first order, fine for a few degrees of jitter (L59-63).
  • Euler fallback unwraps around the first value so ±180° does not average to 0° (L71-77).
  • Code fact: the returned OrientationData does not copy isGyroAssisted (defaults true) (L36-43, L46-52).
  • features unused / off: none.

CompassProbe.kt (sensor/) — ours: estimates true-compass offset of the capture's arbitrary yaw zero

  • status: ours, shipped-on (Screen L304-315; result read at Screen L1459 for the heading handed back)
  • our changes vs theirs: whole file is ours
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
sensor TYPE_ROTATION_VECTOR (magnetometer-fused) at SENSOR_DELAY_UI n/a compass source and rate L31, L45
MAX_PITCH_DEGREES 30f n/a capture samples steeper than this are ignored L85
LEVEL_UP_COMPONENT 0.5f (camera within 30° of horizontal) n/a compass sample counts only when level L86
MIN_SAMPLES 10 n/a offset returns null until this many samples L87
caller sample period 200 ms n/a how often (capture yaw, pitch) is fed in (≥ 2 s of level aim before an offset exists) Screen L313
averaging circular mean (sin/cos sums) over the whole screen lifetime, no reset n/a — L40-69
  • authors' notes:
  • Game rotation vector yaw has an arbitrary zero that changes per capture; on 2026-11-25 two points shot facing opposite ways both reported ~-20° start yaw and the automatic way back landed on the wrong wall (L15-20).
  • Indoors the compass can be off by tens of degrees, so its output is a suggestion the agent confirms, never a silent decision (L25-26).
  • Code fact: magnetometer accuracy is ignored (onAccuracyChanged is a no-op, L82) and there is no reset, so a bad stretch near steel stays in the average for the whole session.
  • features unused / off:
  • No accuracy gating or outlier rejection; adding SENSOR_STATUS_UNRELIABLE filtering would be the obvious hardening.

CaptureActivity.kt — ours: Property Walk's entry into the engine (permission gate, capture/import flow, review screen, hand-back, cache housekeeping)

  • status: ours, shipped-on (launched from host MainActivity.kt L38 via CaptureActivity.intent(mode, scope); Dart capture360.dart L55-56 passes mode: 'photos' when importing and scope: 'ring'|'sphere')
  • our changes vs theirs: whole file is ours (replaces upstream MainActivity as the entry point)
  • levers:
lever value in OUR build value in THEIRS what it controls how to change it
EXTRA_MODE / MODE_PHOTOS "mode" / "photos" n/a import photos already on the phone instead of camera L252-253
EXTRA_SCOPE / SCOPE_RING "scope" / "ring" (anything else = full sphere) n/a Ring vs Sphere capture scope L296, L300, L378-382
result extras "path", "width", "height", "error", "heading" (Float), "bentPath" n/a contract with host L244-262
CAPTURE_DIR / KEEP "pw_captures" / 4 newest files kept n/a where handed-back spheres live until upload L248-249, L195
bent-joins cache "pw_bent", 3 newest kept, JPEG 95 n/a second picture copy L102-105
PARK_PREFS "pw_capture_park" n/a last result parked for takeParked if the caller was recreated L255, L264-293
KEEP_DEBUG_SESSIONS 6 (~75 MB each) n/a debug builds keep this many capture sessions' photos in cacheDir/sphere_sessions; dirs starting "test_" are never pruned L299, L130-136
debug restitch hook DebugRestitch.runIfRequested at start (debug only) n/a re-build kept frames with each stitch option L120-125
release cleanup on finish deleteImageCache, imports, sphere_sessions deleted (release only; imports always) n/a ~100 MB per capture otherwise L222-241
buffer.clear(deleteFiles = !DEBUG) on Retake — n/a debug keeps frames on retake L361
review preview decode PANO_TEXTURE_MAX_DIMENSION n/a preview sphere texture size L403-407
default restitch style StitchStyle.Balanced (or offer.madeWith) n/a style recorded for the finished sphere L323, L386
review colours / sizes bg 0xFF101314, button 0xFFE4F222 56dp, Retake 52dp n/a review screen look L413-440
  • authors' notes:
  • The sphere is copied out of the engine's self-pruning cache into pw_captures so it survives until upload (L73-74).
  • LastSphereInfo is process-wide because the stitch runs deep in the camera screen and the result is handed back from the activity; bentPath is cleared each stitch so a restitch never returns an older picture (L76-94).
  • Debug keeps the last few sessions because on 2026-11-25 the Entrance point came out ghosted and its photos were already replaced by the next capture (L126-129).
  • Embedded, upstream's app-start cache pruning never runs, so every capture left ~100 MB of frames + spheres + imports (L224-226).
  • deleteImageCache also removes sphere_sessions, "which is why build 13 kept nothing", so debug skips it (L230-231).
  • Review screen stripped to Use / Retake because an agent tapped upstream's "Saved to gallery" thinking it saved the point and nothing reached the tour (2026-11-25) (L391-395).
  • Import mode is not camera-gated, matching upstream (L163-164).
  • After two denials Android answers "denied" without asking, so the gate offers the app settings page (L481-482).
  • returning flag prevents a double tap returning twice (L171-176).
  • features unused / off:
  • Code fact: restitch(style) (L328-351), restitchError, restitching and frameFiles are defined but nothing in the review UI calls or shows them — upstream's "Restitch as Balanced / Crisp / Careful" (mentioned in the KDoc L311-313) is unreachable. To expose it, add buttons in the review Column (L419-441) that call restitch(StitchStyle.X) when restitchOffer != null.
  • Upstream result-screen actions (export poses, save to gallery, save frames, share) deliberately dropped.

Totals

  • Lever rows: 171 (20 files)
  • Authors' notes bullets: 140
the camera screen, their app shell, settings, storage, debug tools

engine reference — the camera screen, their app shell, settings, storage, debug tools

part of the engine reference (master_doc/engine/). written 2026-11-26 by reading every file of our copy (commit 16eb526) against theirs (b5796d7), plus their docs, tests, tools and commit history. line numbers point at our code at 16eb526; the floor-photo commits after it (eff5cd1, 022767a) shift a few. levers were read from the code, not tried on the phone. start at master.md -> "if something goes wrong with the camera".

Vendored engine: photosphere-android (MIT, by theclumsypirate, a fork of n30dyn4m1c/360-photo-app), upstream commit b5796d7. - OURS = apps/mobile/android/photosphere/src/ (committed state; our edits carry "Property Walk" comments). - THEIRS = app/src/ at b5796d7. - Line numbers point at OURS unless a line says otherwise.

How the files were compared: diff -r --strip-trailing-cr (our copy has CRLF line endings, theirs LF). - These files in this scope have real changes: PhotoSphereCameraScreen.kt, PhotoSphereApplication.kt, AndroidManifest.xml, res/values/strings.xml, and the build file (fully rewritten). Two more are ours only: diagnostics/DebugRestitch.kt, and the absent res/mipmap-anydpi-v26. - Every other file in scope differs only in line endings. That includes MainActivity.kt, settings/, result/, importer/, metadata/, storage/, util/, ui/theme/, orbit/, src/debug and src/release. - Not compiled: app/orbit-disabled/ and the test/testDebug sets exist upstream only.

Status words used below: - shipped-on: compiled into our app and running. - shipped-off: compiled, but the switch is forced off. - debug-only: present only in debug builds. - unreachable: compiled, but nothing in our app reaches it. Our manifest registers only CaptureActivity; upstream's MainActivity is not registered. - ours: written by us.

Sections 1–9 below are by the lead agent. The settings/result/importer/metadata/storage sections, then the src/debug, src/release and orbit sections, follow after them.


PhotoSphereCameraScreen.kt — the guided capture screen: camera bind + 3A, sensor-driven auto-shutter loop, HUD, floor photo, stitch hand-off

  • status: shipped-on. Our CaptureActivity calls it at CaptureActivity.kt:377-388 with initialScope = Ring when intent extra scope == SCOPE_RING, else Sphere. Upstream's MainActivity calls it at MainActivity.kt:480 (unreachable for us).
  • our changes vs theirs (3268 lines vs 2951):
  • New parameter initialScope: SphereCaptureScope = SphereCaptureScope.Sphere (:278), which seeds captureScope (:387). Theirs was hard-coded to Sphere.
  • CompassProbe (:304-315): a real magnetometer bearing, sampled every 200 ms against the tracker's yaw. It turns the image's middle column into a compass heading, LastSphereInfo.centerYawDegrees = ((start yaw + offset) % 360 + 540) % 360 - 180, or null when there is no reading (:1453-1466). CaptureActivity returns it as the heading extra.
  • Exposure gate, new constants UPRIGHT_PITCH_DEG = 40f, UPRIGHT_DWELL_MS = 1_500L, REMETER_AWAY_MS = 1_000L, FALLBACK_BLIND_LOCK_MS = 12_000L (:214-224):
    • The "ready" flag needs the phone held within ±40° of level for 1.5 s, with AE CONVERGED/FLASH_REQUIRED and AWB CONVERGED (or AWB state null) (:751-767, :831-844).
    • After 6 s (THREE_A_LOCK_TIMEOUT_MS) a 250 ms polling loop starts (:957-1004). It readies once aimed and (settled, or 12 s since the loop started).
    • Lowered for more than 1 s before the first frame → it un-readies and re-meters (:970-1000).
    • The loop runs in the effect's own scope, not the screen's, so a rebind cancels it (:954-957).
  • lockThreeA is now a no-op that only marks ready (runCatching { Unit }, :782-791). The real AE+AWB lock happens on the preview's repeating request right after the first photo lands (buffer.frames.value.size == 1, :1174-1193).
    • It is released when the run goes back to zero photos (noPhotosYet effect, :493-507).
    • Theirs locked AE+AWB inside lockThreeA, as soon as AE converged or at 6 s, whatever the lens faced.
    • Why we changed it: on 2026-11-25 an M36 metered face-up on a desk at 1/17 s ISO 3205 and every frame came out white. A second M36 session came out green because AWB was frozen mid-adjustment (:743-750, :834-839, :1174-1178).
  • Default seam mode SeamMode.WinnerTakeAll ("Crisp"), where theirs was SeamMode.Blend (:509). Reason given: upstream's own fix for doubled near objects (KNOWN_ISSUES.md "Ghosting and sliced objects"). It needs equal brightness, hence the lock after the first photo (:487-490).
  • The debug target-plan branches are dead: if (BuildConfig.DEBUG) became if (false) at :401 (latitude span) and :1098 (plan builder). Upstream forced the 36-frame DebugTargetPlans.fullSphere in debug builds; ours always uses SphereTargetPlan.createForFieldOfView(scope = captureScope).
  • Floor photo step (:607-611, :1575-1625, :1638-1648, FloorPhotoDialog :2801-2853, FLOOR_SHOT_SETTLE_MILLIS = 1200L :2799):
    • When the run completes with ≥ PhotoSphereStitcher.MIN_FRAMES (= 3, PhotoSphereStitcher.kt:222) frames, a non-dismissable dialog asks for one straight-down floor photo from a step back.
    • The photo is taken 1.2 s after the tap and saved to <session>/floor.jpg, with floor_pose.txt beside it (yaw,pitch,roll;m0,...,m8).
    • The photo is passed as floorShot to the stitcher. "Skip" stitches without it.
  • Auto-stitch on completion: the floor dialog opens by itself, so no tap is needed (:1577-1585). canStitch now also requires run.isComplete (:1748-1750); theirs offered Finish after 3 frames. onFinish opens the floor step instead of calling startStitch() (:1751).
  • Bent-joins output: bentOutput = bentSphereWriter(context) is passed to the stitcher, with LastSphereInfo.bentPath cleared first (:1410-1413).
  • HUD switches forced off:
    • captureScope = null and onScopeChange = null, so the Ring/Sphere pill is hidden in all builds (:1734-1738). Theirs hid it only in debug.
    • showExposure = false, so the brightness slider is hidden (:1811).
    • canSaveFrames = false (:1815).
    • showDebugDropdown = false, so the night-mode/flashlight menu is hidden (:1818). Theirs: true.
    • DebugSwitches behind if (false) (:2231). Theirs: if (BuildConfig.DEBUG).
  • Hints:
    • New exposureLocked parameter on captureHint (:3000), which shows "Hold the phone up toward the room to start" until ready (:3012).
    • The fallback hint is "Follow the arrow to the dot, then hold still" in every build (:3027). Theirs showed capture_hint_search in debug and an empty string in release.
  • Strings re-worded in res/values/strings.xml: "frames"→"photos", "band"→"part", "Finish & stitch"→"Finish", "Building your sphere"→"Building your 360° view", and all stitch error texts.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
HINT_HOLD_RELEASE_MILLIS 400L how long the hint keeps saying "hold" after the gate drops (display only) :197
THREE_A_LOCK_TIMEOUT_MS 6_000L OURS: delay before the aimed/settled polling loop starts. THEIRS: blind AE/AWB lock at 6 s :212
UPRIGHT_PITCH_DEG (ours) 40f n/a max |pitch| counted as "aimed at the room" for the ready gate, and for re-metering :215
UPRIGHT_DWELL_MS (ours) 1_500L n/a how long the phone must stay aimed before ready :218
REMETER_AWAY_MS (ours) 1_000L n/a lowered this long before the first frame → AE/AWB unlocked, hasLockedOnce=false :221
FALLBACK_BLIND_LOCK_MS (ours) 12_000L n/a after this long aimed, ready even without CONVERGED :224
RING_LATITUDE_SPAN_FACTOR 1.3f ring canvas height = vFOV × 1.3, capped at 180° :238
SHOT_POSE_TOLERANCE_DEGREES 0.4 a shot within 0.4° of the dwell mean is stamped with the mean, otherwise with the shutter-time pose :248, shotPose :3162-3173
FLOOR_SHOT_SETTLE_MILLIS (ours) 1200L n/a delay between the "Take floor photo" tap and the shutter :2799
param initialScope (ours) default Sphere; host sends Ring via extra scope n/a (always Sphere) full sphere vs horizon ring plan + canvas CaptureActivity.kt:378-382; :278
captureScope (rememberSaveable) initialScope Sphere plan scope; re-plans only while the buffer is empty (:1246-1250) :387. The HUD toggle is hidden (:1736)
latitudeSpanDegrees Sphere 180f; Ring vFOV×1.3 capped at 180f debug: from DebugTargetPlans saved type GPano/canvas latitude span passed to stitcher + GPano :401-412 (if (false) kills the debug branch)
planStartYawDegrees (rememberSaveable) Float.NaN until the first fix plan anchor yaw; also centerLongitudeDegrees of the stitch (puts the first view mid-image) :394, :1448-1452
compass sample period (ours) delay(200) n/a CompassProbe sampling for the heading :313
Samsung ultrawide override BuildConfig.DEBUG && isSamsung() && pref samsung_highres/prefer_ultrawide → preferWidestCamera = true which lens shoots the sphere (debug, Samsung) :322. The pref is set only from SettingsScreen (unreachable)
guidanceEnabled (rememberSaveable) default context.isScreenReaderActive() (Settings.Secure.ACCESSIBILITY_ENABLED == 1) beeps, dwell haptics, spoken "next: above you, to your left" speaker button top-right, visible in our build (:2042-2075); :333-335
guidance loop cadence beep interval GuidanceProfile.beepIntervalMillis(distance); idle 250 ms; dwell poll 40 ms; else 150 ms; spoken cue after 600 ms settle audio guidance timing :630-692
debugNightEnabled (rememberSaveable) false night burst-merge capture (saveNightBurst) when also deviceProfile.nightMode != null && nightModeSupported only via the dropdown, hidden (:1818) → unreachable
debugTorchEnabled (rememberSaveable) false cameraControl.enableTorch dropdown, hidden → unreachable
distortionEnabled false passes radialDistortion = optics.radialDistortion (else null) to stitcher DebugSwitches "Dist" (hidden); :482
refinementEnabled false useRefinement (feature-based pose refinement) "Refine" (hidden); :483
seamMode SeamMode.WinnerTakeAll SeamMode.Blend seamMode: Blend (wide cross-fade) / Carve (graph cut) / WinnerTakeAll (closest optical centre) "Seam" cycles Blend→Carve→WinnerTakeAll→Blend (:1788-1793, hidden); :509
movingMaskEnabled false movingObjectSeamMask (mask nodes where frames disagree) "Mask" (hidden); :513
blockExposureEnabled false perBlockExposure (per-block gain on top of per-frame gain) "Block" (hidden); :516
graphSelectionEnabled false graphSubsetSelection (drop frames refinement matched nothing for) "Graph" (hidden); :519
warpEnabled false localWarpAlignment (APAP-lite mesh per frame) "Warp" (hidden); :522
perceptualSeamEnabled false perceptualSeamCost (OKLab seam cost) "Percept" (hidden); :525
colorFrames false debugColorFrames (paint each frame a solid colour to check placement); also diagnostics/debugColors "Color" (hidden); :528
isThreeALocked / hasLockedOnce false/false at each bind (:699-700) hasLockedOnce is the shutter gate canTrigger (:1087). OURS: means "ready", not locked :366, :371
exposureRange / exposureIndex from cameraInfo.exposureState; compensation re-applied on rebind (:905-910) EV compensation; applyExposure unlocks AE first (:580-600) slider hidden (showExposure=false, :1811)
setAeLocked AE only (AWB untouched) slider's lock button :556-570, unreachable (slider hidden)
Preview resolution RATIO_4_3_FALLBACK_AUTO_STRATEGY keeps preview = stills FOV (no 16:9 crop) :807-811
ImageCapture CAPTURE_MODE_MAXIMIZE_QUALITY, FLASH_MODE_OFF, 4:3, target captureMaxLongEdgePx × (captureMaxLongEdgePx·3/4) with FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER still size/quality; per-device px in SphereDeviceProfile.kt (e.g. 4000) :853-880
camera selector widestCameraSelector() if deviceProfile.preferWidestCamera, else DEFAULT_BACK_CAMERA; a failed bind falls back to the default which lens :718-722, :884-894; SphereDeviceProfile
PreviewView.scaleType FILL_CENTER projection maths assumes a uniform fill :438
initial focus lockFocusAt(0.5f, 0.5f) when focusMode == FOCUS_POINT; a tap re-aims it (FLAG_AF only) focus plane :1065-1067, :1684-1693, focusAt :3134-3159. (Our SphereCaptureProfile.kt:253 now uses continuous AF "like the stock camera"; how that interacts with this one-shot trigger is unverified)
burstPerTarget deviceProfile.burstPerTarget N stills per target, keep the sharpest (SharpnessSelection) :1167, saveFrame :3044-3111
night mode active debugNightEnabled && nightMode != null && nightModeSupported saveNightBurst vs saveFrame :1148
stitcher backend StitcherBackend.getSelectedBackend → KOTLIN unless debug + pref debug_prefs/use_cpp_stitcher Kotlin vs native C++ :1323-1324. The pref is set only in SettingsScreen (unreachable)
C++ stitch params outWidth = 1024, ssaa = 2, hfovDeg = debug FOV or fieldOfView.horizontalDegrees, doGain = true, doRefine = true, refineIters = 4; output filesDir/temp_stitch_<ms>.jpg; no RestitchOffer native path :1351-1363
Kotlin stitch params maxInputDimension = deviceProfile.stitchMaxInputDimension, maxOutputWidth = deviceProfile.stitchMaxOutputWidth, unsharpAmount = deviceProfile.unsharpAmount, pivot = deviceProfile.pivot (PivotModel lever arm 0.35 m / scene 10 m, PivotModel.kt:71), portraitRotationDegrees = optics.portraitRotationDegrees, longitudeSpanDegrees = 360f, centerLongitudeDegrees = planStartYaw or 0, latitudeSpanDegrees, centerLatitudeDegrees = 0f, bentOutput, floorShot main stitch :1411-1470
GPano written forSphereRegion(w, h, lonSpan 360, centerLon 0, latSpan, centerLat 0) XMP on the finished JPEG (centred at 0 on purpose: it describes image columns, not sensor yaw) :1477-1484
RestitchOffer madeWith = StitchStyle.forSeam(seamMode), params = FOV, optics, distortion, max dims, unsharp, pivot, refinement, colours, latSpan, centerLon what a later restitch reuses :1537-1556; our review screen has no buttons for it (CaptureActivity.kt:391-395)
MIN_FRAMES 3 minimum for floor step / Finish / stitch PhotoSphereStitcher.kt:222
canStitch (Finish button) run.isComplete && frames ≥ 3 && stitchJob == null frames ≥ 3 && stitchJob == null when "Finish" shows :1748-1750
onFinish floorShot = null; floorStep = true startStitch() Finish → floor dialog :1751
onRestart resetGuidance(); buffer.cancelSession() "Start again" (visible only when complete, :2306-2318) :1752-1758
canUndo / undoEnabled frames.isNotEmpty() && stitchJob == null / !run.isCapturing undo button top-left :1762, :1771
captureScope (HUD) / onScopeChange null / null if (DEBUG) null else captureScope / if (DEBUG) null else {...} Ring/Sphere pill :1736-1738
canChangeScope !BuildConfig.DEBUG && frames empty && no stitch pill enabled state (moot: pill hidden) :1737
showExposure false boundCamera != null && evRange.last > evRange.first brightness slider :1811 (theirs computed at :1658-1659)
canSaveFrames false bufferedFrames.isNotEmpty() && stitchJob == null "Save N frames" → MediaExporter to gallery :1815
showDebugDropdown false true night mode + flashlight menu :1818
DebugSwitches row if (false) if (BuildConfig.DEBUG) the 9 A/B switches (Dist, Refine, Seam, Color, Mask, Block, Graph, Warp, Percept) :2231
hint: not ready (ours) "Hold the phone up toward the room to start" n/a shown while !hasLockedOnce :3012
hint: fallback "Follow the arrow to the dot, then hold still" debug: capture_hint_search "Move the reticle onto the marker"; release: "" default line :3027
lock badge capture_lock_fixed / capture_lock_hint / capture_lock_focusing / capture_lock_locked focus status text. lockBadge is passed to CaptureHud (:1730), but CaptureHud never draws it, and FocusLockChip (:2685) has no caller in our tree: dead in both versions :1663-1671
camera-error retry bindAttempt++ re-keys the bind effect recover after another app took the camera :474, :941-948, :1841-1849
stale-session prune buffer.pruneStaleSessions() on every sessionId deletes every other cache/sphere_sessions/* folder :1049-1051 → SphereImageStore.pruneSessions (SphereImageStore.kt:180-190)
HUD layout numbers top scrim 200 dp (landscape 120 dp), bottom scrim 260 dp (landscape 120 dp wide), finish button 54 dp, progress bar anim 420 ms, stitch ring anim 500 ms, hint crossfade 220 ms look :2000-2024, :2297, :2584, :2901, :2736
  • authors' notes:
  • :191-197 hint "hold" is debounced 400 ms against gate flapping at the 2° threshold. Display only; capture and audio use the raw value.
  • :199-212 lock on CONVERGED, the right moment both by day (a few frames) and by night (after the ramp). Some HALs never report CONVERGED, hence the timeout. A settled-but-unreported exposure beats the stream-start default that freezes a black viewfinder.
  • :226-238 ring band is widened 1.3× because rolling the phone sweeps its half-diagonal, wider than the vertical half-angle, plus aim error and refinement movement.
  • :240-248 the mean of ~20 dwell samples is quieter than the one shutter sample. Past 0.4° the phone really moved, and the shutter sample is the honest pose.
  • :251-271 frames are stitcher input in cache, not gallery photos. The plan is anchored at the bearing of the first sensor fix. The caller owns the CAMERA permission.
  • :285-293 keepScreenOn for the whole capture: minutes of pointing must not hit the screen timeout.
  • :296-299 orientation is held as State, not read with by. Reading .value in composition would recompose the whole screen at sensor rate; only the overlay draw lambda reads it.
  • :301-303 (ours) the tracker's yaw has an arbitrary zero (no magnetometer), so CompassProbe is the only source of a real bearing. It is used only for the returned heading.
  • :319-321 the Samsung ultrawide preference is read once per screen, so a mid-session flip cannot renumber targets.
  • :337-342 capture, undo and restart are serialised in SphereCaptureCoordinator, because a capture suspends for hundreds of ms while its frame is written.
  • :351-358 the optics are re-read from the lens that actually bound and its buffer aspect, not guessed. They scale the plan spacing, the overlay rectangles and the per-frame stitch FOV.
  • :361-371 hasLockedOnce, not isThreeALocked, gates the shutter, so a later manual unlock (brightness) does not kill capture.
  • :380-383 the scope is locked once the first frame lands: re-planning would renumber the targets.
  • :389-394 the plan anchor survives configuration changes (the buffer does too), so a mid-run recreation rebuilds the same plan.
  • :396-400 ring span is capped at 180°: GPano cannot express a taller span, and throwing would discard the render.
  • :476-481 pose refinement starts OFF. Sensor poses + pinhole are the reliable core, and refinement can pull frames off the sensor answer when there is parallax (a body-swivel capture of a close scene breaks the pure-rotation model).
  • :510-528 what each A/B switch does: moving mask (things that moved between frames), block exposure (steps a whole-frame mean can't see), graph selection (orphan frames painting unmeasured patches), warp (APAP-lite parallax residual), OKLab seam (cut reads through exposure differences), colour frames (placement bug vs content bug).
  • :530-539 tap-to-focus in AF_MODE_AUTO holds the lens at the converged distance until the next trigger. That keeps the whole sphere on one focal plane and sharp on the real scene rather than parked at infinity.
  • :550-555 setAeLocked re-pins whatever the HAL converged on; AWB is left alone.
  • :572-579 a locked AE ignores compensation on most HALs, so adjusting unlocks first. Stills follow the preview on most HALs.
  • :602-605 stitch progress travels as a StateFlow, because Compose state written from a background dispatcher is unsafe.
  • :627-629 the guidance loop polls alignment at the beep cadence instead of observing sensor-rate state.
  • :675-681 the first target is not announced (it is where the user already faces). A 600 ms settle stops every marker the reticle sweeps over from being spoken.
  • :694-696 the bind is re-keyed on bindAttempt, so a failed bind can be retried in place.
  • :712-717 speed-first profiles take the widest lens (more coverage per frame). Sharpness-first profiles (S23 among them) take DEFAULT_BACK_CAMERA, which Android requires to be the primary main lens, not the ultrawide.
  • :724-740 (theirs, partly superseded) locks must not sit in the stream's first request: that freezes the stream-start defaults and a dark scene never brightens. The convergence callback runs on the camera thread and the bind on main, so the holders are atomics, and a null control read must let the timeout retry.
  • :743-750 (ours) M36 face-up on a desk on 2026-11-25 locked at 1/17 s ISO 3205 → every frame pure white. The fix: lock only while aimed (|pitch| < 40°) after 1.5 s. No frame escapes, because canTrigger = hasLockedOnce.
  • :752-755 (ours) the latest AE state is tracked so the fallback does not lock mid-ramp after the phone is lifted from a dark desk.
  • :799-806 preview pinned to 4:3. CameraX would otherwise pick a display-shaped 16:9 preview, which is a crop of a 4:3 sensor, and the markers would sit where the capture reaches rather than where the user sees.
  • :815-823 FLASH_REQUIRED counts as converged: it is the dark-scene equivalent when flash is off.
  • :834-839 (ours) AWB must settle too. Locking on AE alone froze the M36's AWB mid-adjustment and the session came out green (2026-11-25). A null AWB state counts as settled.
  • :855-856 flash is off: flash on some frames leaves seams no blend hides.
  • :858-862 stills are capped at the profile's long edge. The stitch reads about 1024 px per frame; 50 MP stills are slower, slow the burst and heat the phone.
  • :903-910 a 0..0 EV range means no compensation (slider hidden). Compensation is re-applied after a rebind so it is not silently dropped.
  • :911-914 record the lens that answered: a filter that matched nothing, or a logical camera, would otherwise leave the optics describing the wrong lens.
  • :918-923 the capture profile is re-resolved against the bound lens. A FIXED_FOCUS guess on a lens that can focus would kill tap-to-focus.
  • :931-940 a camera error (another app, service death, thermal) drops the use case and shows the retry card. Buffered frames are untouched, so the run continues after retry.
  • :950-953 the timeout covers HALs that never report CONVERGED; the callback wins on devices that do.
  • :954-956 (ours) the polling loop uses the effect scope, so a rebind after a camera error cancels it instead of polling the old session's control.
  • :971-974 (ours) a lock is final only once a frame exists. A bad lock heals by lowering the phone, so the agent need not reopen capture.
  • :1015-1019 CameraX only unbinds when the lifecycle dies (not when this screen leaves), so the bind is undone explicitly to save battery and heat.
  • :1035-1041 the stills' EXIF rotation follows the display. Android 16+ ignores the portrait lock on large screens, so tablets can rotate mid-session.
  • :1047-1048 old sessions are cleared when a new one starts, so the cache doesn't grow by a sphere of JPEGs per run.
  • :1060-1064 the initial centre focus lands before the first dwell can complete, so it cannot race a shutter.
  • :1069-1071 collecting suspends across the shutter: no second capture can start while one is written (the StateFlow conflates).
  • :1078-1080 no capture during a stitch: the frame would not be in the set and would be deleted with it.
  • :1083-1087 no frame before the first lock, or a dark scene gives a near-black still.
  • :1089-1092 the plan is rebuilt on the saved anchor after recreation.
  • :1108-1113 (debug) FOV is baked into each frame's EXIF comment and a session sidecar for the offline Python stitcher. Debug only, so the release comment shape stays what the importer parses.
  • :1174-1178 (ours) the lock comes after the first photo so all 16 match. Locking at bind froze the M36 preview green/white.
  • :1194-1199 the token refuses an advance if the run was restarted or stepped back while writing, so the reticle never lands past an un-shot target.
  • :1215-1224 a failed capture stays on the same target (retried, not skipped). SessionSupersededException is an expected restart race, not reported.
  • :1240-1245 a plan change from the optics resets guidance only while the buffer is empty.
  • :1256-1261 export-frames confirms first: dozens of full-res JPEGs in the gallery.
  • :1282-1299 stitch is started LAZY so stitchJob is set before finally clears it. It waits for any in-flight shutter, or that frame would land after the snapshot and be deleted, leaving a silent hole.
  • :1310-1313 the camera basis matrix travels with the angles: near the zenith yaw and roll collapse, and angles alone can't place a frame.
  • :1423-1429 guided capture is shot standing and turning, so the lens swings on an arm (PivotModel). portraitRotationDegrees restores a frame whose EXIF rotation tag was lost.
  • :1442-1447 centred on the first shot's bearing, so the start view is mid-image and the ±180° wrap is behind the user. GPano stays centred at 0.
  • :1502-1504 a sphere too big for the disk keeps its frames, so a retry costs only the stitch.
  • :1521-1531 frames stay buffered after a stitch (for Save frames / restitch). The restitch frame list is read at tap time.
  • :1560-1561 frames are kept after a failed stitch: the usual fix is to shoot a few more.
  • :1741-1747 (theirs) three frames are already a panorama and the user decides on the result screen. (Ours) offering Finish after three read as nagging to stop early, so it shows only at completion and is a fallback to auto-build.
  • :1759-1771 undo is dimmed, not hidden, while a shutter is in flight (that frame isn't in the buffer yet). A control that vanished on 30-odd captures reads as a glitch.
  • :1854-1862 the camera error card exists because without it a never-bound camera looks like a live viewfinder and the only way out is killing the app.
  • :1988-1992 in landscape (Android 16 forced rotation) the controls move to the right edge, so the bottom stack doesn't cover the aim point.
  • :1995-1999 scrims both top and bottom: white text over a bright sky is unreadable at either end.
  • :2222-2228 (theirs) debug switches used to appear at frame 3 and grew the stack into the aim area, and 9 buttons overflowed the width. Now present from the start and scrollable.
  • :2253-2262 (theirs) the Finish button animates in so its arrival is noticed and isn't a mis-tap under the thumb.
  • :2319-2323 the exposure row is last in the column so the bottom edge holds it still while the rest grows upward.
  • :2386-2392 debug switches are one quiet scrolling line and must never grow into the viewfinder.
  • :2493-2495, :2515-2519 the scope selector is one shared track (an exclusive choice). enabled is passed to Surface because the old onClick check left disabled segments clickable, and TalkBack announced a dead button.
  • :2557-2560 the progress pill is spoken as one sentence, not five fragments.
  • :2578-2581 the progress bar animates, so a frame landing is visible in peripheral vision.
  • :2717-2721 the hint crossfades, because a hard cut between similar sentences at arm's length is missed.
  • :2789-2796 the stitching dialog is modal and not dismissable. Cancel takes effect at the next stage boundary; a native call can't be interrupted. (Note: our FLOOR_SHOT_SETTLE_MILLIS was inserted between this KDoc and StitchingDialog, detaching it: cosmetic.)
  • :2880-2882 the indicator is the subject: a stitch is minutes of blocked screen.
  • :2896-2898, :2918-2919 the ring animates between coarse stages. When OpenCV is opaque it spins instead of inventing a percentage.
  • :3015-3017 the shutter is held only at Unreliable compass accuracy; Low still shoots, with advice to calibrate.
  • :3022-3023 a closed ring is a good result, so saying so makes "keep going" a real choice.
  • :3037-3043 burst: the sharpest is kept and the losers are deleted in commitBestFrame. A failed burst deletes its reserved files.
  • :3063-3067 each burst shot keeps its own shutter-time attitude. A hand easing off after shot 1 would otherwise misplace shots 2–3.
  • :3086-3090 a null commit means the session was cancelled. Reporting success would advance past an un-shot target.
  • :3099-3102 cancellation (leaving mid-shutter) is not a failure, but the reserved files are still cleared.
  • :3150-3151 a failed focus sweep doesn't fail the session.
  • :3166-3167 the relative rotation angle comes from the trace of aᵀb (the element-wise dot product).
  • :3178-3179 onCaptureStarted runs at exposure start, the instant whose attitude the frame records.
  • :3209-3214 the widest-camera filter matching nothing makes bind throw, and the caller falls back to the default camera.
  • :3229-3231 the camera provider is bridged by hand to avoid a coroutines-guava dependency.
  • findings from reading our code (not author notes; checked from code only, not on the phone):
    • lockThreeA still logs "AE/AWB locked" (:790) although it locks nothing now. The log line that marks the real lock is "Exposure and white balance locked after the first photo" (:1190).
    • Stale comments, because the toggle is hidden: :276-277 ("the in-capture toggle can still change it") and :384-386 ("Horizon ring stays one tap away"). Also :1732-1733, which says debug picks the plan in Settings.
    • pruneStaleSessions (:1049-1051) runs in every build on every new ImageBufferManager. Its sessionId comes from SphereImageStore.newSessionId() at construction (ImageBufferManager.kt:83). pruneSessions deletes every other folder, including test_* (SphereImageStore.kt:180-190). This appears to defeat CaptureActivity's debug KEEP_DEBUG_SESSIONS = 6 (CaptureActivity.kt:126-136, :299): at most the current session's frames survive once the camera screen opens. Unverified on the phone.
    • Debug log :1107 and sidecar :1127 record DebugTargetPlans.getSavedType(context), which is always FULL_SPHERE, even for a Ring capture.
    • The re-meter loop sends AE/AWB unlock requests even though lockThreeA locks nothing. Harmless.
  • unused features and how to turn them on:
  • A/B stitch switches: change if (false) → if (BuildConfig.DEBUG) at :2231 (theirs). Or change a default at :482-528 to ship one (for example refinementEnabled = true). Run scripts/capture_test.py first, per CLAUDE.md.
  • Seam style: SeamMode.Blend / Carve / WinnerTakeAll at :509.
  • Night mode + flashlight menu: showDebugDropdown = true at :1818. Night needs deviceProfile.nightMode != null && nightModeSupported (see SphereDeviceProfile.kt).
  • Brightness slider: restore showExposure = showExposure at :1811 (computed at :1659).
  • Save frames to gallery: canSaveFrames = bufferedFrames.isNotEmpty() && stitchJob == null at :1815.
  • Ring/Sphere pill: captureScope = captureScope, onScopeChange = { captureScope = it } at :1736-1738. Today the host picks the scope through the intent extra scope.
  • Finish after 3 frames (upstream): drop run.isComplete && at :1748.
  • Upstream 3A behaviour (lock at converge/6 s): put the addCaptureRequestOptions(AE_LOCK=true, AWB_LOCK=true) body back inside lockThreeA at :786, and remove the aimed gate at :844/:969.
  • Debug 36-frame plan: if (false) → if (BuildConfig.DEBUG) at :401 and :1098. The 8 plan types live in DebugTargetPlans (debug source set); the Settings picker is unreachable, so set the pref debug_target_plans/plan_type by hand.
  • C++ native stitcher: debug build + pref debug_prefs/use_cpp_stitcher = true. It needs the native lib, which our module does not build (no CMake / externalNativeBuild in photosphere/build.gradle.kts).
  • Restitch with another seam style: the RestitchOffer is produced (:1537-1556) and CaptureActivity keeps restitch(style), but no button calls it (CaptureActivity.kt:322-351, :391-395).

MainActivity.kt — upstream's single-activity app shell: entry chooser, permission gate, result screen, settings, "Open with" viewer, restitch

  • status: unreachable in our app (we launch only via CaptureActivity; their MainActivity is not registered in our manifest). It still compiles into our library.
  • our changes vs theirs: none (identical except CRLF).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
REQUIRED_PERMISSIONS CAMERA, plus WRITE_EXTERNAL_STORAGE when SDK_INT <= P (28) runtime permission set behind the camera :182-187. Our minSdk is 29, so storage is never added; our manifest also dropped WRITE_EXTERNAL_STORAGE
edge-to-edge SystemBarStyle.dark(TRANSPARENT) for both bars light icons forced over the black viewfinder :117-120 (CaptureActivity copies this, CaptureActivity.kt:143-146)
onNewIntent setIntent(intent); recreate() a new "Open with" while running restarts :133-139
external viewer intent.data or EXTRA_STREAM decoded with sampleSizeFor(..., PANO_TEXTURE_MAX_DIMENSION) → PanoramaSphereView open any image as a 360 from another app :234-276, :365-381. Needs the VIEW/SEND intent filters our manifest dropped
Entry Capture, Import first-screen choice :197-200, EntryChooser :498-617
debug entries "Capture fisheye" (DebugFisheyeCaptureScreen) and "Extended capture" (starts com.n30dyn4m1c.photosphere.extendedcapture.ExtendedCaptureActivity by class name, FLAG_ACTIVITY_NEW_TASK) when BuildConfig.DEBUG experimental capture flows :437-464, :409-415
settings icon top-start, 56 dp, padding(start=8, top=32) opens SettingsScreen :602-615
restitch restitchStyle default StitchStyle.Balanced; restitchSphere(appContext, offer.frames(), offer.params, style) "Restitch as Balanced / Crisp / Careful" on the result screen :287-326, :417-426
discardSphere deletes the cached sphere + buffer.clear() on Dispatchers.IO + NonCancellable; cancels a restitch in flight Take another :329-346
PermissionStatus resolver Granted / an empty results map → ShowRationale / rationale → ShowRationale / else PermanentlyDenied permission state machine :657-666
hasRequested rememberSaveable false asks once automatically; no re-fire on recreation :698, :712-717
screen name for LagTracker settings / little planet editor / gpano metadata editor / fisheye capture / result / entry / capture / import which screen a late frame happened on :353-363
  • authors' notes:
  • :110-116 the bars are pinned to light icons: the system day/night default paints dark icons over a black viewfinder. The app scheme is always dark.
  • :135-136 "Open with" while running → recreate, keeping that path stateless.
  • :172-181 HIGH_SAMPLING_RATE_SENSORS is a normal permission. Requesting it at runtime always fails; the manifest is enough. Storage is needed only on ≤ API 28 (MediaStore needs none for own media).
  • :191-196 Import needs no camera permission (the system picker grants per-photo access), so it sits beside the gate.
  • :202-214 two destinations, so a when instead of a nav graph. A non-null sphere is the single source of truth for the result screen.
  • :226-228 the sphere is deliberately not rememberSaveable: a File shouldn't be smuggled through a Bundle, and a stale result is worse than restarting.
  • :231-233 the "Open with" viewer has no UI button; it is reachable only by external intent.
  • :278-280 the buffer outlives the camera screen (ViewModel store), so the result screen can offer the frames. It is snapshotted at handover.
  • :333-341 a restitch in flight is cancelled on discard, or it would land after teardown. NonCancellable cleanup, because a multi-MB JPEG would otherwise be left. A fresh run must not inherit coverage.
  • :350-352 the camera opening is the expensive screen, so the log names the screen.
  • :578-579 experimental entries are debug only "until the walks are proven on device".
  • :636-656 permission gotcha: a dismissed dialog (swipe, call, screen lock) returns an EMPTY map. emptyMap().values.all{} is vacuously true, which would enter the camera with no permission (black viewfinder). Grants are read from the system instead, and shouldShowRationale is false after a cancel, so trusting it would wrongly send the user to Settings.
  • :694-697 hasRequested is saveable, so a recreation (font scale, dark mode, foldable) doesn't re-fire the dialog.
  • :719 the grant is re-checked on resume after a trip to Settings, so there is no restart.
  • :756-760 the permission screen is the front door for first-time users, so it is composed, not dumped.
  • :168 the log text "memorie redusa" is Romanian ("low memory"), a leftover from the original author.
  • unused features and how to turn them on:
  • All of it is unused. To bring a piece back, register MainActivity in the host manifest. Or call the composable you want from CaptureActivity: PanoramaResultScreen for Save/Share/Restitch/Export poses, SettingsScreen for the diagnostics report and the debug prefs, EntryChooser debug buttons for the fisheye / Extended capture.
  • "Open with" 360 viewer: needs an activity with the VIEW/SEND image/* intent filters (see the AndroidManifest section).
  • Extended capture (debug): a single Intent().setClassName(ctx, "com.n30dyn4m1c.photosphere.extendedcapture.ExtendedCaptureActivity") from CaptureActivity or the host works, because the debug manifest registers that activity (see the src/debug sections).
  • Note: CaptureActivity has no runtime-permission code of its own (grep finds none), so the Flutter host must hold CAMERA before launching it. That is from code reading; not checked how the host does it.

PhotoSphereApplication.kt — process start-up: crash report, file log, Material You flag, OpenCV load, picture-cache retention

  • status: the Application subclass is unreachable (our manifest has no android:name, so it never runs). Ours: ensureInitialized(context) is shipped-on. CaptureActivity calls it at CaptureActivity.kt:142, and DebugRestitch calls it at DebugRestitch.kt:57.
  • our changes vs theirs:
  • Added ensureInitialized(context) (:159-182), synchronized and once per process. It runs Report.install, FileLogger.init, MaterialYou.load, OpenCVLoader.initLocal().
  • It deliberately skips Logging.installCrashHandler(), pruneOrphanedSpheres(), pruneDeadImageCache(), pruneExpiredPhotos() and watchForeground() (so LagTracker.start() never runs in our app either).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
IMAGE_CACHE_GRACE_MILLIS 30_000L backgrounded longer than this → cached frames/spheres wiped at next launch :188 (not run in our app)
CACHED_PHOTO_RETENTION_MILLIS 3_600_000L (1 h) max age of cached pictures at start :195 (not run in our app)
BACKGROUND_MARKER "last_background" in cacheDir the timestamp file for the above :185
orphaned spheres keep only the newest cache/spheres/*.jpg cleanup after process death :78-88 (not run)
isOpenCvAvailable set by OpenCVLoader.initLocal() stitching on/off; read by the stitcher :202, :176
LagTracker start/stop on first activity resumed / last paused slow-frame counting :143-149 (not run: grep finds no other LagTracker.start in our tree, so LagTracker never counts in our app)
  • authors' notes:
  • :20-27 initLocal links the .so files inside the APK (no OpenCV Manager app). If it fails, stitching is off but capture still works, so the state is recorded instead of crashing.
  • :32 the report is installed first, so a crash below it is written down.
  • :37 Material You is read once at start, so the first composition knows it.
  • :46-51 a finished sphere whose process died is orphaned (the result screen held it only in memory). Each is several MB; the newest is kept, since it may be a stitch the user never saw.
  • :54-58 cached pictures must not outlive the app. If the last run ended more than 30 s ago, or there is no marker (crash/upgrade), frames and spheres are wiped. Logs and crash reports are kept.
  • :61-64 even a long-lived process mustn't hold pictures past the retention.
  • :93-97 a fresh marker means a quick return, so files are kept (the process may still be alive under a restored task).
  • :141-142 slow-frame counting runs only while something is resumed.
  • :161-166 (ours) embedded as a library, the Application never runs; the host calls this instead, minus the pruning and the foreground watcher.
  • unused features and how to turn them on:
  • Cache retention / dead-run wipe: call SphereImageStore.pruneExpiredPhotos(ctx, now - 3_600_000L) and/or deleteImageCache from ensureInitialized or CaptureActivity. Mind the debug keep-sessions logic.
  • Crash handler to logcat: add Logging.installCrashHandler() in ensureInitialized. Report's handler is already installed and writes filesDir/crashes/.
  • LagTracker: call LagTracker.start() in CaptureActivity.onResume and stop() in onPause.

Report.kt (diagnostics) — one shareable .txt: app version, Android exit reasons, saved crashes, slow frames, JSON log, logcat tail

  • status: install is shipped-on (via ensureInitialized), so uncaught crashes are written to filesDir/crashes/ in our app. build/share are unreachable (called only from SettingsScreen).
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
CRASHES_KEPT 3 crash files kept in filesDir/crashes/ :227
EXITS_KEPT 5 getHistoricalProcessExitReasons entries (API 30+) :228
ANR_LINES 400 ANR trace lines included :229
LOG_LINES 6000 logcat -d -v threadtime -b main,system,crash -t 6000 :230, :194-200
report file cache/reports/app-report-<version>.txt; the folder is emptied first output :100-104
share authority ${packageName}.reports FileProvider (manifest ${applicationId}.reports, report_paths.xml → cache/reports/) :108
redaction emails → <email>, Bearer … → Bearer <token>, access_token/refresh_token/id_token/code/client_secret values (≥ 8 chars) → <token>; names ≥ MIN_NAME = 3 chars → <account> privacy of the report :202-223, :236
extended-capture section (debug) newest getExternalFilesDir/extended_capture/run_*/optics.txt, count of extended_* frames, reference_raw.jpg size debug readout :89-95, :173-192, :231-235
divider 64 × = :237
version shown BuildConfig.VERSION_NAME = "0.0.6-beta+pw" (ours, a buildConfigField) theirs "0.0.6-beta" (versionName) photosphere/build.gradle.kts:22
  • authors' notes:
  • :24-29 no background recording: FileLogger already keeps 4 h of JSON and LagTracker counts only while on screen. Nothing runs while the app is closed. Pass appVersion explicitly.
  • :84-88 the debug extended-capture optics are included so a run can be read without adb. In release BuildConfig.DEBUG is a compile-time false, so the code drops out.
  • :159-161 exit reason codes 14/15/16 are mapped by number ("frozen", "app state changed", "app was updated"); they are newer than the SDK constants used.
  • :121 exit reasons are not kept before Android 11.
  • unused features and how to turn them on:
  • Report export: call Report.build(ctx, BuildConfig.VERSION_NAME) then Report.share(ctx, file) from any button in CaptureActivity. The provider and paths are already in our manifest.

LagTracker.kt (diagnostics) — Choreographer slow-frame counter with screen "where" marks

  • status: unreachable in practice. start() is called only from PhotoSphereApplication.watchForeground, which never runs for us. where() is called from MainActivity, and mark() from MaterialYou.setEnabled; both are unreachable. Its counts stay 0.
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
SLOW_MILLIS 50L a frame this late counts as lag :31
FREEZE_MILLIS 700L a frame this late is also logged as a warning (release); debug logs every slow frame :34, :78-83
KEPT 200 slow frames remembered :37
MARKS_KEPT 50 moments remembered :40
snapshot worst-N 10 worst frames in the report :174
  • authors' notes:
  • :19-24 lateness = now − frame's due time, not the gap since the last frame. The gap counted idle time, so an app idle for 6 s looked frozen for 6 s.
  • :62-64 uses System.nanoTime, not SystemClock.uptimeNanos (API 35+ only; the app runs from 26). Both read Choreographer's monotonic clock.
  • :73-77 debug builds write each late frame to the JSON log as it happens, because the in-memory list was lost when a process was killed before the report was opened.
  • :104-108, :120-123 a slow frame next to a palette flip, or "camera opening", explains itself; on its own it says little.
  • unused features and how to turn them on: call LagTracker.start() / stop() from CaptureActivity resume/pause, and LagTracker.where("capture"). Read it with LagTracker.report().

PoseExport.kt (diagnostics) — reads each frame's EXIF pose stamp back and writes cache/spheres/poses.txt

  • status: unreachable (its only caller is PanoramaResultScreen's debug "Export poses").
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
stamp regex index=(-?\d+);yaw=(-?[\d.]+);pitch=(-?[\d.]+);roll=(-?[\d.]+) (EXIF UserComment) what is parsed (ignores the debug ;matrix=…;hfov=…;vfov=… tail) :60-62
output cache/spheres/poses.txt (fixed name, overwritten), %.6f angles, Locale.US the report :101-131
  • authors' notes:
  • :15-28 values come from the files on disk, not from memory. Each line keeps the yaw=..;pitch=..;roll=.. shape that the CI pose reader searches sidecars for.
  • :38-40 a frame with no stamp is still listed, so line count = frame count.
  • :93-96 blocking I/O off main. It returns a Result and never throws (the caller is a button).
  • :103-104 the name is fixed: the report describes the sphere being held.
  • unused features and how to turn them on: call PoseExport.export(ctx, buffer.files()) (off main) after a stitch; the file is shareable through the existing spheres/ FileProvider path. DebugRestitch's own regex already reads the extra matrix/FOV fields.

DebugRestitch.kt (diagnostics, ours) — adb-triggered re-stitch of the newest kept session, once per variant, for A/B on real frames

  • status: ours. Debug-only at runtime: runIfRequested returns false unless BuildConfig.DEBUG (:54). Triggered from CaptureActivity.onCreate when savedInstanceState == null and cache/pw_restitch/request.txt exists; the activity then finishes without capturing (CaptureActivity.kt:119-125).
  • our changes vs theirs: the whole file is ours.
  • levers (flags are joined with + in one request line, one variant per line):
lever value OURS what it controls how to change
request file cache/pw_restitch/request.txt (deleted when read) trigger + variant list :45, :64-66; created with adb shell run-as <pkg> (scripts/capture_test.py)
input session the newest dir in cache/sphere_sessions by lastModified; frame_*.jpg, sorted by name, pose + matrix + hfov/vfov from the EXIF UserComment frames used :70-96
output cache/pw_restitch/<variant>.jpg (JPEG 90); older .jpg deleted first; "DebugRestitch done" logged at the end results :67-69, :193-203
refine useRefinement pose refinement :174
carve / wta SeamMode.Carve / WinnerTakeAll; default Blend seam style. Note: the app ships WinnerTakeAll (PhotoSphereCameraScreen.kt:509), so a plain base variant is NOT the shipped look; use wta :175-179
mask / block / graph / warp / oklab moving mask / per-block exposure / graph subset / local warp / perceptual seam same as the camera-screen A/B toggles :180-184
nadir StitchTuning.maskBehindNadir = ("nadir" in flags); shipped default true (EquirectangularRenderer.kt:1067) downward photos paint the side away from the holder. Gotcha: a variant WITHOUT nadir turns it OFF, so it differs from the shipped behaviour :106-107
sift StitchTuning.refineSift = true (default false, EquirectangularRenderer.kt:1047) SIFT matching in refinement :113
detN StitchTuning.refineDetectLongEdge = N (default 512, :1051) detection resize before matching :114-116
eyelevel / noeyelevel StitchTuning.tiltPenalty = 5000.0 / 0.0 (shipped default 0.0, EquirectangularRenderer.kt:1036) tilted photos don't paint furniture height when an eye-level one covers it. The comment says "(now the default)", but the code default is 0.0 (the rule is off): the comment contradicts the code :117-120
sharpN StitchTuning.featherPower = N (default 3, :1057) overlap-mix weight exponent :121-124
ringN keep N evenly spread eye-level (|pitch| < 20°) photos; all tilted ones kept fewer-photo experiments :98-100, :125-132
floor uses floor.jpg + floor_pose.txt (pitch defaults to 90 if unreadable) floor patch :134-148
bend also writes <variant>_bent.jpg bent joins :149-157
fovNN FOV × NN/100 (e.g. fov96) lens-angle correction; the M36's measured angle is ~3-5% narrower than reported :42-43, :159-162
arm0 / arm10 / arm20 PivotModel.None / lever arm 0.10 m / 0.20 m; default profile.pivot (0.35 m, PivotModel.kt:71) turning-axis offset :166-173
fixed maxInputDimension, maxOutputWidth, unsharpAmount from SphereDeviceProfile.forDevice :163-165
  • authors' notes:
  • :15-34 debug only; triggered by a request file over adb with run-as, never by the UI. The frames are the newest folder in cache/sphere_sessions.
  • :48-52 called when the app comes to the front, so capture_test.py can trigger it with a plain launch.
  • :68 previous results are deleted so a pull never mixes two runs.
  • :159-160 the M36's measured angle is about 3-5% narrower than it reports.
  • gotcha (from code): StitchTuning is a global object that is mutated, then restored after each variant (:187-191). If stitchPhotos threw instead of returning a Result, the restore would be skipped (unverified whether it can throw). The run executes on a plain Thread (:58).
  • gotcha (from code): if fewer than 3 frames, or no hfov stamp (hfov is in EXIF only in debug captures), it returns silently after the first log line (:101), and "DebugRestitch done" is NOT logged on that path.
  • gotcha (from code): no centerLongitudeDegrees / latitudeSpanDegrees is passed, so variants use the stitcher defaults. The output may be rotated relative to the shipped sphere, and a Ring capture is not cropped the same way (unverified: other agent's scope for stitcher defaults).
  • unused features and how to turn them on: already on in debug builds. Write request.txt and launch CaptureActivity.

FileLogger.kt + Logging.kt (util) — JSON-lines log file in cache/logs/photosphere.log + logcat helpers and crash handler

  • status: shipped-on (FileLogger.init runs in ensureInitialized). Logging.installCrashHandler is unreachable (it is called only from PhotoSphereApplication.onCreate).
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
RETENTION_MILLIS 4 * 3_600_000L (4 h) log entries older than this are pruned FileLogger.kt:23
PRUNE_EVERY 100 appends prune cadence :26
MAX_BYTES 3_000_000L past this, the oldest half is dropped :29
file cache/logs/photosphere.log location; adb shell "run-as <package> cat cache/logs/photosphere.log" :31-32, :17-18
stack trace cap 4096 chars per-line trace size :67
readRecent cap 1_048_576L bytes tail size in the report :110
Logging.TAG "PhotoSphere" logcat tag (adb logcat -s PhotoSphere) Logging.kt:16
  • authors' notes:
  • FileLogger.kt:7-16 INFO and above also go to the file, so adb can pull history logcat rotated away. DEBUG/VERBOSE stay logcat-only, because the 50 Hz attitude stream would be MBs per hour.
  • FileLogger.kt:52-53 appendText opens, writes and closes each line, so a crash right after logging keeps it.
  • Logging.kt:9-12 the crash handler exists so a background-thread crash (sensor thread, stitch worker) leaves a trace under one tag.
  • gotcha (from code): Logging.d DOES write to the file (Logging.kt:28-31), contradicting both KDocs, which say DEBUG stays logcat-only. Only v is logcat-only.
  • unused features and how to turn them on: none hidden. Pull the log with run-as as above (this is how scripts/ read sessions).

ui/theme (Color.kt, Theme.kt, MaterialYou.kt, Shape.kt, Type.kt) — always-dark palette, optional wallpaper accents, corner ladder, type scale

  • status: shipped-on. PhotoSphereTheme wraps CaptureActivity's content (CaptureActivity.kt:148). MaterialYou.load runs in ensureInitialized.
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
SphereAccent 0xFF3DDC84 (green) "captured/locked/yes"; primary Color.kt:29
SphereActive 0xFFFFC24B (amber) "aim here"; secondary :32
GlassSurface / GlassSurfaceDim black α 0.55f / 0.38f HUD panes :42, :45
GlassContent / GlassContentDim 0xFFF2F5F7 / same α 0.62f HUD text :48, :51
ChromeScrim black α 0.60f top/bottom gradient wash :54
surfaces Background 0xFF0A0D10, Surface 0xFF12171B, SurfaceHigh 0xFF1B2228, OnSurface 0xFFE7EDF1, OnSurfaceVariant 0xFF9DA9B3, Outline 0xFF333D45, PhotoWell 0xFF05070A dark ladder :63-81
pref photosphere_prefs / material_you default false wallpaper accents (Android 12+); neutrals stay the app's MaterialYou.kt:32-33, :47-61; switch only in SettingsScreen (unreachable)
shapes 8 / 12 / 18 / 24 / 30 dp; PillShape 50% corner radii Shape.kt:16-25
type platform FontFamily.Default; displaySmall 34 sp / −0.8 tracking; headlines 26/22 sp; titles 21/16/14 sp; body 16 sp / 23 lh type scale Type.kt:25-81
platform theme Theme.PhotoSphere parent android:Theme.Material.NoActionBar, transparent bars, window bg @color/sphere_background cold-start window res/values/themes.xml; used by CaptureActivity in our manifest
  • authors' notes:
  • Theme.kt:3-21 dark always. Both screens show an image, a light chrome tints it and glares while the user judges exposure, and the capture screen is black regardless.
  • Theme.kt:23-29, :68-73 with Material You the wallpaper gives only hues; the app keeps its neutrals, so the chrome stays dark and the capture markers follow the accent.
  • Theme.kt:65-66 the palette is recomputed only when the switch flips (a resource lookup).
  • MaterialYou.kt:11-29 dynamic colour exists only from Android 12, so the switch is hidden below. The flag lives in one observable holder, so a flip recomposes only the theme and the switch (otherwise the whole tree including the camera preview, with each press costing more).
  • Color.kt:5-24 the colour budget buys exactly two signals, warm/cool opposites, bright enough over a blown sky or a dark room. Defined once to stop drift.
  • Color.kt:47 content is not pure white, which glares against night scenes.
  • Shape.kt:3-13 radii climb with surface size, so a chip and a sheet look like one family.
  • Type.kt:10-23 platform font, because the APK already carries OpenCV for every ABI. Headlines are tracked tight; small labels are tracked wide for at-a-glance reading at arm's length.
  • unused features and how to turn them on: Material You, with photosphere_prefs/material_you = true on Android 12+.

AndroidManifest.xml (main) + res/xml + res/values — library manifest, FileProviders, backup rules, strings

  • status: shipped-on (merged into the host app).
  • our changes vs theirs:
  • No <application> attributes beyond android:largeHeap="true". Theirs set name/icon/label/theme/allowBackup/backup rules/supportsRtl/targetApi 31.
  • Registers .CaptureActivity (exported=false, screenOrientation=portrait, theme @style/Theme.PhotoSphere) instead of .MainActivity. Theirs was exported, a LAUNCHER, and had VIEW + SEND image/* intent filters for "Open with".
  • Dropped WRITE_EXTERNAL_STORAGE maxSdkVersion=28 (our minSdk is 29).
  • Comments shortened.
  • Removed res/mipmap-anydpi-v26 (adaptive launcher icons).
  • strings.xml re-worded (see the PhotoSphereCameraScreen section).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
permissions CAMERA, HIGH_SAMPLING_RATE_SENSORS, VIBRATE + WRITE_EXTERNAL_STORAGE max 28 AndroidManifest.xml:16-20
features camera.any required; sensor.gyroscope / sensor.accelerometer not required Play filtering :22-30
largeHeap true not set stitch holds several full-canvas buffers :32
sphere FileProvider ${applicationId}.fileprovider → cache/spheres/ (file_paths.xml) share a finished sphere (content:// URI) :42-50; file_paths.xml (path must match SphereImageStore.SPHERES_DIRECTORY)
report FileProvider ${applicationId}.reports → cache/reports/ share the diagnostics report :53-61; report_paths.xml
backup rules backup_rules.xml / data_extraction_rules.xml exclude captures/ referenced from theirs <application> unused in ours (not referenced). Their path captures/ doesn't match the real dirs (cache/sphere_sessions, cache/spheres; cache is never backed up anyway)
debug manifest registers ExtendedCaptureActivity (+ largeHeap) see the src/debug sections src/debug/AndroidManifest.xml
  • authors' notes (theirs, removed from our copy, kept here):
  • Storage: API 29+ writes through MediaStore with no permission. Nothing reads the photo library, so no READ_EXTERNAL_STORAGE / READ_MEDIA_IMAGES, which also avoids Android 14 selected-photos handling.
  • HIGH_SAMPLING_RATE_SENSORS is needed above 200 Hz (API 31+) to track attitude finely enough. It is a normal permission and must NOT be requested at runtime.
  • Portrait is deliberate (Google Camera does the same). From Android 16 the platform ignores fixed orientation on large screens and in multi-window, so the app follows the display instead of fighting it.
  • The FileProvider exists because a file:// URI throws FileUriExposedException on API 24+. The authority follows the applicationId, so debug .debug doesn't clash with release.
  • Only the reports folder is exposed to the report share.
  • unused features and how to turn them on:
  • "Open with 360" viewer: add an activity with the VIEW/SEND image/* filters (theirs AndroidManifest.xml, MainActivity block) that shows PanoramaSphereView.

build.gradle.kts (module) — how the engine is built inside our host vs upstream's app build

  • status: ours (rewritten). Upstream's app/build.gradle.kts is reference only.
  • our changes vs theirs:
  • com.android.library instead of the application plugin.
  • compileSdk 35 (theirs 37); minSdk 29 (theirs 26); no targetSdk/versionCode/applicationId.
  • buildConfigField VERSION_NAME = "0.0.6-beta+pw", because library modules have no VERSION_NAME.
  • Release isMinifyEnabled = false (theirs true + isShrinkResources), with consumer-rules.pro (the same OpenCV / native keep rules as their proguard-rules.pro).
  • No splits.abi block: the ABI is chosen by the host (android/app/build.gradle ndk { abiFilters "arm64-v8a" }).
  • No signing config; no applicationIdSuffix ".debug".
  • jvmToolchain(17) plus -Xwhen-guards, -Xnon-local-break-continue, -Xmulti-dollar-interpolation (theirs Kotlin 2.2.10 / AGP 9.3.1; ours uses the host toolchain).
  • No kotlin.exclude of orbit files: not needed, because orbit-disabled/ isn't copied.
  • Same dependency versions as upstream's catalog: core-ktx 1.15.0, lifecycle 2.8.7, activity-compose 1.9.3, compose-bom 2024.10.01, CameraX 1.4.0 (all four), exifinterface 1.3.7, opencv 4.12.0.
  • No test dependencies, and no test sources copied.
  • packaging.jniLibs.useLegacyPackaging = false is not set in ours (host default).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
compileSdk 35 37 API surface photosphere/build.gradle.kts:16
minSdk 29 26 device floor :19
VERSION_NAME "0.0.6-beta+pw" versionName "0.0.6-beta" logs, report, crash files :22
release minify false (+ consumer rules) true + shrinkResources R8 in the engine :26-30
ABI split none (host: arm64-v8a only) arm64-v8a, armeabi-v7a, x86_64, -PonlyAbi= narrows, isUniversalApk = false APK ABIs (OpenCV is ~120 MB unpacked for all ABIs) host android/app/build.gradle:36-37; theirs app/build.gradle.kts:60-71
buildConfig true true BuildConfig.DEBUG gates (debug plans, extended capture, sidecars, DebugRestitch) :39
OpenCV org.opencv:opencv:4.12.0 (Maven) same (option B: local SDK module :opencv) stitch :85
MediaPipe absent absent (was com.google.mediapipe:tasks-vision:0.10.14 for orbit) orbit subject tracker see the orbit-disabled sections
  • authors' notes (theirs app/build.gradle.kts):
  • :13-14 minSdk 26 keeps adaptive icons, ART and the modern camera2 pipeline without legacy fallbacks; CameraX itself supports 21+.
  • :23-25 release signing comes only from CI -P properties. Without them the release is unsigned.
  • :56-59 the OpenCV AAR has every ABI (~120 MB unpacked). Splitting keeps one ABI per APK; Play bundles do the same.
  • :84-86 buildConfig = true so BuildConfig.DEBUG lets R8 strip debug screens from release.
  • :94-95 OpenCV .so files load from the APK directly on API 23+ (useLegacyPackaging = false).
  • :100-123 orbit/MediaPipe is kept as source in app/orbit-disabled/ (no source set compiles it). The two kotlin.exclude lines don't actually keep files out, because AGP ignores them; moving the files is what does it. Don't put a slash-star glob in a Kotlin block comment, because it opens a nested comment and breaks the script.
  • Ours :5-7: compileSdk 35 is safe because the code has no BAKLAVA / SDK_INT >= 36 gates (checked when we vendored it).
  • unused features and how to turn them on:
  • R8 for the engine in release: set isMinifyEnabled = true in the host app module; the consumer rules keep OpenCV/JNI.
  • Unit tests: copy upstream app/src/test + testDebug, and add junit + kotlinx-coroutines-test as testImplementation (see the test/ section below).

Part 2: settings, result, importer, metadata, storage

SettingsScreen.kt — upstream's Settings page: Material You switch, diagnostics report export, panorama-tool launchers, and debug-only lag / target-plan / Samsung / stitcher-backend rows

  • status: unreachable in our app (we launch only via CaptureActivity, their MainActivity is not registered). The only caller is MainActivity.kt:383. Note: the PREFS this screen writes are still READ by code we ship (see levers), so the values a debug tester set earlier would still apply, but nothing in our app can change them.
  • our changes vs theirs: none (identical except CRLF). Indirect change: our PhotoSphereCameraScreen.kt:1098 and :401 wrap the debug target plan in if (false), so the "Debug Target Plan" picker below no longer changes the plan even in debug builds (it only shows up in the log line :1107 and the debug sidecar :1127).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
Material You row shown MaterialYou.isSupported = SDK_INT >= S (Android 12) hides the palette switch below Android 12 SettingsScreen.kt:85, ui/theme/MaterialYou.kt
pref photosphere_prefs / material_you (Boolean) default false wallpaper palette on/off; written MaterialYou.setEnabled (MaterialYou.kt:53), read once at start MaterialYou.load (PhotoSphereApplication.kt:38, :175) Settings > Material You switch (SettingsScreen.kt:322) — unreachable for us; or edit pref
BuildConfig.DEBUG gate debug-only rows: LagRows, TargetPlanRows (:88), SamsungRows (:93, also needs SamsungHighRes.isSamsung()), StitcherBackendRows (:101) which rows appear build type
pref debug_target_plans / plan_type (String enum name) default FULL_SPHERE (debug src/debug/.../DebugTargetPlans.kt:27-33); release stub always FULL_SPHERE, set is a no-op (src/release/.../DebugTargetPlans.kt:61-63) debug capture pattern; 8 types: Full Sphere, Horizon Ring, Tiny Planet, Asteroid, Freeze Frame, Surrounding, Three Steps, Forward Overturn radio list SettingsScreen.kt:143-168. In OUR build it is dead: PhotoSphereCameraScreen.kt:401 and :1098 are if (false)
pref samsung_highres / prefer_ultrawide (Boolean) default false debug + Samsung only: shoot the sphere on the ultrawide lens (preferWidestCamera = true); read once per camera screen at PhotoSphereCameraScreen.kt:322 switch SettingsScreen.kt:291-297; SamsungHighRes.setUltrawidePreferred
Samsung full-sensor still test writes cacheDir/samsung_highres/highres_<W>x<H>.jpg probes the largest sensor size (SamsungHighRes.probe) and takes one still; timeout HIGH_RES_TIMEOUT_MILLIS = 45_000L (SamsungHighRes.kt:252) button SettingsScreen.kt:228-273
pref debug_prefs / use_cpp_stitcher (Boolean) default false debug only: C++ OpenCV native stitcher instead of the Kotlin one. Read by StitcherBackend.getSelectedBackend (stitching/StitcherBackend.kt:15-16, 32-44), which forces KOTLIN in release; consumed at PhotoSphereCameraScreen.kt:1323 and ImportPhotosScreen.kt:168 switch SettingsScreen.kt:607-614, or StitcherBackend.setBackend
C++ stitcher output width outWidth = 1024, ssaa = 2, doGain = true size of the C++ path's sphere (not in this file) PhotoSphereCameraScreen.kt:1350-1354
lag log file name "lag-log.txt" (text/plain via SAF) debug frame-timing dump (LagTracker.report()) SettingsScreen.kt:397
report export Report.build(context, BuildConfig.VERSION_NAME), Save (SAF CreateDocument text/plain) / Send (Report.share) diagnostics report (recent activity, crashes); shown in all builds SettingsScreen.kt:457-512
panorama tools "Convert Panorama to Little Planet", "Add GPano Metadata to 360 photo" buttons open LittlePlanetEditorScreen / GpanoMetadataEditorScreen via MainActivity callbacks SettingsScreen.kt:520-561
  • authors' notes:
  • :51-61 Settings today is mainly the diagnostics report export; space left for future toggles. Material You is a release feature (capture + import screens follow the wallpaper palette when on). Frame timing readout is "for the moment" so stays debug only; the report is deliberately NOT behind the debug gate so any user can send one.
  • :82-84 palette switch is not gated by debug; it only shows where the platform can derive a palette — below Android 12 the switch "could only ever say no".
  • :116-122 the target plan picker only changes which targets the plan lays out and in what order; the user still aims manually.
  • :173-176 Samsung rows (full-sensor still test, ultrawide preference) are hidden on every other phone.
  • :302-308 Material You row: one line, one switch, deliberately no note.
  • :329-336 "It lags" is worth nothing without numbers, and numbers are only useful next to what was happening, so the lag file also carries moments like a palette flip (MaterialYou.setEnabled calls LagTracker.mark).
  • :342-343 the lag summary is re-read whenever the palette flips, because the point of the row is to see what a flip costs.
  • :405-408 report Save/Send live only in the Export section at the bottom so the button is not shown twice.
  • :564-565 stitcher backend toggle is debug only. UI text (:618): C++ path = "full native pipeline (spherical warp, multiband blend, bundle adjustment). Requires native library built via CMake"; Kotlin path (:620) = "Sensor-guided capture with OpenCV Java stitching fallback".
  • gotcha (from code, :572-577): useCppStitcher is a remember { mutableStateOf(...) } that the switch never assigns, so flipping it writes the pref but the switch and the description text do not visibly change until the screen is re-entered.
  • gotcha (from code, :126, :180): scope in TargetPlanRows is unused.
  • unused features and how to turn them on:
  • The whole screen is unused by us. To expose it, CaptureActivity would need a route to SettingsScreen(onBack, onLittlePlanetClick, onGpanoClick) (or register MainActivity).
  • Debug target plans: remove if (false) at PhotoSphereCameraScreen.kt:401 and :1098 (restores upstream's debug behaviour, which forced a full sphere in debug per our comment :1096-1097), and expose TargetPlanRows.
  • C++ stitcher: set debug_prefs/use_cpp_stitcher=true in a debug build (e.g. adb shell run-as <pkg> editing the prefs XML) and ship the native lib. Our module apps/mobile/android/photosphere/ has no src/main/cpp and build.gradle.kts has no externalNativeBuild/CMake, so the native library is not built in our app; what OpenCv360Stitcher.create() then does is unverified here (other agent's scope).
  • Samsung ultrawide: set samsung_highres/prefer_ultrawide=true on a Samsung debug build.
  • Material You: set photosphere_prefs/material_you=true (Android 12+); applies in release too.
  • status: unreachable in our app (we launch only via CaptureActivity, their MainActivity is not registered). Only caller MainActivity.kt:402 (opened from SettingsScreen's "Add GPano Metadata to 360 photo" button).
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
decode cap MAX_DIM 4096 (power-of-two inSampleSize until both sides ≤ 4096) max side of the photo that gets tagged and saved; bigger photos are downsampled, so the saved file is smaller than the original GpanoMetadataEditorScreen.kt:332-336
2:1 warning band ratio < 1.8f or > 2.2f → warning shows "Not a 2:1 photo, this is not a 360 pano"; does NOT block injection :346, banner :153-165
JPEG quality 92 re-encode quality of the tagged temp file :369
GPano fields written fullPano = croppedArea = bitmap W×H, croppedAreaLeft/Top = 0 (via GPanoMetadata defaults for the rest) always tags as a full uncropped 360×180 sphere :371-378
temp file cacheDir/gpano_*.jpg (kept, not deleted) holds the XMP-tagged file until Save :367
save target MediaStore Pictures/360Panoramas, name gpano_<millis>.jpg, image/jpeg where "Save with GPano Metadata" writes :412-416
picker PickVisualMedia.ImageOnly (system photo picker) which files can be chosen :215, :292
  • authors' notes:
  • :67-72 opens from Settings → Advanced settings → "Add GPano Metadata to 360 photo"; uses the system photo picker like ImportPhotosScreen; flow = import → GPano XMP injected → opens in viewer with a Save button.
  • :103 injection runs automatically when the source bitmap changes (no confirm step).
  • :152 the not-2:1 warning is persistent (stays on screen) rather than a snackbar.
  • :313-316 decode on IO and downsample to max 4096 px "to avoid OOM".
  • :354-357 the temp file is deliberately kept so the save copies the bytes with XMP intact (re-decoding/re-encoding would drop the XMP).
  • :380 return the XMP file itself, "don't decode to bitmap, don't delete".
  • :399-402 save copies the injected file byte-for-byte through MediaStore to keep the GPano XMP.
  • gotcha (from code): "Open in 360 Viewer" and the post-inject view are a flat Image(ContentScale.Fit) (:179-184), not the sphere viewer, despite the label.
  • gotcha (from code, :106): auto-inject only runs when xmpInjectedFile.value == null, and after injection the Import/Change buttons are hidden (:212, :289 need !showViewer), so only one photo can be tagged per visit; back out and re-enter for another.
  • gotcha (from code): the original EXIF is lost (bitmap re-encode) and the image is downsampled above 4096 px.
  • unused features and how to turn them on: whole screen unused. To use it, route to GpanoMetadataEditorScreen(onBack) from CaptureActivity. Our own captures do not need it: every sphere is already GPano-tagged by SphereImageStore (SphereImageStore.kt:499, :591).
  • status: unreachable in our app (we launch only via CaptureActivity, their MainActivity is not registered). Only caller MainActivity.kt:395 (from SettingsScreen "Convert Panorama to Little Planet").
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
initial tilt / zoom / pan / spin 0f / 300f / 0f / 0f starting slider values (zoom 300° here vs converter default 180f) LittlePlanetEditorScreen.kt:81-84
slider ranges Tilt -90..90, Zoom 60..359, Pan -180..180, Spin -180..180, step 1f, suffix ° user range per slider. Zoom above 350 is clamped by the converter (LittlePlanetConverter.kt:61) :214-217
slider steps ((end - start) / step).toInt() Compose counts intermediate stops, so e.g. Tilt has 180 steps → stop spacing 180/181 ≈ 0.994°, not exactly 1° (from code) :431
preview debounce delay(150) ms wait after a slider move before re-rendering :110-116
preview size 512 px live preview resolution :318
save size outputSize = 2048 (label "Save Little Planet (2048px)") saved image side :345, :272
decode cap MAX_DIM 4096 downsample picked image until both sides ≤ 4096 :381-385
2:1 warning band < 1.8f or > 2.2f shows "Not a 2:1 photo, this is not a 360 pano" :395
file name / album little_planet_<millis>.jpg, via MediaExporter.exportBitmap → Pictures/360Panoramas, JPEG q 92 where the result lands :351-352, MediaExporter.kt:350
  • authors' notes:
  • :64-68 opens from Settings → Advanced settings → Convert Panorama to Little Planet; uses the system photo picker like ImportPhotosScreen.
  • :101 preview auto-generates when a source is picked; :109 slider changes re-render with a 150 ms debounce.
  • :302-303 preview at 512 px; :329-330 save at 2048 px.
  • :362-365 decode on IO and downsample to max 4096 px "to avoid OOM".
  • gotcha (from code): the 2:1 warning tolerates 1.8–2.2, but LittlePlanetConverter.convert requires exactly width == height * 2 (LittlePlanetConverter.kt:44); neither generatePreview (:314-326) nor saveLittlePlanet (:342-353) catches that, so a near-2:1 image (e.g. 8000×4001) throws inside a coroutine — likely an app crash (unverified on device).
  • gotcha (from code): the converter leaves transparent corners (LittlePlanetConverter.kt:83) but the save is a JPEG, so the corners cannot stay transparent (exact colour unverified).
  • gotcha (from code): every slider tick launches a new full render on scope without cancelling the previous one (:314), so renders can finish out of order (unverified visually).
  • unused features and how to turn them on: whole screen unused; route to LittlePlanetEditorScreen(onBack) from CaptureActivity to expose.

LittlePlanetConverter.kt — pure-Kotlin CPU stereographic ("little planet") projection from an equirectangular bitmap

  • status: unreachable in our app. Only callers are LittlePlanetEditorScreen.kt:316 and :343, which is itself unreachable.
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
outputSize default param 2048 square output side, circle inscribed LittlePlanetConverter.kt:38
fovDegrees default param 180f zoom (bigger = wider) :39
tiltDegrees / panDegrees / spinDegrees defaults 0f / 0f / 0f view pitch / view yaw / output roll :40-42
FOV clamp coerceIn(20.0, 350.0) avoids degenerate projection at extremes :61
stereographic scale 2.0 * tan(halfFovRad / 2.0) maps image edge to half-FOV from nadir :65
input check require(width == height * 2) exact rejects anything not exactly 2:1 (throws IllegalArgumentException) :44-46
sampling bilinear, ix/iy clamped to W-2 / H-2, no wrap across the 0/W seam output sharpness and seam handling :129-154
output ARGB_8888, alpha 0 outside the circle and on zero-length directions transparent corners :49, :83, :116
  • authors' notes:
  • :16-22 pure Kotlin/CPU, "no RenderScript"; meant to run off the main thread; projection from the nadir, tilt/pan move the view centre, spin rolls the output, zoom = FOV.
  • :60 FOV clamped "to avoid degenerate projection at extremes".
  • :63-64 scale chosen so screen edge (dist = radius) lands at halfFov; unit stereographic r = 2·tan(θ/2).
  • :87 spin is applied to screen coordinates before projecting.
  • :91-92 θ is the angle from the nadir (looking down, −Y).
  • :113 direction re-normalised "to guard against drift".
  • :124-127 longitude wrapped into [0,1); latitude 0 at north pole, π at south.
  • gotcha (from code): bilinear sampling clamps at eqW - 2 instead of wrapping, so the column at the 0/W seam is never blended with column 0 (a faint seam line is possible; unverified visually).
  • gotcha (from code): whole-image IntArrays for input and output — a 4096×2048 source is ~32 MB of ints plus ~16 MB for a 2048² output; not tested here on low-RAM phones (unverified).
  • unused features and how to turn them on: could make a "little planet" share image of a Property Walk sphere by calling LittlePlanetConverter.convert(bitmap) on an exactly 2:1 bitmap; not wired anywhere in our app.
  • status: shipped-off (in code, disabled). Callers in shipped code: PhotoSphereCameraScreen.kt:1267 (exportFrames, "Save frames") is reachable only through a HUD button whose visibility we pinned to canSaveFrames = false (PhotoSphereCameraScreen.kt:1815). PanoramaResultScreen.kt:213/479/913 and LittlePlanetEditorScreen.kt:352 are unreachable (MainActivity only). SphereImageStore.kt:37/89 only mention it in KDoc. So nothing in our app writes to the gallery.
  • our changes vs theirs: none in this file. Indirect: our CaptureFlow replaced upstream's result screen (CaptureActivity.kt:391-395: an agent tapped "Saved to gallery" thinking it saved the point, 2026-11-25), and the camera HUD's "Save frames" is forced off at PhotoSphereCameraScreen.kt:1815 (upstream: canSaveFrames = bufferedFrames.isNotEmpty() && stitchJob == null, upstream PhotoSphereCameraScreen.kt:1561). Our library minSdk = 29 (photosphere/build.gradle.kts:19) vs upstream app minSdk = 26, so the API 26–28 legacy branches below are dead code for us, and our library manifest declares no WRITE_EXTERNAL_STORAGE (upstream declares it, capped at API 28).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
ALBUM "360Panoramas" album folder name MediaExporter.kt:55
RELATIVE_PATH "Pictures/$ALBUM" MediaStore relative path (API 29+) :61
MIME_TYPE "image/jpeg" MediaStore mime :63
FILE_NAME_PREFIX + date format "panorama" + yyyyMMdd_HHmmss (Locale.US) → e.g. panorama_20261126_101500.jpg default sphere name, sorts chronologically :65, :78-82
frame name frame_<sessionDirName>_%02d.jpg (fallback session) names for "Save frames" export :149-150
bitmap JPEG quality 92 (pending and legacy paths) Little Planet and other derived images :350, :389
API split SDK_INT >= Q (29) → pending insert; else legacy direct write write path :106, :169
debug frame check keys "yaw=", "pitch=", "roll=", "hfov=" in EXIF TAG_USER_COMMENT debug-only log warning when an exported frame lacks baked pose/FOV :189-200 (called at :137 when BuildConfig.DEBUG)
NonCancellable export runs on dispatcher + NonCancellable copy cannot be abandoned halfway :103, :133, :167
  • authors' notes:
  • :26-33 spheres stay in the app cache until the user asks to keep them; this is "the step that asks". Own album so they do not scatter through the camera roll, and every gallery/backup/share target can see them.
  • :35-38 the JPEG is copied byte for byte — never decoded/re-encoded — because a re-encode drops the GPano XMP and the gallery then shows a flat wide picture instead of a pannable sphere.
  • :42-45 API 29+: insert with IS_PENDING = 1, stream, then publish with IS_PENDING = 0; nothing half-written is visible, and no storage permission is needed.
  • :47-50 API 26–28: no RELATIVE_PATH/pending flag; write into public Pictures and point the row at it with DATA; needs WRITE_EXTERNAL_STORAGE, which upstream's MainActivity.REQUIRED_PERMISSIONS requests on exactly those versions.
  • :87-89 pass real width/height so gallery apps can lay the image out without decoding.
  • :91-94 NonCancellable once the row exists — an abandoned copy would leave a pending row nothing will publish or clean up; failures come back as a failed Result ("tell the user, not crash").
  • :119-127 exportFrames is the "save what I shot" escape hatch; names carry session id + position so re-exports do not collide; EXIF (attitude in every build, camera basis + FOV in debug builds) travels along because it is a byte copy; any failure fails the whole batch.
  • :152-158 exportBitmap is for derived in-memory images (e.g. Little Planet) that have no source file.
  • :182-188 the debug check never rewrites anything; a warning means the user's file has the same gap.
  • :222-223 straight byte copy so GPano XMP and every EXIF tag arrive exactly as written.
  • :226-227 a pending row nobody publishes is invisible "but not free" — delete it rather than leave a zero-byte entry.
  • :238-240 if the publish update hits 0 rows, delete and fail loudly so the user is never told "Saved to gallery" for a row that stays pending/invisible.
  • :251-254 legacy path writes the file first and inserts the row after, because inserting first could leave a row pointing at a file that never appears.
  • :277-278, :290-291 legacy failures delete the partial/unindexed file to avoid clutter in the user's public Pictures.
  • :309-314 uniqueFile appends (n); MediaStore does this itself from API 29, but below it a second export in the same second would silently overwrite the first.
  • unused features and how to turn them on:
  • Save frames to gallery: set canSaveFrames = bufferedFrames.isNotEmpty() && stitchJob == null at PhotoSphereCameraScreen.kt:1815 (upstream value); the confirm dialog SaveFramesConfirmation (:1628-1636) is still wired.
  • Save the finished sphere to gallery: call MediaExporter.export(context, sphere.file, width = w, height = h) from our CaptureFlow (upstream did it from PanoramaResultScreen); deliberately removed by us — see CaptureActivity.kt:391-395.
  • Legacy API 26–28 branches only matter if our minSdk drops below 29 and WRITE_EXTERNAL_STORAGE (maxSdkVersion 28) is added to our manifest.

PanoramaResultScreen.kt — upstream's post-stitch screen: sphere preview + fullscreen, Save to gallery, Share, Take another (with discard prompt), Save frames, Restitch as Balanced / Crisp / Careful, debug diagnostics + Export poses

  • status: unreachable in our app (we launch only via CaptureActivity, their MainActivity is not registered). Only caller MainActivity.kt:417. CaptureActivity.kt:45 still imports it but never calls it; our CaptureFlow draws its own review instead (CaptureActivity.kt:389-442: PanoramaSphereView + "Use this view" + "Retake"). Everything else in the file is private, so nothing in our app uses it.
  • our changes vs theirs: none in this file. Replaced at the call site: CaptureActivity.kt:391-395 — "Upstream's result screen showed debug text, Export poses, Save to gallery, Save frames, Share and New photo — an agent tapped 'Saved to gallery' thinking it saved the point, and nothing reached the tour (2026-11-25)." Our replacement also drops the Restitch chips even though CaptureFlow still holds the restitch wiring (CaptureActivity.kt:322-351, restitch() is defined but no button calls it).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
PREVIEW_MAX_DIMENSION 1440 default long edge for decodePreview; now unused because the call passes PANO_TEXTURE_MAX_DIMENSION PanoramaResultScreen.kt:98, call :172
preview decode size PANO_TEXTURE_MAX_DIMENSION = 2048 (from PanoramaView.kt:43), power-of-two sampleSizeFor (PhotoSphereStitcher.kt:1302-1307) texture handed to the sphere view :172
default preview mode PreviewMode.Panorama (Flat removed) flat vs pannable preview; selector only lists Panorama :166, :619
preview well aspect 16f / 9f preview box shape (fixed ratio because the column scrolls) :470
diagnostics collapse show all if lines.size <= 7, else first 6 + "… +N lines — tap to expand" debug-only diagnostics block (BuildConfig.DEBUG && sphere.diagnostics != null) :378-404
debug "Export poses" shown when BuildConfig.DEBUG && frameFiles.isNotEmpty(); PoseExport.export → shared as text/plain pose report off the on-disk frames :411-443, :989-1014
debug colours badge shown when sphere.debugColors warns the image is solid-colour placement checks, not a photo :360-376
Save frames button canSaveFrames = frameFiles.isNotEmpty() && !isWorking && restitching == null per-frame gallery export behind a confirm dialog :520, dialog :271-280
Restitch chips shown when onRestitch != null; styles Balanced / Crisp / Careful; current style marked re-stitch buffered frames with another style :838-884
onHighResRerun / highResRerunLabel default null / "" debug extended capture's 4K rerun button; no normal path passes it :156-157, :888-907
share ACTION_SEND, image/jpeg, FileProvider URI via SphereImageStore.shareUri, ClipData + FLAG_GRANT_READ_URI_PERMISSION, chooser with FLAG_ACTIVITY_NEW_TASK share sheet for the sphere :952-980
Save button sizes height 54.dp; share/take-another 50.dp layout :729, :798, :816
  • authors' notes:
  • :92-97 a 4096×2048 sphere is 32 MB decoded on a screen a tenth that wide; 1440 keeps the flat preview sharp for ~4 MB.
  • :118-122 the photo is already a GPano-tagged JPEG in cache and nothing is published yet, deliberately, so a bad run never has to be deleted out of the camera roll.
  • :124-128 KDoc says the preview defaults to the flat equirectangular frame (the "honest picture": black pole wedges = parts never reached) with a toggle to the sphere view. Stale: the code now defaults to Panorama and has no flat mode (:165, :617-618 "flat preview removed, but the selector and enum are kept").
  • :130-142 frameFiles empty for imported spheres; onRestitch null when frames are gone (e.g. imported); restitchError shown once then consumed.
  • :153-155 the optional high-res rerun button is null on every normal path "so the screen is exactly what it always was unless a caller asks for it".
  • :182 the decoded bitmap is the screen's own scratch and is recycled on dispose.
  • :189-191 leaving discards the sphere (only in cache), so back = delete unless exported; both exits ask first.
  • :195-197 diagnostics grow one line per frame; on a 36-frame sphere they pushed the preview and export button off screen, so the column scrolls and the block starts collapsed.
  • :200 fullscreen = the pannable view alone "like a web 360 viewer"; :282-283 it is a Dialog so system back closes it instead of discarding the sphere.
  • :203-207 Save frames is the same escape hatch as the capture screen's; confirm first.
  • :229-237 while an export is in flight it cannot be cancelled (NonCancellable), so leaving would land the photo in the gallery after the user confirmed destroying it; the exit waits and shows a snackbar instead.
  • :250-251 without the BackHandler, back would leave the activity with a sphere still cached.
  • :326-329 header deliberately compact: everything above the photo is space taken from the photo.
  • :358-359 solid-colour placement checks are not photographs, so say so on screen, not only in debug diagnostics.
  • :380-381 diagnostics collapsed because a full sphere lists ~forty frames.
  • :406-410 debug pose export: stamped attitudes are meant to be inspected outside the app; cheapest honest route is a text report read back off the files; only when there are frames (an imported sphere's cells came from elsewhere).
  • :466-467 fixed aspect ratio, not weight, because a scrollable column cannot give weight a bounded height.
  • :532-536 frame export confirm: dozens of full-res JPEGs is storage and clutter worth a caution icon and an exact count.
  • :569-577 discard prompt: until exported the cached JPEG is the only copy — "minutes of standing in one place turning on the spot, undone by one tap" next to Share; never shown once saved.
  • :714-716 a restitch replaces the file every other button reads, so all other actions wait while one runs.
  • :723-725 Save gets full width + filled style because it is the one action with consequences; "the hierarchy is the recommendation".
  • :731-733 Save is disabled (not hidden) once done — "Saved to gallery" answers "did that work?", and re-tapping would file a second copy.
  • :736-738 the landed export keeps the accent colour; a dimmed control would read as "unavailable".
  • :772-773 frames are "asked for, never assumed".
  • :818-819 Take another is held back during export: the file being copied is the one this button deletes.
  • :835-837 restitch is for "a flaw worth re-rolling", only while frames are buffered.
  • :932-933 tapping the current style re-stitches identically ("harmless but pointless"), so the landed style stays marked.
  • :945-950 share sends the JPEG as-is (GPano intact) via a FileProvider URI with a read grant; a file:// URI would throw FileUriExposedException on API 24+; returns false when nothing can receive an image. :956 IllegalArgumentException means the file is outside every path in file_paths.xml. :964 some targets read the grant off ClipData, not the extra. :972 started from a Context that may not be an Activity.
  • :985-987 the pose report lives in the spheres cache dir, which the FileProvider already serves, so only the MIME type differs.
  • unused features and how to turn them on:
  • Restitch as Balanced / Crisp / Careful: our CaptureFlow already keeps restitchOffer, restitchStyle, restitching, restitchError and restitch(style) (CaptureActivity.kt:322-351) — either add chips to our review screen calling restitch(...), or call PanoramaResultScreen(sphere, frameFiles, onTakeAnother = ::discard, madeWith = restitchStyle, restitching = restitching, onRestitch = restitchOffer?.let { { s -> restitch(s) } }, restitchError = restitchError, onRestitchErrorShown = { restitchError = null }) exactly as MainActivity.kt:417-426 does (but that brings back Save-to-gallery, which we removed on purpose).
  • Fullscreen sphere viewer (Dialog) and Share sheet: copy :284-310 / shareSphere (:952-980) into our review if wanted.
  • Debug Export poses / diagnostics block: only on this screen; port :378-443 to see them in our debug builds.

PanoramaView.kt — the GL (OpenGL ES 2.0) drag-to-look / pinch-to-zoom inside-out sphere viewer (PanoramaView + PanoramaSphereView composable), plus a pure-Kotlin mirror of its UV maths

  • status: shipped-on. PanoramaSphereView is the 360° preview in our review step (CaptureActivity.kt:414-418), and PANO_TEXTURE_MAX_DIMENSION sizes that preview's decode (CaptureActivity.kt:406). Also used by unreachable PanoramaResultScreen.kt:295/676 and MainActivity.kt:372.
  • our changes vs theirs: none. Note: upstream's unit test app/src/test/java/com/n30dyn4m1c/photosphere/result/PanoramaUvTest.kt (which pins equirectUvForView) is not vendored — our module has only src/main, src/debug, src/release.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
DEFAULT_FOV_DEGREES 70f vertical FOV the viewer opens at PanoramaView.kt:34
DRAG_SENSITIVITY_DEGREES 160f degrees turned per one screen width of drag (both yaw and pitch use width) :37
PITCH_LIMIT_DEGREES 89f pitch clamp ±89° (mapping degenerates at ±90°) :40
PANO_TEXTURE_MAX_DIMENSION 2048 (public const) long edge the texture is decoded to (2048×1024 for a sphere); used by our CaptureActivity review :43
zoom clamp 15f..120f (telephoto..fisheye) pinch zoom limits :104, KDoc :68
initial yaw / pitch 0f / 0f opens on the image's middle column (u = 0.5), horizon level :73, :77
render mode RENDERMODE_WHEN_DIRTY redraws only on gesture/texture change :85
GL version setEGLContextClientVersion(2) GLES 2.0 :81
texture wrap S = GL_REPEAT, T = GL_CLAMP_TO_EDGE; filters GL_LINEAR (no mipmaps) seam bleed across ±180°, pole edge clamp :238-241
latitude span spanLat = 2π·H/W, clamped 0.05f..π lets a ring (shorter than 2:1) sit at its true elevation instead of stretching over the poles :216-217
shader precision precision mediump float fragment maths precision :321
drag direction yaw += pan.x/width·160, pitch += -pan.y/width·160 "drag right turns right, drag up looks up" :445-455
  • authors' notes:
  • :45-53 KDoc: the flat 2:1 frame is never really looked at; seams and horizon are judged by panning, so this is "deliberately an inspection tool" and the result screen keeps the flat frame as the honest overview. (Stale for the result screen, which removed the flat preview; and our CaptureFlow shows only this view.)
  • :54-57 a per-pixel software remap in Compose cannot hold 60 fps, hence a GLSurfaceView with a fragment shader casting one ray per pixel.
  • :57-59 poles stay legible: looking up shows the black wedges, same as the flat frame.
  • :62 until setSphere uploads pixels the view stays black.
  • :83-84 redraw only when dirty; gestures call invalidateView.
  • :88 setSphere is safe from any thread (queued to the GL thread).
  • :124-125 every renderer entry point runs on the GL thread, so no locking.
  • :141-148 latitude span derived from aspect (square pixels ⇒ width:height = 360°:span): a ring capture's band must sit at its true elevation, the flat preview looks right either way but the sphere view would deform a band mapped as a sphere.
  • :170-171 texture uploaded lazily in onDrawFrame because surface creation and the bitmap can arrive in either order.
  • :235-237 REPEAT on S because the ±180° seam is one pixel column; it lets seam samples bleed across instead of showing the black clamp edge.
  • :243-244 GL keeps its own copy after upload; the Kotlin bitmap stays with the caller's decode lifecycle.
  • :160 / :274 a failed link/compile leaves the view black and is logged.
  • :306-319 camera basis follows the app's convention: forward (sin yaw cos pitch, cos yaw cos pitch, sin pitch) in X-east / Y-north / Z-up; right = horizontal bearing 90° off the aim; vertical half-angle = FOV, horizontal stretched by aspect (mirrors SphereProjection.focalLengthPx); sampling inverts Equirectangular.direction (lon atan2(x,y), lat asin(z)), so it is the same sphere the flat frame draws, centred on north.
  • :348-351 equirectUvForView mirrors the GLSL so the convention can be pinned by unit tests; :397-399 the mirror must normalise the ray too, or asin reads an unnormalised z (atan2 is scale-invariant so u needs no fix).
  • :407-411 gestures live in the composable (Compose detectors) to stay testable.
  • :427-428 the GLSurfaceView must get onResume/onPause, or its thread keeps rendering behind a backgrounded screen.
  • :446-449 drag: one screen width = 160°, "Street-View convention — dragging right turns the view right (yaw grows, matching the compass convention); dragging up looks up".
  • gotcha (from code): with GL_CLAMP_TO_EDGE on T, a ring capture (span < π) shows the top/bottom texture rows smeared when the viewer looks past the band, not black (unverified on device).
  • gotcha (from code): yaw 0 is the texture centre column; in our captures that is the compass bearing LastSphereInfo.centerYawDegrees, so the review opens facing that bearing.
  • unused features and how to turn them on:
  • Read the current view (PanoramaView.yawDegrees / pitchDegrees / fovDegrees are public getters) to set e.g. a tour's initialYaw from where the agent was looking — not wired; PanoramaSphereView keeps the PanoramaView private inside remember, so you would need to expose it.
  • Restore the unit test by copying upstream app/src/test/.../result/PanoramaUvTest.kt into photosphere/src/test/....
  • status: shipped-on. Our CaptureActivity shows it when the intent has mode = "photos" (CaptureActivity.kt:153, :366-375, no camera gate :165); the Flutter host sends that from the "Use photos I already took" button (apps/mobile/lib/features/upload/upload_panorama_screen.dart:338 → lib/services/capture360.dart:55 → host android/app/src/main/kotlin/in/propertywalk/property_walk/MainActivity.kt:38). Also called by upstream MainActivity.kt:468 (unreachable).
  • our changes vs theirs: none in this file. At the call site we pass restitchOffer = null (CaptureActivity.kt:372), so an imported sphere can never be re-stitched, and LastSphereInfo.centerYawDegrees stays null for imports (CaptureActivity.kt:77-80), so no heading is returned. Imported copies in cacheDir/imports are deleted when CaptureActivity finishes (CaptureActivity.kt:233).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
MAX_PICK 100 max photos the system picker returns (PickMultipleVisualMedia(MAX_PICK)) ImportPhotosScreen.kt:70, :117
minimum photos PhotoSphereStitcher.MIN_STITCHABLE_FRAMES = 2 below it: "Pick at least two photos." PhotoSphereStitcher.kt:225; checks :128, :141
ATTITUDE_RE yaw=(-?\d+(?:\.\d+)?);pitch=(...);roll=(...) on EXIF TAG_USER_COMMENT recognises frames this app stamped (SphereImageStore) :73-74, :465-474
pose rule stamped poses only if every photo has one; else even ring mixed sets always fall back to the ring :134, :147-154
fallback ring step horizontalFovDegrees * 0.65f, pitch 0, roll 0, centred on 0° ((index - (count-1)/2) * step) yaw spacing for unstamped photos, in pick order :480-489
FOV used optics.fieldOfView = this phone's own camera FOV (rememberSphereOptics) lens FOV assumed for ALL photos, foreign ones too :100, :144
radial distortion null none applied (foreign lens unknown) :231
stitch caps deviceProfile.stitchMaxInputDimension, .stitchMaxOutputWidth, .unsharpAmount from SphereDeviceProfile.forDevice input downscale, output width, sharpening :101, :232-234 (values in SphereDeviceProfile, other scope)
seam mode default SeamMode.Blend; button cycles Blend → Carve → WinnerTakeAll, label "Seams: blend/carve/winner" overlap strategy; the button is NOT debug-gated, so agents see it :110, :408-425
C++ backend branch only if StitcherBackend says CPP (debug + debug_prefs/use_cpp_stitcher); outWidth = 1024, ssaa = 2, doGain = true, doRefine = true, refineIters = 4 native stitch path :168-224
import copy location cacheDir/imports/import_<millis>/import_%02d.jpg; previous import dir deleted on a new pick where picked photos are copied :122-127
diagnostics text "Import: N photos / Poses: stamped EXIF|even ring / Seams: … / FOV: H° x V° (screen)" attached to the StitchedSphere (shown only on upstream's result screen in debug) :248-252
cancel "Cancel" TextButton → stitchJob?.cancel() abort the stitch :313-315
  • authors' notes:
  • :76-79 stitches gallery series or frames this app saved earlier through "Save frames".
  • :80-85 stamped UserComment poses are used only when every pick has one; otherwise a horizon ring in pick order spaced by the lens's overlap step — "the honest assumption for an ordered left-to-right series", which pose refinement (when enabled) corrects; "half a run of stamped poses plus half a run of guesses is neither".
  • :87-89 same PhotoSphereStitcher as capture, only the pixels' origin differs; a foreign lens's distortion is unknown, so none is applied.
  • :108-109 the prototype's winner-takes-all overlap lives here too so one import can be re-run with each strategy on the same photos; :406-407 same three strategies as capture's debug toggle.
  • :111-112 progress travels as a flow because the stitcher reports from a worker thread and Compose state must not be written from there.
  • :476-478 ring poses are centred on 0°.
  • string import_body: "an ordered left-to-right series works best. Photos this app saved reuse the exact angles they were shot at."
  • gotcha (from code): the fallback ring is a single horizon row with yaw spread (count-1)·0.65·hFOV; it never wraps or closes the circle, so N photos give a partial strip unless they really were shot at that spacing (e.g. 100 photos at hFOV 65° would span far over 360°).
  • gotcha (from code): our app can never produce stamped frames for the gallery because "Save frames" is off (PhotoSphereCameraScreen.kt:1815), so in practice our imports always take the even-ring path unless the photos came from an upstream build.
  • gotcha (from code): the "Seams:" cycle button is visible in release builds of our app.
  • unused features and how to turn them on:
  • Restitch for imports: give CaptureFlow a RestitchOffer built from the picked files instead of null (CaptureActivity.kt:372) — not built upstream either (KDoc PanoramaResultScreen.kt:137-138 says imported spheres have no restitch).
  • Hide the seam toggle for agents: wrap :408-425 in if (BuildConfig.DEBUG).
  • C++ stitch path: see SettingsScreen use_cpp_stitcher.

GPanoXmpInjector.kt — GPanoMetadata (full-pano / sphere-region maths) + a byte-level JPEG marker splicer that writes the GPano XMP packet without re-encoding

  • status: shipped-on. Every sphere our app hands back is tagged through it: SphereImageStore.writeStitchedSphere → GPanoXmpInjector.inject(temp, gpano) (SphereImageStore.kt:499), called from capture (PhotoSphereCameraScreen.kt:1382, :1474 with forSphereRegion), restitch (Restitch.kt:137-140) and import (ImportPhotosScreen.kt:244). Also used by unreachable GpanoMetadataEditorScreen.kt:379.
  • our changes vs theirs: none. Upstream's unit test app/src/test/java/com/n30dyn4m1c/photosphere/metadata/GPanoXmpInjectorTest.kt is not vendored (our module has no src/test).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
projectionType default PROJECTION_EQUIRECTANGULAR = "equirectangular" GPano:ProjectionType GPanoXmpInjector.kt:44, :71
usePanoramaViewer default true → written "True" GPano:UsePanoramaViewer, "the switch a viewer actually reads" :46, :298, :381
forFullPano(w,h) full = cropped = w×h, left/top 0 full 360×180 tag :77-84
forSphereRegion ranges longitude span 1f..360f, latitude span 1f..180f, centre latitude -90f..90f (require) ring/partial tag: fullW = round(w·360/lonSpan), fullH = round(h·180/latSpan), centre longitude folded into [-180,180), left/top clamped as rounding guards :99-135
capture's call longitudeSpanDegrees = 360f, centerLongitudeDegrees = 0f, latitudeSpanDegrees = latitudeSpanDegrees (180 for Sphere scope, vFOV × RING_LATITUDE_SPAN_FACTOR capped 180 for Ring), centerLatitudeDegrees = 0f what our spheres get tagged as (Sphere scope ⇒ identical to forFullPano per KDoc :96-97) PhotoSphereCameraScreen.kt:1477-1483, span :401-412
TOOLKIT "PhotoSphere" (x:xmptk) tool marker in the packet :181
TEMP_SUFFIX ".gpano.tmp" sibling file while rebuilding :201
MAX_SEGMENT_LENGTH 0xFFFF packet must fit one APP1 or IOException :198, :257-260
insertion point after the last APP0/APP1 (JFIF, EXIF), before ICC/others where the XMP segment goes :270-277
existing XMP APP1 starting with http://ns.adobe.com/xap/1.0/\0 or http://ns.adobe.com/xmp/extension/\0 is dropped replace, never append :362-366
xpacket end "r" (read-only, no padding) packet trailer :314-316
fields NOT written no PoseHeadingDegrees, InitialViewHeadingDegrees, InitialViewPitchDegrees, InitialHorizontalFOVDegrees, CaptureSoftware, etc. (from code: only the 8 attributes at :298-311) viewers open on their own default heading buildXmpPacket :292-317
  • authors' notes:
  • :18-29 every length is in pixels of the image the metadata is attached to; CroppedArea = what part of the full sphere the pixels cover; a partial capture keeps the full-pano size of the complete sphere and places the covered rectangle inside it, so a viewer renders only the band and limits panning, instead of black wedges.
  • :43 viewers only understand equirectangular; :70 it is "the only projection Google Photos, Facebook and friends will render".
  • :92-97 a ring is expressed as a horizontal slice of a full sphere; a full sphere passed through forSphereRegion resolves to the same values as forFullPano.
  • :114-119 longitude is periodic; folding the centre into [-180,180) keeps the cropped rectangle inside the bounds; a region straddling ±180° must be expressed on one side (same unwrap as the canvas).
  • :129-131 the clamps only guard against a rounding landing one pixel past the edge.
  • :142-144 without this the output is "just a wide picture"; neither ExifInterface nor Bitmap.compress can write an XMP packet.
  • :146-151 pixels never touched: walks marker segments, drops old XMP, splices a new APP1, copies the rest (incl. entropy-coded scan) verbatim — re-encoding would cost another generation of JPEG loss.
  • :155-159 metadata APPn segments sit before quant tables and scan; the packet goes after JFIF/EXIF "where readers expect it", before heavier things like ICC.
  • :161 plain java.io, so unit-testable off-device.
  • :173-177 extended-XMP continuation is never written (GPano packet is a few hundred bytes) but recognised so replacing someone else's XMP can't orphan a continuation.
  • :206-209 width/height must be the real pixel size; wrong values give a pano that does not close or is squashed at the poles.
  • :211-214 blocking I/O off the main thread; failures return a failed Result because a sphere without metadata is still a good image — "losing it over a header would be the worse outcome".
  • :229-232 some filesystems refuse rename onto an existing name; fall back to atomic Files.move(REPLACE_EXISTING) rather than delete-then-rename (which would open a window with neither copy).
  • :279-280 from the first non-metadata marker on, bytes are copied as-is.
  • :289-290 UsePanoramaViewer is the switch; the rest says how to wrap pixels.
  • :314-315 "r" = read-only (no padding), nothing may edit in place; rewriting the segment, as this class does, is still fine.
  • :348 any number of 0xFF fill bytes may precede a marker.
  • :362-363 two XMP packets in one file is undefined; readers take the first.
  • :380 XMP booleans are the capitalised words, not 1/0 or lowercase.
  • unused features and how to turn them on:
  • Heading in the file: add GPano:PoseHeadingDegrees (and/or InitialViewHeadingDegrees) to buildXmpPacket from LastSphereInfo.centerYawDegrees; today the heading travels only as the heading intent extra (CaptureActivity.kt:212). Not built.
  • forSphereRegion with longitudeSpanDegrees < 360 (partial arcs) is supported by the maths but no caller uses it (capture always passes 360).
  • Restore tests: copy upstream GPanoXmpInjectorTest.kt into photosphere/src/test/....

SphereImageStore.kt — owns the engine's cache layout: per-capture frame folders, the one finished GPano-tagged sphere, EXIF pose stamps, debug sidecars, FileProvider share URI, and cache wipes

  • status: shipped-on (core path). Used by our CaptureActivity (StitchedSphere type; deleteCachedSphere on Retake CaptureActivity.kt:360; deleteImageCache on finish in release :232), by camera stitch (PhotoSphereCameraScreen.kt:1331-1382, :1474), import (ImportPhotosScreen.kt:172-244), restitch (Restitch.kt:94, :137), and ImageBufferManager (ImageBufferManager.kt:120-361). Retention sweeps (pruneExpiredPhotos) are called only from PhotoSphereApplication.onCreate (PhotoSphereApplication.kt:72), which never runs embedded — see below.
  • our changes vs theirs: none in this file. Around it (ours): PhotoSphereApplication.ensureInitialized (PhotoSphereApplication.kt:162-180) runs the start-up "minus the cache pruning and the foreground watcher", so pruneExpiredPhotos, pruneDeadImageCache and pruneOrphanedSpheres never run in our app; instead CaptureActivity copies the sphere to cacheDir/pw_captures (keeps KEEP = 4) and on finish deletes sphere_sessions, spheres, walks (deleteImageCache) and imports in release; debug keeps the last KEEP_DEBUG_SESSIONS = 6 session folders (CaptureActivity.kt:126-136, :227-240, :249, :299).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
SPHERE_JPEG_QUALITY 95 JPEG quality of the finished sphere (writeStitchedSphere(quality = …) default) SphereImageStore.kt:76, :483
SESSIONS_DIRECTORY "sphere_sessions" cacheDir/sphere_sessions/<sessionId>/ frame folders :57
SPHERES_DIRECTORY / SPHERES_DIRECTORY_NAME "spheres" finished-sphere folder; must match res/xml/file_paths.xml <cache-path path="spheres/"> :66-69
SPHERE_FILE_PREFIX + name sphere_ + yyyyMMdd_HHmmss + .jpg, temp .jpg.tmp sphere file names; stale sweep matches sphere_*.jpg :54, :488-490
session id format yyyyMMdd_HHmmss_SSS (Locale.US) folder name; ms precision on purpose :104-109
frame names frame_%03d.jpg; burst candidates frame_%03d_t%d.jpg per-target files :132-133, :152-156
ALBUM "PhotoSphere" used only in EXIF ImageDescription ("PhotoSphere frame N", "PhotoSphere equirectangular panorama") — not the gallery album (that is MediaExporter 360Panoramas) :50, :415, :600
EXIF frame stamp UserComment = index=%d;yaw=%.3f;pitch=%.3f;roll=%.3f + debug-only ;matrix=… (%.6f) and ;hfov=%.4f;vfov=%.4f; Software = PhotoSphere; Orientation re-written pose stamp the importer's ATTITUDE_RE parses :363-450
CAPTURE_SUMMARY_FILE "capture_debug.json" (debug only) sidecar: hFOV, vFOV, portraitRotation, planType, targetCount :238-269, :345
C++ poses.json debug only; hfov_deg, shots {file,index,yaw_deg,pitch_deg = -pitch,roll_deg} input to native stitcher :292-329
default GPano GPanoMetadata.forFullPano(bitmap.width, bitmap.height) tag when the caller passes none (import, non-ring path) :484
FileProvider authority "${packageName}.fileprovider" share URI (manifest provider ${applicationId}.fileprovider) :550-551
retention (caller side) CACHED_PHOTO_RETENTION_MILLIS = 3_600_000L (1 h), IMAGE_CACHE_GRACE_MILLIS = 30_000L, marker last_background upstream start-up sweeps; dead in our embed PhotoSphereApplication.kt:185-195
  • authors' notes:
  • :24-39 three destinations: cache sessions (raw frames, large, cleared when next run starts), the sphere cache (one finished GPano JPEG shown on the result screen, goes no further unless asked), MediaStore (MediaExporter; "Export to gallery" is the only thing that exposes a sphere).
  • :40-45 sessions and spheres are intermediate data, not keepsakes; deleted on discard/start-over; survivors of a process death are wiped shortly after the app was last backgrounded; long-running processes swept at next start; diagnostics logs never touched.
  • :59-65 the spheres dir is shared via FileProvider and named in res/xml/file_paths.xml too; they must stay in step or Share fails with IllegalArgumentException at tap time.
  • :71-75 quality 95 because the sphere is the only kept image and has already been through one JPEG generation.
  • :88-91 StitchedSphere is a File, not a Bitmap: both destinations want a file, and a 4096×2048 bitmap is 32 MB of heap to carry across a screen change.
  • :105-107 millisecond session ids because the manager is recreated on configuration changes and two sessions in the same second would share a folder and mix frames.
  • :114-117 frames go to cache, not gallery: "a user who asked for one sphere has not asked for forty-four photos in their camera roll".
  • :124-125 fail early on mkdir — otherwise it surfaces later as a baffling CameraX "no such file" error.
  • :147-150 burst candidates keep _t{k} names until a winner is promoted, so the session holds exactly one file per index.
  • :173-176 a sphere's frames are ~100 MB; cache is only reclaimed under pressure, so an abandoned run is cleared at the start of the next.
  • :195-201 pruneExpiredPhotos bounds a long-lived process; cache/logs and filesDir/crashes are outside these dirs and left alone.
  • :231-237 debug sidecar gives an offline stitcher what EXIF lacks (actual FOV, EXIF-rotation turn, plan type, target count); never written in release.
  • :285-290 C++ convention: world X right, Y down, Z forward; yaw about Y (+ right), pitch about X (+ UP), roll about Z (+ clockwise from behind); R = Ry·Rx·Rz camera→world. :312-314, :333-335 Kotlin pitch is negative above the horizon, so it is negated for C++.
  • :350-355 the EXIF pose is the stitcher's starting guess ("the difference between searching for correspondences and merely confirming them"); UserComment because EXIF has no attitude tag; fixed key=value; form for unambiguous parsing.
  • :356-361 the stitch itself reads the pose from the in-memory BufferedFrame; never rely on saveAttributes for it — that rewrite re-encodes the JPEG and has dropped CameraX's ORIENTATION tag on some files, which decodeUpright rotates by; "the rotation tag is the one thing the file cannot lose".
  • :369-376 debug builds append the rotation matrix because angles collapse and yaw is arbitrary near the poles, exactly where a laptop stitcher needs the matrix; release keeps the angles-only shape the importer parses.
  • :378-384 debug builds append FOV so every frame carries its own calibration; release must keep the exact importer shape.
  • :406-408 read and re-write ORIENTATION explicitly, or saveAttributes() may reset it to NORMAL and every frame decodes landscape.
  • :426-429 debug reads the EXIF back to prove each key landed; cheaper than finding out at stitch time.
  • :447 / :605 metadata is a nice-to-have; never lose the frame/sphere over it.
  • :455-458 writeStitchedSphere is the handover between stitching and result; preview, export and share all work from that one file.
  • :460-463 default tag = full sphere; ring captures pass forSphereRegion.
  • :465-469 order matters: EXIF first (saveAttributes rewrites the file and may not carry unknown segments), GPano second so the sphere marker is written by the last thing to touch the file.
  • :471-475 built under a temp name and moved into place; the previous sphere is deleted only after the swap so a failed encode never destroys the last good output; only one sphere is ever in play.
  • :501-503 a GPano failure is recoverable: the file still opens, just flat.
  • :505-507 atomic move; REPLACE_EXISTING also absorbs a same-second name collision.
  • :519-522 only final-name sphere_*.jpg files are swept; a .tmp belongs to whatever is still writing (or a crashed run).
  • :544-548 share needs a FileProvider URI (file:// throws on API 24+); authority from the running package because the debug build has a .debug suffix.
  • :563-568 deleteImageCache is for after a process death: no screen references the files; logs and crash reports deliberately kept, "only pictures go".
  • :589-592 the "this is a 360 photo" marker is XMP GPano, not EXIF; ExifInterface cannot write XMP.
  • gotcha (from code): stampCaptureOrientation does call saveAttributes() on each frame (:424), the very rewrite the KDoc warns about; the guard is re-writing ORIENTATION first.
  • gotcha (from code): writeStitchedSphere deletes every other sphere_*.jpg in the folder (:523-531), so two stitches can never coexist in spheres/; our CaptureActivity relies on copying out to pw_captures before that matters.
  • unused features and how to turn them on:
  • Time-based retention (1 h) and dead-run wipe: only in PhotoSphereApplication.onCreate; to use embedded, call SphereImageStore.pruneExpiredPhotos(context, now - 3_600_000L) from ensureInitialized or CaptureActivity.
  • pruneSessions(context, keepSessionId) deletes EVERY session folder except the current one, with no debug or test_ exception (:180-190). It runs in all builds from ImageBufferManager.pruneStaleSessions (ImageBufferManager.kt:359-363), triggered by LaunchedEffect(sessionId) in the camera screen (PhotoSphereCameraScreen.kt:1049-1051, same as upstream :909-910). From code this looks like it defeats our debug "keep the last 6 captures" logic (CaptureActivity.kt:126-136, KEEP_DEBUG_SESSIONS = 6): as soon as a new camera capture opens, older session folders are pruned. Unverified on device — check with scripts/capture_test.py pull-all after two captures; a fix would be to skip pruneStaleSessions when BuildConfig.DEBUG.
  • Debug capture sidecar + matrix/FOV EXIF are on automatically in debug builds (for scripts/capture_test.py-style offline restitch).

ImageBufferManager.kt — the in-memory index of one capture session's frames (files on disk + attitude), with burst promotion, undo, clear, session restart and a ViewModel holder that survives configuration changes

  • status: shipped-on. rememberImageBufferManager() is used by our CaptureFlow (CaptureActivity.kt:320, buffer.files() :321, buffer.clear(deleteFiles = !BuildConfig.DEBUG) on Retake :361) and the camera screen (PhotoSphereCameraScreen.kt:390/442; reserveFrame / reserveBurstFrames :3054-3056, commitBestFrame :3091, undoLastFrame :1774, cancelSession :1756, pruneStaleSessions :1050, debugCaptureFovDegrees :1114), plus night capture (NightCaptureExtensions.kt:36, :89). record(bitmap, …) and frameAt have no callers.
  • our changes vs theirs: none in this file. Call-site difference: on Retake we call buffer.clear(deleteFiles = !BuildConfig.DEBUG) (keeps frames on disk in debug), upstream MainActivity calls buffer.clear() (MainActivity.kt:344).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
DEFAULT_JPEG_QUALITY 95 quality when a Bitmap is recorded (record(bitmap, quality = …); no callers) ImageBufferManager.kt:36, :261
BUFFER_HOLDER_KEY "photosphere.ImageBufferManager" ViewModelStore key of the holder :39, :401
debugCaptureFovDegrees null (set by camera screen in debug only to [hFOV, vFOV]) appended to every frame's EXIF comment as ;hfov=;vfov=; also seeds the C++ path's hFOV :97, PhotoSphereCameraScreen.kt:1114-1117
burst size count from caller (deviceProfile.burstPerTarget; night nightConfig.framesPerTarget); require(count > 0) candidates per target before the sharpest is promoted :134-146, PhotoSphereCameraScreen.kt:1167
clear(deleteFiles = true) default deletes JPEGs, keeps session id after a successful stitch / discard :314-328
undo rule drops the most recently shot frame (maxBy capturedAtMillis), not the highest index "undo that shot" :287-301
superseded-session rule a frame whose parent folder ≠ current sessionId is deleted and returns null (SessionSupersededException class exists for callers) stops a late shutter from an old run joining the new set :49-50, :216-221
stale prune pruneStaleSessions() → SphereImageStore.pruneSessions(keep = current) deletes every other session folder :358-363
  • authors' notes:
  • :41-48 a frame whose session was cancelled mid-shutter is a silent drop, not a capture failure — the user asked for the restart.
  • :56-59 capture produces frames faster than anything consumes them and the stitcher needs the whole set at once; this sits between ("Finish & stitch" reads files), thrown away after.
  • :61-66 pixels stay on disk: forty-odd full-res JPEGs as bitmaps would be several hundred MB of heap; only paths + sensor metadata are in memory.
  • :67-70 mutations suspend and touch disk; reads are safe from composition; a Mutex serialises mutations so two captures finishing at once cannot lose a frame.
  • :77-78 holds the application context, because the manager outlives screens and would leak an Activity.
  • :90-96 debug FOV calibration is stamped so a laptop stitcher reads focal length off the JPEG; null in release; never read by the on-phone stitch.
  • :129-132 canonical frame_%03d.jpg is reserved for the winner; candidates _t{k} until commitBestFrame; single-frame callers keep using reserveFrame.
  • :151-157 promotion happens inside the candidate's own folder so a frame from a superseded session stays put and record's session check still rejects it; the stitcher reads frames, never the folder.
  • :169-172 atomic replace on promotion; deleting the canonical first could lose both copies if the process died between calls.
  • :181-183 deleting losing siblings can never hit the winner: burst names always carry _t{k}.
  • :198-205 re-recording an index replaces the entry (retries don't duplicate); a stray frame from a cancelled session is "exactly what a stitcher cannot cope with".
  • :212-215 session check and append share one lock, otherwise a concurrent cancel could append a frame whose file was just deleted.
  • :254-255 bitmap record is for ImageAnalysis frames or tests; it does not recycle the bitmap.
  • :279-284 undo is the Street-View-style "undo that shot" for a blurred frame or something moving through; its target becomes active again. :289-290 targets can be shot in any order, so undo takes the last shot, not the highest index.
  • :306-312 clear keeps the session id (capture continues in the same folder); deletion is NonCancellable because a buffer cleared as the screen goes away would otherwise leave a sphere's worth of JPEGs with nothing left to clean them.
  • :333-339 cancelSession removes the whole folder so a half-written capture can't survive; an in-flight capture must be cancelled by the caller's coroutine or its frame lands in the new folder.
  • :350-352 same-millisecond restart would reuse the name, harmless because the folder is already gone.
  • :374-382 the ViewModelStore holder keeps the session across recreation (font scale, locale, dark mode, foldable resize, Android 16 force-rotated large screens) instead of a fresh session whose first act would prune the previous run's files "out from under the user"; a session abandoned by finishing the activity is cleared by pruneStaleSessions on the next run.
  • :383 falls back to composition scope without an activity (previews). :393-394 uses the public ViewModelProvider, not internal ViewModelStore.put.
  • gotcha (from code): pruneStaleSessions keeps only the current session, which appears to cancel our debug "keep last 6 captures" (see SphereImageStore section).
  • unused features and how to turn them on:
  • record(bitmap, index, orientation, quality) — record frames from an ImageAnalysis stream instead of takePicture; no caller.
  • frameAt(index) — per-target lookup; no caller.
  • Bursts (sharpest-of-N per target) are driven by deviceProfile.burstPerTarget (SphereDeviceProfile, other scope); this file already supports any count > 0.

BufferedFrame.kt — data class for one buffered frame: file, capture-plan index, yaw/pitch/roll, camera-basis matrix, capture time

  • status: shipped-on. Produced by ImageBufferManager.record (ImageBufferManager.kt:235-243), consumed by restitch (Restitch.kt:75), night capture (NightCaptureExtensions.kt:34), the stitch path via buffer.frames, and the pose-type note in SphereImageStore.kt:357.
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
cameraBasis default null full rotation matrix ([right, −up, forward] columns, CameraBasis.toRotationMatrix layout); null only for frames without a sensor sample BufferedFrame.kt:33
sign conventions yawDegrees −180..180 compass bearing; pitchDegrees −90..90 negative above horizon; rollDegrees −180..180 how every consumer reads the angles :19-24
elevationDegrees -pitchDegrees (positive up) convenience getter; no callers of this property found outside the file (other elevationDegrees hits are on OrientationData/SphereTarget) :38
  • authors' notes:
  • :8-12 angles copied from OrientationData keep its conventions (yaw = compass bearing, pitch negative above the horizon); held in memory as well as EXIF so the stitcher can order/pre-align without re-reading forty-odd JPEG headers.
  • :16 index = position in the capture plan and the file's sequence number.
  • :25-32 the stitcher reconstructs the pose from cameraBasis, because it carries the orientation exactly where Euler components collapse (a frame aimed at the zenith).
  • :35 capturedAtMillis orders frames of equal index (and drives undo-last-shot in ImageBufferManager).
  • gotcha (from code): data class with a FloatArray field — equals/hashCode compare the array by identity, not contents; undoLastFrame uses filterNot { it == last }, which still works because it compares the same instance.
  • unused features and how to turn them on: none beyond the unused elevationDegrees getter.

Part 3: src/debug, src/release, orbit/, app/orbit-disabled/, tests

Catalog part: debug / release source sets, orbit, orbit-disabled, tests

Scope: src/debug, src/release, src/main/.../orbit/{OrbitPlan,OrbitStore}.kt (ours == theirs except CRLF), upstream-only app/orbit-disabled/* (18 files) and upstream-only src/test + src/testDebug. Line numbers are OUR copy where one exists, else upstream (marked "theirs").

How our build consumes these source sets (read from the gradle files, not from a built APK): - Our photosphere module is an Android library (apps/mobile/android/photosphere/build.gradle.kts:9); the Flutter host (apps/mobile/android/app/build.gradle:63) depends on it with implementation project(":photosphere"). A host debug build gets the library's debug variant (so src/debug is compiled and its manifest merged); a host release build gets src/release. Standard AGP variant matching; unverified against a built APK. - Host applicationId is in.propertywalk.property_walk with no debug suffix (app/build.gradle:27), not upstream's theclumsypirate.com.photosphere.github(.debug). - Our library manifest (src/main/AndroidManifest.xml) registers only CaptureActivity; upstream MainActivity.kt is still compiled in our src/main but is not registered, so nothing it opens (Settings, EntryChooser, fisheye screen, extended-capture button) is reachable. - Our PhotoSphereCameraScreen.kt replaced upstream's if (BuildConfig.DEBUG) with if (false) at line 401 (latitude span) and line 1098 (plan). Lines 1107 and 1127 still call DebugTargetPlans.getSavedType(context) under BuildConfig.DEBUG (log label + debug sidecar), so the debug DebugTargetPlans IS executed in our debug builds, read-only. - Upstream excludes orbit code via app/build.gradle.kts:100-132 (theirs): the files live in app/orbit-disabled/, which no source set compiles; our vendored tree does not contain that folder at all.


AndroidManifest.xml (src/debug) — debug-only manifest additions: registers ExtendedCaptureActivity, turns on largeHeap

  • status: debug-only; merged into our debug APK but nothing in reachable code starts the activity → unreachable in our app
  • our changes vs theirs: none (identical modulo CRLF)
  • levers:
lever value OURS value THEIRS if different what it controls how to change
android:largeHeap true – bigger Dalvik heap for the 4096x2048 extended render src/debug/AndroidManifest.xml:18 (ours already sets largeHeap in src/main/AndroidManifest.xml, so this is redundant for us; upstream main does not set it)
ExtendedCaptureActivity exported false – only in-app code can start it line 22
screenOrientation portrait – locks the extended screen to portrait line 24
theme @style/Theme.PhotoSphere – theme line 25
label @string/extended_capture_label ("Extended capture") – activity label line 23 / debug/res/values/strings.xml:6
  • authors' notes:
  • l.5-9: merged only into debug, so release never contains ExtendedCaptureActivity; no launcher entry of its own (one icon in debug); opened from a debug-only entry-chooser button; not exported so nothing outside the app can start it.
  • l.14-16: largeHeap because the extended capture renders a 4096x2048 sphere with several full-canvas float arrays; debug only so release is unaffected.
  • unused features and how to turn them on: the activity is registered in our debug APK but its only launcher is upstream MainActivity.kt:445-460 (EntryChooser button, unregistered in ours). To use it: from host/CaptureActivity debug code call startActivity(Intent().setClassName(ctx, "com.n30dyn4m1c.photosphere.extendedcapture.ExtendedCaptureActivity")) behind BuildConfig.DEBUG (same pattern as upstream MainActivity.kt:449-456). Not exported, so adb shell am start should be refused (standard Android rule; unverified on device).

strings.xml (src/debug/res/values) — debug-only string for the extended-capture label

  • status: debug-only; only used by the (unreachable) ExtendedCaptureActivity
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
extended_capture_label "Extended capture" – activity label line 6
  • authors' notes: l.2-4: merged only into the debug variant.
  • unused features and how to turn them on: n/a (main also has entry_extended_capture = "Extended capture", src/main/res/values/strings.xml:67, used by the unreachable EntryChooser button).

ic_launcher_foreground.xml (src/debug/res/drawable) — debug launcher foreground: yellow knot plus DEBUG banner

  • status: debug-only; unused in our app (host uses @mipmap/ic_launcher PNGs from app/src/main/res/mipmap-*; our library has no mipmap-anydpi that references this drawable)
  • our changes vs theirs: none
  • levers: none (vector art, 108dp, viewport 512)
  • authors' notes: l.2-3: DEBUG variant only, release keeps the brand mark from main; vectors have no shadows.
  • unused features and how to turn them on: n/a.

DebugTargetPlans.kt (src/debug) — debug-only picker of alternative capture patterns (8 plan types saved in SharedPreferences)

  • status: debug-only. In ours: getSavedType() is executed in debug builds (PhotoSphereCameraScreen.kt:1107 log label, :1127 debug sidecar planType), always returning FULL_SPHERE because the only setter UI (SettingsScreen.kt:124-176 TargetPlanRows) is reachable only from unregistered MainActivity. fullSphere() (:1099) and the HORIZON_RING latitude branch (:402-405) sit under if (false) → unreachable. The six alternate builders are never called anywhere, even upstream.
  • our changes vs theirs: none in this file. Call-site change in PhotoSphereCameraScreen.kt: if (BuildConfig.DEBUG) → if (false) at :401 and :1098 (comment at :1095-1096: "the scope toggle drives the plan in every build (upstream forced a 36-frame full sphere in debug)").
  • levers:
lever value OURS value THEIRS if different what it controls how to change
pref file PREFS "debug_target_plans" – SharedPreferences file holding the choice line 27
pref key KEY_PLAN_TYPE "plan_type" (enum name string) – saved plan type; default FULL_SPHERE lines 28, 31-35; set via setSavedType (l.38) or upstream Settings → "Debug Target Plan" radio list
tinyPlanet elevations 0, 20, 40, 60, 75, -20, -40, -60, -75, -85, -88 – extra rings near nadir lines 79-83
asteroid elevations -85, -75, -60, -40, -20, 0, 20, 40, 60, 75 (nadir first) – bottom-up walk lines 101-104
freezeFrame defaults centerElevation = 0f, bandHeight = 30f, clamp ±75 – 3-ring band lines 116-117, 127-131
surrounding default elevation = 15f, one ring – single off-horizon ring line 142, 151
threeSteps elevations 0, 45, -45 – 3 rings line 165
forwardOverturn 0, then 15..75 step 15, then -15..-75 step 15 (11 rings) – horizon→zenith→nadir lines 181-186
yaw spacing (all alt builders) hFov * FIELD_OF_VIEW_SAFETY_FACTOR (0.9) * (1 - DEFAULT_TARGET_OVERLAP_FRACTION (0.35)) – equator yaw step, widened by 1/cos(elev) per ring lines 72-76 etc.; constants in SphereTarget.kt:156,170
pole guard shrink <= 1e-3f → 360° spacing; count coerceAtLeast(1) – ring target count near poles lines 264-266
ring direction odd rings reversed – serpentine sweep line 251
  • authors' notes:
  • l.17-24: picker changes only which targets the plan lays out and in what order; the user still aims manually.
  • l.44-47: fullSphere matches production SphereTargetPlan.createForFieldOfView.
  • l.56-58: horizon ring = faster, equirectangular output with black poles.
  • l.66-70: tiny-planet plan is denser near horizon/nadir because the stereographic projection stretches the nadir.
  • l.88-92, 109-113, 136-139, 154-157, 169-172: asteroid / freeze / surrounding / three_steps / forward_overturn are modelled on Insta360 plan JSONs (asteroid-north_pole, freeze-normal.json, surrounding-normal.json, three_steps-normal.json, forward_overturn-normal.json).
  • l.239-241: createUnchecked is an internal copy of SphereTargetPlan.Companion.createUnchecked (that one is private at SphereTarget.kt:232).
  • Observation (not an author note): Type descriptions/scopes disagree with the builders: SURROUNDING says "Three rings: horizon, +30°, -30°" but surrounding() is one ring at 15°; FREEZE_FRAME says "single ring" but builds 3; TINY_PLANET/ASTEROID say "walk a ring" but build 11/10 rings; FORWARD_OVERTURN says "single ring" but builds 11.
  • Observation: upstream debug always lays fullSphere() (theirs PhotoSphereCameraScreen.kt:956-957) whatever type is picked; picking HORIZON_RING only shrinks the canvas latitude span (theirs :367-373), i.e. a full-sphere walk rendered into a ring-height canvas.
  • Observation: in our debug builds the log line type= (:1107) and the debug sidecar planType (:1127) always say Full Sphere / FULL_SPHERE even for a Ring-scope capture — misleading when reading logs.
  • Imports DEFAULT_EQUATOR_SPACING_DEGREES and DEFAULT_RING_ELEVATIONS (l.4-5) are unused.
  • unused features and how to turn them on: (1) set the pref without UI: debug builds via adb shell run-as in.propertywalk.property_walk editing shared_prefs/debug_target_plans.xml key plan_type (run-as needs a debuggable build; unverified); (2) make the plan follow it: replace if (false) at PhotoSphereCameraScreen.kt:1098 with a when (DebugTargetPlans.getSavedType(context)) that maps each Type to its builder (no such mapping exists anywhere today), and restore :401 so the canvas span matches; (3) the setter UI already exists as SettingsScreen.TargetPlanRows (shown under BuildConfig.DEBUG, SettingsScreen.kt:88-91) but needs a reachable SettingsScreen.

DebugTargetPlans.kt (src/release) — release stub so main compiles; only Type enum, getSavedType, setSavedType, fullSphere

  • status: shipped (compiled into release) but never executed: every call site is under BuildConfig.DEBUG or if (false)
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
getSavedType always Type.FULL_SPHERE – stub line 61
setSavedType no-op – stub line 63
  • authors' notes: l.5-11: exists only so main sources compile in release, where call sites are behind BuildConfig.DEBUG and never execute. The Type enum (l.14-59) is a verbatim copy of the debug one, including the mismatched descriptions.
  • unused features and how to turn them on: none (stub). Note our library release has isMinifyEnabled = false (photosphere/build.gradle.kts:28), so unlike upstream (R8 on) the stub is not stripped.

DebugFisheyeCaptureScreen.kt (src/debug) — placeholder "Capture fisheye" R&D screen with two buttons that do nothing

  • status: debug-only; unreachable in our app (only caller is upstream MainActivity.kt:409-416, unregistered)
  • our changes vs theirs: none
  • levers: none. Both buttons ("Import fisheye images", "Fisheye camera capture (experimental)") have onClick = {} (l.58, l.67).
  • authors' notes:
  • l.26: debug-only fisheye capture R&D UI, not shipped in release.
  • l.52: subtitle is Romanian: "Alege modul de captură fisheye (UI R&D, doar debug)" = "choose the fisheye capture mode (R&D UI, debug only)".
  • unused features and how to turn them on: nothing behind it to turn on; no fisheye capture/import code exists in this scope.

DebugFisheyeCaptureScreen.kt (src/release) — release stub, composable that renders nothing

  • status: shipped (compiled), never executed
  • our changes vs theirs: none
  • levers: none
  • authors' notes: none (no comments).
  • unused features and how to turn them on: n/a.

ExtendedCaptureActivity.kt — debug-only host activity for ExtendedCaptureScreen; prunes old runs on start

  • status: debug-only; unreachable in our app (see manifest section)
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
prune on create pruneOldRuns(now - ExtendedStore.RETENTION_MILLIS) (1 h) on Dispatchers.IO – deletes old extended runs each launch lines 36-41
system bars SystemBarStyle.dark(TRANSPARENT) both – edge-to-edge dark bars lines 42-45
  • authors' notes:
  • l.19-28: declared only in src/debug/AndroidManifest.xml; no launcher entry; entry chooser starts it by class name behind BuildConfig.DEBUG so release never names the class; hosts only ExtendedCaptureScreen, so the normal capture path is untouched by construction.
  • l.34-35: old test runs are not keepsakes; clear anything older than the retention before a new sweep.
  • unused features and how to turn them on: launch by class name from a debug-only button (see manifest section).

ExtendedCaptureScreen.kt — debug-only guided capture on a 62-point reference grid (or adaptive plan), burst-sharpest shutter, AE/AWB lock, on-phone stitch, 4K rerun

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
DWELL_DEGREES 2f – aim must stay within this for the dwell (AlignmentGate threshold) line 119
DWELL_MILLIS 300L – dwell time before shutter line 120
EXTENDED_TOLERANCE_DEGREES (final on-target check, both axes) 3f – second gate before firing ExtendedGrid.kt:44, used at l.694-696
STREAM_ASPECT_RATIO 4f / 3f – FOV estimate scaled to the 4:3 stream line 127, passed at l.354
MIN_FRAMES_TO_STITCH 2 – stitch button enable + guard lines 130, 597, 1038
BURST_SHOTS 3 – stills per target; sharpest kept line 140
ANNOUNCE_SETTLE_MILLIS 600L – delay before spoken "next: …" line 149, 710
POSE_WRITE_WAIT_MILLIS 5_000L – max wait for in-flight .pose writes before stitching (poll every 50 ms, l.1275) line 158
lens CameraSelector.DEFAULT_BACK_CAMERA – which camera binds (no choice offered) line 295
capture mode CAPTURE_MODE_MAXIMIZE_QUALITY, FLASH_MODE_OFF, HIGHEST_AVAILABLE_STRATEGY, RATIO_4_3_FALLBACK_AUTO_STRATEGY – full-res untouched JPEGs lines 270, 277-287
plan choice reference grid if matchesReferenceFieldOfView(optics.fieldOfView) else SphereTargetPlan.createForFieldOfView(..., Sphere) – 62-grid vs adaptive lines 359-376
compass gate only OrientationAccuracy.Unreliable blocks; Low shows a warning – shutter blocking lines 408-413, 659-667
AE + AWB lock CONTROL_AE_LOCK=true, CONTROL_AWB_LOCK=true at Start; cleared on dispose – one exposure for the whole run lines 828, 1320-1330, 311
guidance muted default false (speaker button toggles) – beeps, dwell tick, speech line 340, 859-862
HUD "Hold still" band abs(turn) < 1.5f && abs(tilt) < 1.5f – text switches to Hold still line 1199
4K rerun PrototypeRenderer.HIGH_RESOLUTION_OUTPUT_WIDTH (4096) vs default ExtendedStitch.DEFAULT_REFERENCE_WIDTH (2048); offered only for reference grid, not while stitching, not if already ≥4096 – result-page "Make a 4K sphere" button + dialog lines 571-575, 785-794, 886-913
retake deletes the highest captured index (captured.maxOrNull()) and all its files – undo button lines 864-877
optics note refinement hard-coded true; decodeMaxDimension = max(w,h)/2 (reference) or 1024 (adaptive) – optics.txt content lines 549-554
  • authors' notes:
  • l.112-118: 2°/300 ms is the same tolerance as the normal camera: tight enough that the frame is really where the grid asked (keeps the reference stitch on planned coordinates), still holdable by hand.
  • l.122-126: the optics estimate is scaled by the 4:3 buffer aspect so the stitch is not told the frame sees more or less than it does.
  • l.132-139: 3 shots is what the reference device profile uses; past that another shot buys less than the shake it invites.
  • l.142-148: the hand-over announcement must not fire for a bearing the plan only passed through.
  • l.151-157: a frame saved just before the button press is on disk before its pose; the wait is bounded so a stuck write cannot wedge the screen.
  • l.160-182: one plan; binds the main back camera (the lens the 62 grid was proven for); a narrower lens gets an adaptive plan so the sphere still closes; shares no state with PhotoSphereCameraScreen.
  • l.215-221: an ultrawide frame is the wrong shape for the grid, so the main lens walks it without asking.
  • l.222-226 / 325-329: run directory and start yaw are rememberSaveable (start yaw as NaN, since a Bundle round-trips a float) so a recreation (call, rotation, process death) resumes the same folder.
  • l.236-241: bound lens id is kept so optics describe the lens really streaming; camera bind errors are shown so a black viewfinder is not mistaken for a frozen app.
  • l.341-344: statusLine is log-only; HUD shows only a count, a direction and a progress bar.
  • l.346-353: uses rememberSphereOptics because it reconciles a multi-camera's lens list against the profile; the orbit package's estimate picks the shortest focal length = the ultrawide, i.e. possibly a lens the session never bound (see OrbitFieldOfView).
  • l.362-364: plan is rebuilt once the walk is anchored and stable afterwards (lens fixed once started).
  • l.378-381: reference stitch is placed on the planned coordinates because sensor yaw drifts over a full turn; roll stays measured.
  • l.403-407: an uncalibrated magnetometer shifts every target together (plan is anchored on the walk's own start bearing) and costs nothing; only an Unreliable fusion blocks.
  • l.434-435: one log line per target change, never the 50 Hz attitude stream.
  • l.447-454: the whole burst runs in one main-thread coroutine; each shot's pose is read from live sensor state at its own shutter.
  • l.481-490: leaving mid-burst is a cancellation, not a failure; a failed half-burst is deleted so the dir keeps one file per target.
  • l.618-619 / 774-778: a 4K rerun / "Take another" deletes the replaced cached sphere so the cache does not keep both.
  • l.639-642: shutter skipped while compass is unreliable; distance still reported so the reticle keeps helping during recalibration.
  • l.678-689: beep cadence = distance; halfway dwell tick is "felt rather than seen".
  • l.701-704: first target is not announced (it sits where the user already faces).
  • l.825-827 / 1304-1318: AE+AWB lock because per-frame auto exposure leaves a brightness step at every ownership border = a fan of light/dark wedges on a flat ceiling; returns null (no lock) if the camera is not camera2-backed.
  • l.829-831: past bug pattern: .format on the second literal of a concatenation binds only to that half and misaligns arguments, so the whole string is parenthesised first.
  • l.892-894: dialog text: the 4096-wide rerun needs a lot more RAM and more than 5 minutes.
  • l.917-924 / 1185-1191: HUD deliberately mirrors the normal capture HUD; no coordinates/plan names/lens numbers on screen.
  • l.1242-1248: spoken phrase uses the forward projection so "behind you" and "above you" compose as a listener expects; same phrasing as the normal path.
  • Observation: StartOverlay KDoc (l.1128) says "the lens choice", but no lens choice is shown (stale since lens is auto-picked).
  • unused features and how to turn them on: whole screen (reachable only via the activity, see manifest section). The PanoramaResultScreen(onHighResRerun, highResRerunLabel) parameters in our main (PanoramaResultScreen.kt:156-157) exist only for this screen.

ExtendedGrid.kt — the 62-target reference grid (5 rows x 10 + 2 caps x 6) and its on-target / turn / tilt helpers

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
EXTENDED_TOLERANCE_DEGREES 3f – yaw AND pitch on-target window line 44
row pitches (negative = up) TOP -45f, HIGH -20f, LEVEL 0f, LOW 20f, BOTTOM 45f – ring elevations lines 47-51
cap pitches ZENITH -75f, NADIR 75f – pole caps lines 54-55
RING_COUNT 10 (36° apart) – bearings per row line 58
CAP_COUNT 6 – bearings per cap line 61
CAP_PITCH_DEGREES 60f – isCap() threshold line 64
walk order LEVEL, HIGH, LOW, TOP, BOTTOM, ZENITH, NADIR – order of rings lines 70-78
reference frame FOV 49f x 63f – frame the grid was proven at lines 134-135
REFERENCE_FOV_BAND 0.15f (±15% → H 41.65-56.35°, V 53.55-72.45°) – when the grid is used instead of the adaptive plan line 138
  • authors' notes:
  • l.10-25: app side of tools/pano_proto/out/virtual_stairs/coords.json: same 62 (yaw,pitch), same 49x63 FOV, same sign convention; tools/scratch/verify_reference_coords.py asserts equality; the Python side (virtual_frames_stairs.py) closed the loop against the source panorama to 1.8/255 with no structural defects.
  • l.27-32: plan is a SphereTargetPlan so overlay, target selection and progress readout speak the normal path's language; a different lens walks the adaptive plan.
  • l.34-39: walk order is not the Python cut order (Python starts rows at -45° and caps at nadir); frame NN ≠ vframe NN, harmless for the stitch because each frame is placed by its own pose sidecar.
  • l.80-87: target bearings are absolute (anchored on the start bearing); pose sidecars stay relative to the same start, which lets the stitch put the start bearing mid-sphere.
  • l.140-149: 36° ring spacing leaves room in a 49° frame and none in a narrower one; a lens that sees less falls back to the adaptive plan to avoid non-overlapping frames.
  • unused features and how to turn them on: n/a (used by ExtendedCaptureScreen). Regression check: upstream testDebug/.../ExtendedGridTest.kt.

ExtendedBurst.kt — fires N stills per target, keeps the sharpest; tap-to-focus helper

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
shots caller passes BURST_SHOTS = 3 – burst length ExtendedCaptureScreen.kt:140,470
winner pick SharpnessSelection.sharpestIndex(files), falls back to index 0 on error – which candidate is kept line 74
candidate name extended_NN_tK.jpg → renamed to extended_NN.jpg – on-disk layout lines 65, 76-79; ExtendedStore.kt:79,87
focus action FocusMeteringAction.FLAG_AF at tapped point – tap-to-focus (AF only, not AE/AWB) lines 150-152
  • authors' notes:
  • l.33-41: a frame blurred by handheld shake is a soft patch or an unusable match; the extended walk wants the normal path's keep-the-sharpest behaviour so the plan is judged on real (not soft) frames.
  • l.43-46: candidates never survive; the directory holds exactly one file per target so sidecar naming does not change.
  • l.48-50: poseAt is called right before each shot; a full-res burst is long enough that the phone moves, so the winner's pose is the one at its own shutter.
  • l.71-72: scoring decodes every candidate; kept off the main thread.
  • l.111-116: promote falls back to copy+delete when rename is refused (different mount, file still open) so a winner is never lost.
  • l.128-137: tap-to-focus: after the trigger in AF_MODE_AUTO the lens stays put until another trigger, keeping all frames on one focal plane (a hunting lens defeats feature matching).
  • l.156-157: a failed focus sweep is not worth failing the session.
  • Observation: the builder does not call disableAutoCancel() / setAutoCancelDuration, so CameraX's default auto-cancel applies (its effect on the "lens stays put" claim is unverified).
  • unused features and how to turn them on: n/a.

ExtendedStitch.kt — on-phone stitch of an extended run: Reference (planned poses + refine + PrototypeRenderer) or Adaptive (production stitcher)

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
Mode Reference / Adaptive (chosen by screen from FOV match) – which pipeline lines 58-64
DEFAULT_REFERENCE_WIDTH 2048 – first reference stitch width line 394
MAX_INPUT_DIMENSION 1024 (profile default is 2000) – adaptive decode long edge line 387, 299
REFINE_LONG_EDGE 640 – decode size for reference pose refinement line 407
REFERENCE_PIVOT PivotModel(leverArmMeters = 0.35f, sceneDistanceMeters = 3.5f) – reference-run parallax pivot line 372
adaptive pivot SphereDeviceProfile.forDevice(context).pivot (assumes scene at 10 m) – adaptive-run pivot lines 356-361
adaptive stitch args useRefinement = true, seamMode = SeamMode.WinnerTakeAll, longitudeSpanDegrees = 360f, centerLongitudeDegrees = 0f, latitudeSpanDegrees = 180f, centerLatitudeDegrees = 0f, maxOutputWidth = profile.stitchMaxOutputWidth, unsharpAmount = profile.unsharpAmount – production-equivalent render lines 294-314
refine intrinsics distortion = null (pinhole) – must match pinhole renderer line 211
raw copy reference_raw.jpg beside the run – byte-compare file line 410
result diagnostics forced null – result screen shows no debug readout line 121
  • authors' notes:
  • l.30-46: Reference keeps the script's pure-geometry pipeline: no lens distortion correction, no sharpening, no hole filling, script output width, half-size decode; only warping and seam blending are the app's. Adaptive pairs the production plan with refinement because measuring without the refiner tests a combination production never runs.
  • l.48-51: pose comes only from the .pose sidecar; frames are written untouched so there is no EXIF comment fallback; a frame without a sidecar is left out, not guessed.
  • l.69-77: planned poses replace drifting sensor yaw/pitch for Reference only, measured roll kept; onProgress arrives on the stitch thread and must be posted to main.
  • l.129-137: Reference renders through PrototypeRenderer one frame at a time so 62 frames need not fit in memory; raw copy is OpenCV-encoded (q95, no metadata) for byte-comparison against stairs_perfect.jpg.
  • l.171-186: a grid target is where the walker was asked to point; the dwell allows a few degrees, which at 4096 px is a visible double edge; production PoseRefiner is seeded with the planned coordinates; any read/match failure falls back to the planned poses ("still a closed grid, just without the last fraction of a degree").
  • l.202-205: refine against a pinhole model too; a distortion correction here would be undone by the renderer and rotate frames back out of alignment.
  • l.257-261: roll is left alone: the grid says nothing about it and the sensor measures it well.
  • l.307-310: sidecar yaw is relative to walk start, so 0 = start bearing lands mid-photo as every 360 viewer expects.
  • l.317-321: a wrong pose is worse than a missing frame.
  • l.346-354 / 363-371: 3.5 m is what the prototype used and what a room actually is; production's HandheldBodySwivel assumes 10 m and may under-correct a close scene because the refiner absorbs it.
  • l.374-386: 1024 because the stitcher holds all frames: 62 frames at the profile's 2000 ≈ 560 MB of pixels vs ≈ 140 MB at 1024, no visible gain (10 frames/ring still carry ≈ 7500 px around 360° into a ≈ 5500 px canvas).
  • l.401-406: 640 because ORB only needs enough pixels to recognise an overlap; keeps 62 decoded frames inside the debug heap.
  • l.396 / FRAME_NAME regex: burst scratch files must never be stitched.
  • Observation: outputWidth is ignored in Adaptive mode (only Reference passes it to the renderer).
  • unused features and how to turn them on: n/a.

ExtendedStore.kt — on-disk layout of extended runs: dirs, frame/pose/burst names, optics note, retention sweep

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none (KDoc still quotes upstream's package path)
  • levers:
lever value OURS value THEIRS if different what it controls how to change
CAPTURE_DIRECTORY "extended_capture" under getExternalFilesDir(null) (falls back to filesDir) – where runs live lines 35, 54, 70
run dir name run_yyyyMMdd_HHmmss – one dir per sweep lines 69-71
RETENTION_MILLIS 3_600_000L (1 hour) – runs older than this (by newest file) deleted on activity start line 44
frame / pose / burst names extended_%02d.jpg, extended_%02d.pose, extended_%02d_t%d.jpg – file naming (2-digit index) lines 79, 83, 87
pose text format yaw=%.3f;pitch=%.3f;roll=%.3f (Locale.US) – sidecar format, same as app's EXIF stamp lines 143-150
optics note optics.txt with frames, frame_width/height, portrait, width/height_axis_fov_degrees, pivot_lever_m, pivot_scene_m, decode_max_dimension, refinement, plan, lens + replay command – offline replay with stitch_closed.py lines 128, 206-259
adb pull path ours: /sdcard/Android/data/in.propertywalk.property_walk/files/extended_capture (derived from host appId) theirs (as in KDoc): /sdcard/Android/data/theclumsypirate.com.photosphere.github.debug/files/extended_capture pulling runs KDoc l.19-21 (stale for us)
  • authors' notes:
  • l.16-21: external files dir so adb pull works on a debug build without root.
  • l.23-28: pose goes to a sidecar, not EXIF, on purpose: ExifInterface.saveAttributes rewrites the file, and these frames must stay byte-for-byte as CameraX wrote them; tools/pano_proto/stitch_closed.py reads the sidecar first, falls back to EXIF comment.
  • l.37-43: these frames are outside the picture cache the app wipes on a dead run, so without the sweep they would gather forever.
  • l.47-52: a run is judged by its newest file, so a run being written is never swept.
  • l.98-105: the directory is the truth about progress (survives recreation); burst scratch files are not counted.
  • l.156-166: frame size must be the upright (EXIF-rotated) one, or the offline resize to half --fw x --fh shears a portrait frame CameraX left landscape; same tag the Kotlin stitcher applies via portraitRotationDegrees.
  • l.186-205: the offline stitcher's 49x63 defaults belong to the virtual set, not to any phone lens, so a real run must carry its own FOV (already in display axes → --hfov/--vfov as-is); pivot recorded so the replay matches; decode size is a deliberate step down from production; refinement/plan/lens make a run self-describing weeks later.
  • unused features and how to turn them on: n/a.

PrototypeRenderer.kt — Kotlin port of tools/pano_proto/stitch_closed.py: pinhole + pivot warp, winner-takes-all, border cross-fade, Telea inpaint

  • status: debug-only; unreachable in our app
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
DEFAULT_OUTPUT_WIDTH 2048 (height = width/2) – canvas width line 60, 118-119
HIGH_RESOLUTION_OUTPUT_WIDTH 4096 – 4K rerun width (matches stairs_perfect.jpg) line 68
FEATHER_PIXELS 80, capped at fw / 8 – linear edge ramp of frame weight lines 69, 154
LEVER_METERS / SCENE_METERS 0.35 / 3.5 – pivot warp defaults (caller passes the pivot) lines 70-71, 105-106
ALT_MIN_WEIGHT 0.05f – min weight of the second frame in a cross-fade line 74
AGREE_DIFF 12.0 (mean abs per channel) – blend only where frames agree, else keep hard edge line 77
cross-fade zone 9x9 (±4 px) around each border pixel, 50/50 blend, ascending owner order – seam softening lines 480-483, 526-530
FILL_DILATE 41 px – near-coverage zone eligible for inpainting line 80
INPAINT_RADIUS 21.0 (INPAINT_TELEA) – hole fill line 81, 662
SPHERE_JPEG_QUALITY 95 – raw OpenCV copy quality line 84
inside test z > 0.02 and pixel inside frame – which canvas pixels a frame can paint line 354
decode half size (fw/2, fh/2) with INTER_AREA; remap INTER_LINEAR, BORDER_CONSTANT – sampling lines 593, 596-606, 760-762
  • authors' notes:
  • l.28-50: exists because production resolves overlaps with multi-band blending and the prototype does not; every op is an OpenCV call with the script's parameters and OpenCV decodes the JPEG, so the input pixels equal the script's.
  • l.52-56: frames streamed twice (winner pass, border pass); only running winner + second best per pixel kept, then each frame's border pixels — that is what keeps a 62-frame grid at 4096 inside a phone budget.
  • l.160-163: only the second-best index/weight is kept, not a second image.
  • l.265-271: warp formula adj = SCENE*dir - LEVER*fwd, normalised; z = adj·fwd; outside if z <= 0.02 or off frame.
  • l.364-377: the script blends per owner inside a 9x9 zone, owners in ascending order, so junction pixels blend more than once; accumulating in float and truncating only at the end is what makes the bytes match.
  • l.442: the script only iterates owners that own a border pixel.
  • l.496-497: only border pixels are ever blended; everything else stays the winner's bytes.
  • l.543: clamp-then-truncate mirrors np.clip(...).astype(uint8).
  • l.746-748: image stays BGR to imwrite, as in the script.
  • l.769-773: EXIF 274 values 3/6/8 → 180 / CW / CCW; flips are not applied (the script does not either).
  • unused features and how to turn them on: n/a.

OrbitPlan.kt (src/main/orbit) — pure-logic orbit walk plan: evenly spaced bearings, on-target, shortest turn, angle wrap

  • status: shipped-off (compiled in our main, no caller in our build; only users are upstream orbit-disabled/* and test/.../OrbitPlanTest.kt)
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
toleranceDegrees 6f (default param) – on-target window line 17
DEFAULT_ANGLE_COUNT 12 – angles per orbit line 50
allowed count 3..36 (require) – guard line 34
  • authors' notes: l.6-13: orbit = photographer circles the subject from evenly spaced compass bearings (outside-in, opposite of a photo sphere); pure logic, the screen feeds live yaw.
  • unused features and how to turn them on: only meaningful with the orbit screens (see orbit-disabled).

OrbitStore.kt (src/main/orbit) — where orbit walk photos live (cache/orbit_walks/walk_/orbit_NN.jpg)

  • status: shipped-on only for the constant: WALKS_DIRECTORY is used by SphereImageStore.kt:209 (pruneExpiredPhotos) and :580 (cache clear), which sweep a folder our app never creates. newWalkDirectory / angleFile / pruneWalks have no caller in our build.
  • our changes vs theirs: none
  • levers:
lever value OURS value THEIRS if different what it controls how to change
WALKS_DIRECTORY "orbit_walks" under cacheDir – orbit cache root line 22
walk dir name walk_yyyyMMdd_HHmmss – one per walk lines 26-27
angle file orbit_%02d.jpg – per-angle file line 36
  • authors' notes: l.10-18: cache dir (intermediate data like sphere sessions); only gallery saves leave the app; a new walk deletes the previous one; abandoned walks cleared on demand — "a dozen full-resolution JPEGs each, never left to pile up".
  • unused features and how to turn them on: see orbit-disabled.

orbit-disabled (upstream only, app/orbit-disabled/, theirs line numbers) — common facts

  • status for all 18: not compiled upstream (directory outside every source set; app/build.gradle.kts:100-132 theirs, plus belt-and-braces kotlin.exclude for OrbitMediaPipeAnalyzer.kt / OrbitCaptureScreen.kt at :128-129) and absent from our tree.
  • upstream restore recipe (theirs app/build.gradle.kts:119-123): move files back to src/main/java/com/n30dyn4m1c/photosphere/orbit/, delete the two excludes, re-add com.google.mediapipe:tasks-vision:0.10.14, restore the orbit entry in MainActivity.
  • extra blockers found (not in the recipe): OrbitCaptureScreen.kt imports com.n30dyn4m1c.photosphere.camera.rememberCaptureFeedback, which does not exist in upstream (or our) main → it would not compile as-is; the MediaPipe model asset pose_landmarker_lite.task is not in the repo (no .task file anywhere) → the analyzer would init-fail and stay inert; in our tree there is no registered MainActivity, so a new launch point is needed.
  • authors' notes (build script, theirs l.108-117): do not put a file glob in that Kotlin block comment (slash-star opens a nested comment and breaks the build script); the excludes alone did not keep the files out (AGP ignored them, build failed on missing mediapipe imports) — the move to orbit-disabled/ is what works; excludes stay so the two rules cannot drift; MediaPipe was dropped because it adds several MB of APK for an unshipped feature (theirs l.165-168).
  • strings the orbit code needs already exist in our src/main/res/values/strings.xml:68-71 (orbit_finish "Done", orbit_tap_subject, orbit_subject_locked, orbit_confirm).

OrbitCaptureScreen.kt — walk-around capture of a tapped subject on a multi-ring pitch grid with dwell shutter, voice, beeps, phase/sector loop proof

  • status: not compiled (orbit-disabled); excluded explicitly too
  • our changes vs theirs: not vendored
  • levers:
lever value OURS value THEIRS if different what it controls how to change
ORBIT_DWELL_DEGREES n/a 4f dwell threshold l.696
ORBIT_DWELL_MILLIS n/a 500L dwell time l.697
VOICE_SETTLE_MILLIS n/a 600L delay before per-target voice l.698
angleCount param n/a default DEFAULT_ANGLE_COUNT (12) — unused in the body nothing l.97
plan n/a orbitPitchPlanForFieldOfView(lensFov) else fixed orbitPitchPlan() (38 targets) grid l.584-585
trusted-reading gate n/a matchScore >= 0.3f once locked ignores passers-by l.389-391
loop proof n/a person: 4 phases seen; object: 12 sectors of 30° early Finish unlock l.429, 448
phase snap bearings n/a FRONT 0, SIDE_LEFT -90, SIDE_RIGHT 90, BACK ±180 jump active target on new body side l.407-412
guidance n/a guidanceEnabled default true beeps/voice l.351
capture n/a CAPTURE_MODE_MAXIMIZE_QUALITY, FLASH_MODE_OFF, analysis STRATEGY_KEEP_ONLY_LATEST camera setup l.183-192
exposure n/a live EV slider via setExposureCompensationIndex brightness l.371-374, 646-649
  • authors' notes:
  • l.80-87: two phases: tap the subject (lens meters on it, walk starts from the bearing faced), then walk the grid; self-contained, nothing outside orbit modified.
  • l.128-131 / 576-578: no compass anywhere: bearings are relative to walk start (yaw 0 = bearing faced at Confirm).
  • l.136-138: phase snap so BACK actually means the back targets.
  • l.156-158: subject guidance via MediaPipe pose; whole screen is debug-only via the MainActivity entry.
  • l.228-229 / 541-542: tap only locks the subject; Confirm starts the walk so the choice is deliberate.
  • l.230: comment says "Same dwell as the normal camera: inside 2 degrees for 300 ms" but the constants are 4°/500 ms (stale comment).
  • l.256-257: the "AHA" moment: lens, square and voice all lock on the subject before the walk.
  • l.282-283: same EXIF pose stamp as the main camera so the stitcher places each angle without re-shoot.
  • l.363-365 / 450-452: walk cannot end on frames alone; full grid auto-finishes; loop proof unlocks manual Finish early but never traps the walk when a phase or cap will not register in bad light.
  • l.367: system back abandons the walk ("half a circle is not a product").
  • l.387-388: once locked, a passer-by with a different body size must not flip phases or hints.
  • l.393-395: person mode proves the circle from seen body phases; object mode from swept yaw sectors (objects have no facing).
  • l.611-614: Finish needs a proven full circle; a complete grid always qualifies.
  • Observation: KDoc says "36 point pitch grid" (l.82, 131) but orbitPitchPlan() builds 38 (12+8+8+4+4+1+1).
  • Observation: the EXIF stamp reads orientation in onImageSaved (l.284-286), i.e. after the save, and stamps absolute yaw, not walk-relative yawRel.
  • unused features and how to turn them on: see common facts; plus provide rememberCaptureFeedback (or drop the shutter-sound line) and ship the .task model asset.

OrbitDepthHold.kt — depth-estimator interface (no-op default) and a 1.5 m ± 0.3 m radius hint

  • status: not compiled; nothing references OrbitRadiusHold or OrbitNoopDepthEstimator even inside orbit-disabled
  • our changes vs theirs: not vendored
  • levers: OrbitRadiusHold.targetMeters = 1.5f, toleranceMeters = 0.3f (theirs l.53-54); hints "Step closer" / "Step back" / "Good distance" / "Distance unknown" (l.63-67).
  • authors' notes: l.6-7: a MiDaS-style monocular depth model could implement this later; l.28: no-op is the default until a real model is wired.
  • unused features and how to turn them on: implement OrbitDepthEstimator and call OrbitRadiusHold.hint() from the capture screen (not wired anywhere).

OrbitFieldOfView.kt — lens FOV from Camera2 (shortest focal length) and an adaptive pitch grid sized to it

  • status: not compiled
  • our changes vs theirs: not vendored
  • levers: plan safety 0.9f on both FOVs (theirs l.63-64), overlap = 0.35f (l.65), ring cap min(75f, max(step, 90 - vPlanned/2 + step/2)) (l.67), plus zenith (-90) and nadir (90) single-target rings (l.83-84), tolerances 4f/4f (l.86).
  • authors' notes: l.15-18: same physics as the normal camera, re-implemented so orbit never touches normal-camera files; null → fixed grid fallback (KDoc says "36 target", actual fixed grid is 38); l.31-32: picks the shortest focal length; l.56-60: vertical neighbours share a third of the frame, outer ring reaches past the poles, ~6 per ring on a ~100° ultrawide.
  • Known flaw (flagged in our ExtendedCaptureScreen.kt:350-353): on a logical multi-camera the shortest focal length is the ultrawide, so this can describe a lens the session never bound.
  • unused features and how to turn them on: n/a beyond the orbit restore.

OrbitFlowOdometry.kt — median horizontal optical-flow shift of background corners (person pixels masked out)

  • status: not compiled; unreferenced
  • our changes vs theirs: not vendored
  • levers: minTrackedPoints = 10 (theirs l.30), maxCorners = 200 (l.35), goodFeaturesToTrack quality 0.01, min distance 10.0 (l.73-74), mask threshold 1.0 inverted (l.66).
  • authors' notes: l.15-21: caller converts pixels to angle; subject stays centred so its pixels are excluded to avoid biasing motion; inputs borrowed, internal Mats released; l.40-41: stateless, reset() kept for API symmetry.
  • unused features and how to turn them on: not wired; would need a frame feed (ImageAnalysis) and a pixel→degree conversion.

OrbitGuidance.kt — "Angle N of M. Next: to your left/right" voice/hint lines for the single-ring OrbitPlan

  • status: not compiled; unreferenced (OrbitCaptureScreen uses its own orbitVoiceFor/orbitHintFor)
  • our changes vs theirs: not vendored
  • levers: none (direction suppressed when on target via OrbitPlan.toleranceDegrees 6°).
  • authors' notes: l.7-11: same words as the sphere capture, with the angle position prepended.
  • unused features and how to turn them on: belongs to the older single-ring orbit UI; not wired.

OrbitHud.kt — orbit copy of the capture HUD: scrims, undo, guidance toggle, progress pill, hint card, EV slider, save-frames, Finish, Restart

  • status: not compiled; used only by OrbitCaptureScreen
  • our changes vs theirs: not vendored
  • levers: scrim heights 200 dp portrait / 120 dp landscape top, 260 dp / 120 dp bottom (theirs l.103, 111-113); progress animation 420 ms FastOutSlowIn (l.283); hint crossfade 220 ms (l.377); Restart shown only when isComplete (l.252); EV slider steps last - first - 1 (l.418).
  • authors' notes: l.65-71: same visuals/motion as capture HUD; counts are angles shot, Finish ends early with a partial set, Restart clears; l.391: exposure row is the capture row minus the AE lock.
  • unused features and how to turn them on: n/a.

OrbitHybridTracker.kt — absolute yaw from rotation vector, anchored relative tracker, gyro+vision hybrid yaw engine

  • status: not compiled; unreferenced
  • our changes vs theirs: not vendored
  • levers: HybridOrbitEngine.anchorGain = 1f (theirs l.70; 1 = snap, <1 = ease; require 0..1 at l.94).
  • authors' notes: l.26-29: relative tracker is drift-free over short windows but absolute, so it jumps if the sensor re-bases its frame; l.62-65: gyro path smooth but drifts; vision anchors (e.g. FRONT phase) snap back to truth.
  • unused features and how to turn them on: not wired.

OrbitKeyframes.kt — ORB descriptor history for loop-closure detection (Hamming kNN + Lowe ratio)

  • status: not compiled; unreferenced
  • our changes vs theirs: not vendored
  • levers: MAX_KEYFRAMES = 16 (theirs l.35), LOWE_RATIO = 0.75f (l.38), minGoodMatches = 15 default (l.73).
  • authors' notes: l.11-13: pure logic, descriptors cloned and history capped; oldest dropped and released first (l.44-45).
  • unused features and how to turn them on: not wired; needs an ORB extractor feeding descriptors.

OrbitMediaPipeAnalyzer.kt — CameraX analyzer running MediaPipe pose landmarker (live stream) → body centre, height, facing phase

  • status: not compiled; additionally excluded by name (theirs build.gradle.kts:128); dependency removed
  • our changes vs theirs: not vendored
  • levers: MODEL_ASSET_PATH = "pose_landmarker_lite.task" (theirs l.37; file not present in repo), VISIBILITY_THRESHOLD = 0.5f (l.40, also used as detection/presence/tracking confidence l.100-102), setNumPoses(1) (l.99), landmarks nose 0 / ears 7, 8 / shoulders 11, 12 / ankles 27, 28 (l.43-61), SHOULDER_BACK_MIN_WIDTH_FRAC = 0.15f (l.64), YUV→JPEG quality 90 (l.290).
  • authors' notes: l.24: "Not bound to any screen yet and inert until wired" (stale: OrbitCaptureScreen binds it at l.189); l.84-87: landmarker created lazily on the CameraX worker so the ~1 s native load never freezes the UI; l.133: always closes the ImageProxy; l.186-187: world landmarks unused; l.235-238: both ears + nose = front, one ear = that side, no face but wide shoulders = back, else unknown rather than a guess; l.271-274: YUV packed to NV21 row by row honouring strides — assuming tight packing skews the image on lenses with row padding.
  • unused features and how to turn them on: see common facts (dependency + asset + un-exclude).

OrbitPitchPlan.kt — default multi-ring orbit grid (12/8/8/4/4 + zenith + nadir = 38) and its helpers

  • status: not compiled
  • our changes vs theirs: not vendored
  • levers: ring pitches HIGH -30f, LEVEL 0f, LOW 30f, TOP -60f, BOTTOM 60f, ZENITH -90f, NADIR 90f (theirs l.64-79); counts 12 / 8 / 8 / 4 / 4 (l.71-75); tolerances 4f/4f (l.34-35, 92); ringTargets count 1..36 (l.103).
  • authors' notes: l.22-26: yaw is relative to walk start, not compass; sensor convention negative = up (l.63); l.81: "default 38 target grid" (other files say 36).
  • unused features and how to turn them on: n/a.

OrbitProjectedTargets.kt — draws pitch-grid targets on the preview relative to the live aim

  • status: not compiled; used by OrbitCaptureScreen
  • our changes vs theirs: not vendored
  • levers: PROJECTED_HALF_HFOV = 30f, PROJECTED_HALF_VFOV = 22.5f defaults (theirs l.92, 95; screen passes lens FOV/2 when known); cull beyond ±1.2 of half-view (l.54); dot radii captured 5 dp, active ring 14 dp stroke 4 dp + fill (5 + 9*dwell) dp, todo 6 dp stroke 1.5 dp, alpha 0.32 (l.62-85).
  • authors' notes: l.16-21: placed like the normal camera projects sphere targets (green captured, amber active, grey todo); KDoc mentions an off-screen chevron that this file does not draw; l.43-44: colours from theme so Material You applies; l.55-56: sensor pitch negative up puts above-horizon targets above centre.
  • unused features and how to turn them on: n/a.

OrbitReticleOverlay.kt — centre reticle with dwell arc + edge chevron, and a single-ring bearing dot strip (OrbitTargetsOverlay)

  • status: not compiled; both composables unreferenced (OrbitCaptureScreen uses FocusReticleOverlay + OrbitProjectedTargets)
  • our changes vs theirs: not vendored
  • levers: ORBIT_RETICLE_RADIUS_FRACTION = 0.16f (theirs l.132), ORBIT_HFOV_DEGREES = 60f (l.133), chevron 14 dp, margin 24 dp (l.91, 109).
  • authors' notes: l.23-31: copied from the sphere capture screen (ring warms white→green inside threshold, dwell arc, chevron when far); l.135-141: bearings outside the view have no dot, the chevron points to them.
  • unused features and how to turn them on: belongs to the older single-ring orbit UI.

OrbitRingUi.kt — circular progress ring of N dots (captured / active pulsing / todo)

  • status: not compiled; unreferenced
  • our changes vs theirs: not vendored
  • levers: ORBIT_RING_RADIUS_FRACTION = 0.30f (theirs l.94), pulse 900 ms reverse (l.42-43), starts at top (-90°) clockwise (l.48).
  • authors' notes: l.51-52: theme colours so Material You applies.
  • unused features and how to turn them on: not wired.

OrbitStitch.kt — stitches an orbit walk with the main stitcher (EXIF poses, else even horizon ring)

  • status: not compiled; used by OrbitViewerScreen
  • our changes vs theirs: not vendored
  • levers: HFOV_DEGREES = 62f, VFOV_DEGREES = 48f fixed (theirs l.99-100; ignores the real lens FOV); fallback ring step hfov * 0.65f (l.86); pose regex yaw=..;pitch=..;roll=.. from EXIF UserComment (l.76, 96-97).
  • authors' notes: l.23-26: honest limitation: the stitcher models rotation from one spot while a walk translates around the subject, so close subjects show parallax seams no blend can hide; result is still one continuous turntable photo.
  • unused features and how to turn them on: n/a beyond the orbit restore.

OrbitSubject.kt — data: OrbitPhase enum (FRONT, SIDE_LEFT, SIDE_RIGHT, BACK, UNKNOWN) and OrbitSubjectReading

  • status: not compiled
  • our changes vs theirs: not vendored
  • levers: none
  • authors' notes: l.19: body height = nose to ankle-midpoint as a fraction of frame height.
  • unused features and how to turn them on: n/a.

OrbitSubjectGuidance.kt — one-line framing hint for the subject (centre, distance, phase)

  • status: not compiled; used by OrbitCaptureScreen
  • our changes vs theirs: not vendored
  • levers: CENTER_TOLERANCE = 0.12f, CENTER = 0.5f (theirs l.3-4).
  • authors' notes: l.9-10: priority UNKNOWN → vertical offset → horizontal offset → distance → phase.
  • unused features and how to turn them on: n/a.

OrbitSubjectLock.kt — locks a subject's body height/centre at tap time; match score and too-close/too-far hint

  • status: not compiled; used by OrbitCaptureScreen
  • our changes vs theirs: not vendored
  • levers: distance band ratio > 1.2f TOO_CLOSE, < 0.8f TOO_FAR (theirs l.95-96, "20 percent tolerance" l.83); match score 1 - |h - locked| / locked clamped 0..1 (l.76-77).
  • authors' notes: l.24-27: used to pick the same person across frames; l.84: larger body = closer.
  • unused features and how to turn them on: n/a.

OrbitViewerScreen.kt — swipe through the walk's angles; Stitch 360, Save all, New walk

  • status: not compiled; unreferenced (upstream MainActivity orbit entry removed)
  • our changes vs theirs: not vendored
  • levers: MAX_PREVIEW_EDGE = 1600 (theirs l.216), power-of-two inSampleSize decode (l.193-196).
  • authors' notes: l.47-54: drag side to side to turn the subject; "Stitch 360" uses the main pipeline; l.186-187: screen-size bitmap, never the full 50 MP; l.73: system back returns to the camera.
  • unused features and how to turn them on: n/a beyond the orbit restore.

test/ + testDebug/ (upstream only) — unit tests usable as regression checks for levers

  • status: not vendored in our tree (exist only upstream under app/src/test and app/src/testDebug); they target the same com.n30dyn4m1c.photosphere packages, so copying them into photosphere/src/test would be the way to use them (unverified that they compile against our modified main).
  • note: test/.../StairsVirtualGridTest.kt:137 loads virtual_stairs_coords.json, which lives only in testDebug/resources/, so it has its data only in the debug unit-test variant.
  • files (one line each, from test names):
  • PermissionGateTest.kt — camera-permission dialog outcomes: cancel vs grant vs rationale vs permanent denial.
  • camera/AlignmentGateTest.kt — dwell gate fires once after the hold, resets on leaving, and pins the shipped defaults (2°/300 ms) the capture flow promises.
  • camera/CameraOpticsTest.kt — main lens chosen over ultrawide on multi-camera, calibration sanity, FOV crop for 4:3 vs widescreen streams.
  • camera/GuidanceProfileTest.kt — beep cadence vs distance (bounded, silent beyond cone), halfway dwell tick, spoken target relations.
  • camera/OrientationSmootherTest.kt — marker smoothing: converges, snaps on fast pans, yaw-wrap short way, rejects magnetometer-only spikes.
  • camera/SharpnessSelectionTest.kt — sharpness score: edges > flat, flat = 0 whatever brightness, tiny frames treated flat.
  • camera/SphereCaptureCoordinatorTest.kt — capture state machine: plan laid once, shutter/undo/restart races, unreliable-sensor block, exposure-lock wait, dwell-sample pose averaging.
  • camera/SphereCaptureProfileTest.kt — focus mode per lens (tap-to-focus vs fixed), lock/OIS defaults, sane default device profile.
  • camera/SphereProjectionTest.kt — target-to-screen projection: centre, left/right/up, roll, behind-camera, edge at one FOV.
  • camera/SphereTargetPlanTest.kt — adaptive plan: rings inside ±60 band, thinning to poles, serpentine order, FOV scaling, ring vs sphere scope.
  • camera/TargetSelectionTest.kt — active-target hand-over rules (hold while wandering, claim when squarely aimed, skip captured, wrap).
  • diagnostics/ReportTest.kt — report redaction of account names, emails, tokens.
  • metadata/GPanoXmpInjectorTest.kt — GPano XMP packet: properties, placement after JFIF/Exif, idempotent, ring = horizontal slice, rejects bad JPEGs.
  • orbit/OrbitPlanTest.kt — OrbitPlan: 12 angles from 0, skips captured, tolerance, shortest turn, wrap range.
  • result/PanoramaUvTest.kt — viewer UV mapping: north = middle, east/south/up/down, aspect, ring-band latitude mapping.
  • sensor/OrientationMeanTest.kt — circular mean across ±180 and zenith dwells as rotations.
  • sensor/OrientationTrackerTest.kt — angle normalisation, display-rotation axis remaps, accuracy mapping (only Unreliable refuses), negative pitch = up.
  • stitching/ExposureCompensationTest.kt — gain solve: equalises pairs/chains, neutral for unreached frames, clamps runaway gains.
  • stitching/LensModelTest.kt — radial distortion distort/undistort inverse, pixel-coefficient normalisation, zero calibration = pinhole.
  • stitching/MultibandBlenderTest.kt — pyramid level count/sizes (coarsest ≈ 8 rows), seam-wrapping footprints, band bounds.
  • stitching/PhotoSphereStitcherTest.kt — status codes, canvas width caps/evenness, latitude-span height, power-of-two subsampling, FOV transpose fix.
  • stitching/PivotModelTest.kt — pivot lever/scene ratio, clamping, referral/projection inverse, footprint shrink off-axis.
  • stitching/RotationMathTest.kt — rotation primitives, Procrustes, RANSAC with 1/3 outliers, rotation averaging, per-frame focal correction.
  • stitching/SeamFeatherTest.kt — seam feather half-weight at the cut, monotonic falloff, pyramid lookup.
  • stitching/SeamSolverTest.kt — max-flow/min-cut correctness and that the seam follows where frames agree.
  • stitching/SphericalGeometryTest.kt — camera basis, equirect mapping, footprints over poles/date line, pose-graph overlap, feather, rejects impossible FOV.
  • stitching/StairsVirtualGridTest.kt — virtual stairs grid: frame count, no duplicates, row overlap, pole caps, matches coords.json.
  • stitching/WinnerSeamsTest.kt — winner-takes-all ownership: closest-to-centre wins, ties keep first.
  • testDebug/extendedcapture/ExtendedGridTest.kt — the 62-target grid (5 rows + 2 cap sets), no gaps for its FOV, matches Python virtual_stairs_coords.json, caps near poles, ±15% FOV band.
  • testDebug/resources/virtual_stairs_coords.json — 62 reference (yaw, pitch, hfov 49, vfov 63) entries vframe_NN.jpg used by the two grid tests.
stitching: the path every capture takes

engine reference — stitching: the path every capture takes

part of the engine reference (master_doc/engine/). written 2026-11-26 by reading every file of our copy (commit 16eb526) against theirs (b5796d7), plus their docs, tests, tools and commit history. line numbers point at our code at 16eb526; the floor-photo commits after it (eff5cd1, 022767a) shift a few. levers were read from the code, not tried on the phone. start at master.md -> "if something goes wrong with the camera".

Paths. OURS = apps/mobile/android/photosphere/src/main/java/com/n30dyn4m1c/photosphere/stitching/ (line numbers below are OURS unless marked "theirs"). THEIRS = theclumsypirate-photosphere-android-b5796d7/app/src/main/.../stitching/. Diffs were taken with diff --strip-trailing-cr (every file differs on line endings only, except the edits listed). Our copy carries no unit tests; the tests quoted are theirs (app/src/test/.../stitching/).

Cross-cutting facts that matter for every file below (read once): - Shipped call = PhotoSphereCameraScreen.kt:1411 (capture finish) and Restitch.kt:107 (result-screen restitch). Capture default seamMode is WinnerTakeAll (OURS, PhotoSphereCameraScreen.kt:509); THEIRS default is SeamMode.Blend (their PhotoSphereCameraScreen.kt:453). distortionEnabled and refinementEnabled default false in both (ours :482-483). - Device profile values handed in (camera/SphereDeviceProfile.kt, out of scope): DEFAULT stitchMaxInputDimension = 2000 (OURS; THEIRS 1024), stitchMaxOutputWidth = 4096, unsharpAmount = 0f, pivot = HandheldBodySwivel; S23/S21: 2000 → 6144, unsharp 0.3. In a debug build debugTuned() replaces scene distance with DEBUG_SCENE_DISTANCE_METERS = 3.0f (SphereDeviceProfile.kt:235), so pivot ratio becomes 0.35/3.0 = 0.1167 instead of 0.035. Whether our shipped APK is a debug variant of this library module: unverified at runtime (CLAUDE.md says APKs are built --debug). - Upstream history: the LensProjection / fisheye groundwork was added in b5796d7 (the commit we vendored) and reverted in 3035b6e (2026-11-25, "Remove fisheye debug R&D UI and projection foundation… Restore default pinhole+radial stitching path"). Confirmed via gh api …/commits/3035b6e: it touched EquirectangularRenderer, LensModel (−150), SeamFinder, SphericalGeometry, PoseRefiner. Everything flagged [groundwork] below is what they removed. - Debug bench (diagnostics/DebugRestitch.kt:106-191) flips StitchTuning per variant and restores it after. Gotcha: it sets maskBehindNadir = "nadir" in flags (line 107), so any bench variant without the nadir flag runs with the holder-side rule OFF, while the phone ships it ON — bench wta ≠ phone Crisp.


PhotoSphereStitcher.kt — entry point: decode frames, fix FOV/orientation, (optional) refine, seam, render, unsharp, bitmap

  • status: shipped-on (ours edited)
  • our changes vs theirs:
  • new param bentOutput: ((Bitmap) -> Unit)? = null (L394): when set and seams != null (Crisp/Careful only, L870) frees the normal canvas (L872), runs SeamBend.solve + a second EquirectangularRenderer.render(bend = field) (L876-908), applies floor patch + unsharp, hands the bitmap out. Any Throwable incl. OOM is swallowed and logged (L927-930); normal picture unaffected.
  • new param floorShot: SphereFrame? = null (L400): decoded at L567-577 with the same no-EXIF portrait-rotation fallback as frames; after coverage checks FloorPatch.plan + FloorPatch.apply paint it into the canvas (L847-865), also reused on the bent picture (L909-917); failures logged, never fatal; released in finally (L958-959).
  • everything else byte-identical.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const MIN_FRAMES 3 UI gate for offering a stitch; history: dropped from 6 to 3 (commit "Stitch from three frames") L222; read by PhotoSphereCameraScreen.kt:1579,1749, DebugRestitch.kt:101
const MIN_STITCHABLE_FRAMES 2 below this → NeedMoreImages L225
const DEFAULT_MAX_INPUT_DIMENSION 1024 default decode long edge (callers override with profile 2000) L228 / caller maxInputDimension
const DEFAULT_MAX_OUTPUT_WIDTH 4096 default canvas width cap L231 / caller maxOutputWidth
const MIN_OUTPUT_WIDTH (private) 512 canvas never narrower L234
const MIN_COVERAGE (private) 0.002f below 0.2% covered → NeedMoreImages; history: was 2% L246
const UNSHARP_RADIUS 1.5 Gaussian sigma (output px) of unsharp mask L249
const UNSHARP_CONTENT_THRESHOLD 24.0 only pixels with grey > 24 get sharpened (gaps/night noise skipped) L252
const UNSHARP_BAND_HEIGHT 256 rows per unsharp band (memory) L255
const UNSHARP_HALO 16 context rows each side of a band L264
DEBUG_FRAME_COLORS 6 BGR Scalars colour-frames placement check palette L34-41
param radialDistortion null Brown-Conrady k1..k3; null = pinhole caller (distortionEnabled default false)
param maxInputDimension 1024 (profile passes 2000) profile passes 1024 decode size; drives canvas width L343 / SphereDeviceProfile
param maxOutputWidth 4096 canvas width cap L344
param unsharpAmount 0f (=off) out = src + amount·(src − blur) L345 / profile (0 DEFAULT, 0.3 S21/S23)
param pivot PivotModel.None lever-arm parallax model (callers pass HandheldBodySwivel) L346
param portraitRotationDegrees 90 clockwise turn applied to frames that decoded landscape with no EXIF tag L347 / optics.portraitRotationDegrees (DebugRestitch does not pass it → 90)
param useRefinement false PoseRefiner on; also the only source of exposure gains (off → all gains 1f, L609) and focal scales (off → 1.0, L612) L348; Restitch forces true for Careful
param seamMode SeamMode.Blend Blend / Carve / WinnerTakeAll L349; capture screen default WTA (ours)
param debugColorFrames false paint each frame a solid colour L350
param movingObjectSeamMask false Carve only: neutralise nodes whose covers differ > 90 RGB L356
param perBlockExposure false BlockExposure fields; also requires BuildConfig.DEBUG (L711) L362
param graphSubsetSelection false drop frames outside largest matched component; requires DEBUG (L635) and refinement to measure anything L370
param localWarpAlignment false APAP-lite meshes; requires DEBUG (L597) and refinement L377
param perceptualSeamCost false OKLab seam cost; DEBUG-gated inside SeamFinder (L314) L383
param longitudeSpanDegrees 360f canvas longitude span, require 1..360 (L406) L384
param centerLongitudeDegrees 0f canvas centre; capture passes first-shot yaw L385
param latitudeSpanDegrees 180f canvas latitude span, require 1..180 (L409) L386
param centerLatitudeDegrees 0f require -90..90 (L412) L387
param bentOutput (ours) null absent second "bent joins" picture L394; wired by capture + Restitch
param floorShot (ours) null absent floor photo patch L400; capture only (Restitch does not pass it)
enum SeamMode Blend, Carve, WinnerTakeAll overlap strategy L162-166
enum StitchStatus codes Ok 0, NeedMoreImages 1, AlignmentFailed 2, CameraEstimationFailed 3, OpenCvUnavailable 100, NoInputImages 101, UnreadableInput 102, EmptyResult 103, OutOfMemory 104, Unknown 199 failure contract L50-88
enum StitchStage Preparing, Reading, Refining, Seaming, Stitching, Projecting progress stages L98-116
canvas width rule round(lonSpan·frameW/hFOV), min(cap), ≥512, forced even from the first decoded frame only (L547) L972-981
canvas height rule round(W·latSpan/lonSpan), ≥1 square pixels L991-1001
FOV swap boundary swap when focal ratio < sqrt(transposedRatio) checked once against frame 0 (L518) L1022-1041
sampleSizeFor power of two, doubles until longest/sample ≤ max BitmapFactory subsample L1302-1308
decode config ARGB_8888 Utils.bitmapToMat accepts ARGB_8888/RGB_565 only L1245
  • authors' notes:
  • L43-49: status codes are this pipeline's own log/bug-report contract: 0–3 registration outcomes, ≥100 machinery failures.
  • L60-66: AlignmentFailed classic cause is translation (walking / pivoting round the body). In this Kotlin path AlignmentFailed and CameraEstimationFailed are never thrown (only mapped to UI strings at PhotoSphereCameraScreen.kt:2983-2984); OpenCv360Stitcher.kt has no StitchStatus refs either (grep).
  • L118-126: Reading/Refining/Seaming/Stitching report real fractions; other stages null fraction → indeterminate spinner on purpose.
  • L171-175: OpenCV's Stitcher cannot be used: no org.opencv.stitching in any prebuilt Android OpenCV; reprojection from measured poses replaces it.
  • L201-203: output is equirectangular by construction; uncaptured areas are black at the correct latitude.
  • L211-221: MIN_FRAMES=3 because poses, not match chains, place frames; more frames only buy coverage, "the user's call".
  • L236-245: MIN_COVERAGE deliberately near the floor; three narrow-lens frames reach <2% of canvas; partial captures are supported.
  • L257-263: halo exists because a band blurred without neighbours darkens at its edges → horizontal line every 256 rows.
  • L319-325: refinement default OFF: measured poses are good enough, and refinement moves frames off them when the scene has parallax (body-swivel of a close scene breaks the pure-rotation model). History (2b986e8): refinement and distortion were both defaulted off after the transpose bug fix.
  • L332-334: onProgress is called on the stitch thread, not main.
  • L403-405: span requires exist because degenerate spans drove allocation to Int.MAX_VALUE rows → confusing OOM.
  • L445-450 / L1003-1018: a swapped FOV makes the two implied focal lengths disagree by ~aspect² (0.56 for 4:3); boundary at sqrt (log-space midpoint) so genuinely asymmetric crops are not mis-swapped by an arbitrary constant.
  • L471-475: frame Mat owned by the iteration until handed to decoded; Mat.release is idempotent.
  • L477-495: rotation fallback only when EXIF tag is absent; a present NORMAL on a landscape frame is a real landscape capture and must not be rotated.
  • L536-539: radial coefficients converted against the focal length this decoded frame implies, so any subsample carries the same physical lens.
  • L584-589: the corrected FOV is passed to refinement; a transposed FOV asks the overlap question about the wrong axis (history de3ba4e fixed exactly this).
  • L603-605: refinement-off branch is a debug A/B that isolates whether a bad feature match moved frames.
  • L631-634 / L667-669: after pruning, gains are remapped to kept positions once; seam solve, block exposure, renderer all read them positionally.
  • L677-682: focal refinement scale is applied to intrinsics and radial re-normalised so footprint and renderer see the measured lens.
  • L702-704: coroutine context captured because seam finder/renderer are non-suspending.
  • L738: "A refinement that cannot run must never sink a stitch" (block exposure failure → scalar gains).
  • L941-943: OOM is caught and returned as OutOfMemory; user can retry at lower input resolution.
  • L949: native OpenCV failures arrive as CvException (RuntimeException) → Unknown.
  • L955-956: prepared and decoded share Mats; releasing decoded covers all paths.
  • L1059-1064: CameraX records rotation in EXIF instead of rotating pixels; a run crossing a screen rotation would mix portrait/landscape frames.
  • L1066-1072 (Motorola quirk): getAttributeInt cannot tell present-NORMAL from missing, so presence is read via getAttribute; a tag reading UNDEFINED (0), which some Motorola HALs write, counts as missing so the portrait fallback still applies (history: "EXIF undefined fallback").
  • L1104-1111: rotate fallback degrees = what CameraX would have recorded; 90/270 is the case actually met.
  • L1152-1159: unsharp done whole was the pipeline's memory peak (~200 MB on the 6144 profile); banded with one untouched source copy so results equal whole-canvas and no band sharpens its neighbour twice.
  • L1294-1300: BitmapFactory honours only powers of two, so the function returns one itself.
  • ours L870-872, L928: bent picture needs hard seams; normal canvas freed first; OOM in the bent pass is deliberately non-fatal.
  • what the tests pin (PhotoSphereStitcherTest): codes 0..3 for registration outcomes, ≥100 for the rest, all codes unique; canvasWidthFor(1024, 66°, cap 8192) = 5584, cap 4096 → 4096; width always even and ≥512 over frame widths 320..4000 × FOV 37/66/90/121; canvasHeightFor(4096,360,180)=2048, (4096,360,72)=819, (4096,180,180)=4096; sampleSizeFor(4000,3000,1024)=4, already-small → 1, always power of two; correctFovOrientation leaves matched portrait (750×1000, 52/66) and landscape alone, swaps transposed (750×1000, 66/52 → 52/66), ignores a ~10% FOV error (52·1.1, 66·0.95); StitchProgress fraction null without total, 11/44 = 0.25.
  • unused features and how to turn them on:
  • exposure gains / focal scales: only arrive with useRefinement = true (Careful restitch, or debug Refine toggle). Bench verdict (RESULTS.md): wta+refine worse on our captures.
  • lens distortion: radialDistortion = optics.radialDistortion (capture debug toggle distortionEnabled).
  • perBlockExposure, graphSubsetSelection, localWarpAlignment, perceptualSeamCost, movingObjectSeamMask: pass true and run a DEBUG build; graph/warp also need refinement. Bench flags block, graph, warp, oklab, mask.
  • debugColorFrames = true (bench/harness) to check placement.
  • floor patch on restitch: not wired — restitchSphere would need to pass floorShot.

EquirectangularRenderer.kt — paints frames onto the canvas through the lens model, banded multi-band pyramid, pinhole-gap fill; hosts OUR StitchTuning

  • status: shipped-on (ours edited)
  • our changes vs theirs:
  • bend: SeamBend.Field? = null threaded through render (L128) → accumulateLevel → accumulateSegment; when the frame is touched, each pixel's sampling direction is recomputed from the shifted level-0 column/row (L717-747). Null = identical to theirs.
  • "mask behind nadir" in the feather (Blend) branch only (L679-692, L822-829): a frame with forwardZ < -0.7 multiplies its feather by clamp(away / 0.15, 0.01, 1) where away = cosine between the pixel's compass bearing and the frame's up-vector bearing.
  • new object StitchTuning (L1025-1080) — process-wide switches read here, in SeamFinder, SphericalGeometry and PoseRefiner.
  • [groundwork] (present in theirs at b5796d7 too, reverted upstream in 3035b6e): intrinsics.projection.project(...) call (L767-777) and the localWarp path guarded by intrinsics.projection === PinholeLensProjection (L778); upstream post-revert inlines the pinhole + radial maths again.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const BAND_HEIGHT (private) 128 rows accumulated at once; peak memory with width L67
const FILL_MIN_COVERAGE (private) 0.95f at/above 95% coverage (and <100%) small holes are inpainted; below, black kept L497
hole dilate kernel 7×7 ellipse grows holes a few px so dark fringe blends L484
inpaint radius 8.0, INPAINT_TELEA gap fill L486
interpolation INTER_LANCZOS4 at level 0, INTER_LINEAR above sampling kernel L532-533
coarse-level source downsample INTER_AREA, size/2^level frame per pyramid level L546-553
scaleFootprint pad start −1, end +2 (rows and cols) coarse footprint never misses a border L929-932
render default params gains=null, seams=null, gainFields=null, localWarps=null, bend=null, pivotRatio=0.0, lonSpan 360, lonCentre 0, latSpan 180, latCentre 0 (no bend) L102-136
StitchTuning.tiltPenalty (var) 0.0 (OFF) absent extra cost for a tilted photo to own furniture height in WTA only; 0 = upstream L1036; bench eyelevel sets 5000.0, noeyelevel 0.0
StitchTuning.TILTED_FORWARD_Z 0.65 (~40°) absent forwardZ
StitchTuning.FURNITURE_BAND_LOW_Z / HIGH_Z −0.77 / 0.26 (~−50° .. +15°) absent direction z band treated as furniture height L1042-1043
StitchTuning.refineSift (var) false absent (ORB) PoseRefiner uses SIFT + BRUTEFORCE instead of ORB + HAMMING L1047; read PoseRefiner.kt:188,204; bench sift
StitchTuning.refineDetectLongEdge (var) 512 512 hard-coded upstream shrink size before feature detection L1051; PoseRefiner.kt:370; bench detN
StitchTuning.REFINE_SIFT_FEATURES 3000 absent SIFT feature count L1053
StitchTuning.featherPower (var) 3 3 (cube, not a switch) blend feather sharpness; ≠3 switches to exp(k·(linear−1)) L1057; bench sharpN
StitchTuning.maskBehindNadir (var) true absent Blend: weight mask above; WTA: SeamFinder.holderSidePenalty L1067; bench nadir (bench defaults it OFF, see top)
StitchTuning.HOLDER_SIDE_PENALTY 3000.0 absent WTA cost on holder's side (border costs run 0..1000) L1070
StitchTuning.DOWN_TILT_FORWARD_Z −0.7 (~45° down) absent which frames count as downward L1073
StitchTuning.BEHIND_FADE 0.15f (~9°) absent cosine range of the fade L1076
StitchTuning.HOLDER_SIDE_TRACE 0.01f absent Blend weight floor on holder's side L1079
  • authors' notes:
  • L21-23: PreparedFrame.image is CV_8UC3, owned by the builder; renderer never releases it.
  • L46-52: with SeamWeights the feather is replaced by seam weights at every pyramid level; single-coverage detail is untouched either way.
  • L54-62: a 4096 canvas needs ~100 MB float accumulator whole; banding keeps peak to tens of MB, total work unchanged.
  • L139-146: full-res 1-byte coverage mask; one scratch per render because a pole-covering frame spans the full width (allocation churn across ~40 frames).
  • L160-165 / L415-420: pyramid mats owned at outer scope so a mid-render failure releases them; levelOneAcc aliases acc on a 2-level canvas; release is idempotent.
  • L171-174: canvas shorter than the coarsest band → plain normalised mean (single level).
  • L263-271, L290-298: level bookkeeping — which coarse levels stay alive for level-1/level-0 bands.
  • L464-473: sensor poses drift a degree or two so a complete run can land at 99% with black slivers; inpaint them; under 95% keep the black — "an honest gap the user should re-shoot, not a smear".
  • L505-508: coarse levels warp a downsampled frame, so the warp lands on the level's Gaussian, not a decimated full-res copy.
  • L601-611: lon/lat factors separate, so per-column parts are computed once; feather measured on the ideal pixel (scale-invariant).
  • L653-656: longitude periodic, canvas column used directly; only forEachColumnRun decides wrap vs clip.
  • L748-752: pivot lever arm is parallel to forward → drops out of lateral/vertical, shortens depth only (one subtraction).
  • ours L679-689: downward photos see the holder on the phone's "bottom" side; first test tour (2026-11-25) had rolls of 75° and 163° because agents twist the phone in hand, so one downward photo looked straight back at the body.
  • L860-863: scratch arrays are often longer than the segment; Mat.put clamps to the Mat's element count.
  • L869-873: Lanczos on finest level keeps edge detail now that canvas ≈ frame resolution.
  • L941-952: a footprint crossing ±180° is two canvas blocks; on a region canvas (<360°) the edge is a real cut and the footprint is clipped; never more than two runs.
  • L974-986: grow-only scratch; tens of MB per band of garbage otherwise.
  • ours L1032-1035: tiltPenalty switched OFF again after 2026-11-26 01:29 bench (32-photo capture): forcing eye-level photos to their bottom edge put dark blurry edge pixels in (black smudges on bed) and cut the bed in a line; with it off and 12 photos around, bed and fridge came out whole. Note: DebugRestitch.kt:118 comment still says "eyelevel (now the default)" — stale, code default is 0.0.
  • ours L1059-1065: maskBehindNadir ON since 2026-11-26 together with the "turn your whole body" hint on floor photos; does nothing useful on captures where the phone was twisted in the hand. RESULTS.md L222-228 (older entry) recorded "no change" on a twist-in-hand capture and "stays off"; RESULTS.md L38 records the later switch ON.
  • what the tests pin (theirs MultibandBlenderTest): scaleFootprint at level 1 halves a footprint, keeps a seam-wrapping (negative) start left of zero, scale 1 is identity, coarse footprint never empty. (No renderer test on device-free JVM.)
  • unused features and how to turn them on:
  • localWarps, gainFields: via stitcher debug flags (above).
  • bent joins: bentOutput + Crisp/Careful.
  • eye-level rule: StitchTuning.tiltPenalty = 5000.0 (WTA only).
  • SIFT refinement: StitchTuning.refineSift = true (+ useRefinement).
  • fill threshold: change FILL_MIN_COVERAGE (e.g. lower to inpaint larger gaps — untested).

SphericalGeometry.kt — poses → camera bases, intrinsics, feather weight, equirect maths, footprints, pivot referral, overlap test

  • status: shipped-on (ours edited; contains [groundwork])
  • our changes vs theirs:
  • featherWeight (L375-384): if StitchTuning.featherPower != 3 return exp(k·(linear−1)) instead of linear³. At 3 identical to theirs.
  • [groundwork] (in b5796d7, reverted in 3035b6e): FrameIntrinsics.projection: LensProjection = PinholeLensProjection (L233) and maxFovDegrees: Double = 179.0 (L238); scaledBy re-wraps projection.scaledBy(...) (L288); forLens(projection, maxFovDegrees) params (L331-332, L341); footprint border walk via projection.unproject then divide by z (L629-635) instead of undistortPixel + cameraXOf/cameraYOf; projectDirection via projection.project (L724). Side effect: cameraXOf/cameraYOf (L648-652) are dead code in our copy (upstream re-uses them after the revert). Behaviour for pinhole/radial is mathematically the same either way.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const FrameFootprint.SAMPLES_PER_EDGE (private) 24 border samples per edge ("enough to catch the bulge at 70° FOV") L505
param FrameFootprint.compute(marginPx) 2 footprint padding px L520
const MIN_DEPTH 1e-6 directions shallower = behind camera L666
FrameIntrinsics.fromFieldOfView FOV range require 1..179 each axis rejects impossible FOV L307-308
FrameIntrinsics.maxFovDegrees [groundwork] 179.0 (removed post-revert) fisheye ray cut-off L238, L332
FrameIntrinsics.projection [groundwork] PinholeLensProjection (removed post-revert) lens model used everywhere L233, L331
scaledBy identity tolerance |s−1| < 1e-6 or s ≤ 0 → same instance L273
focalPx sqrt(fx·fy) single focal for the radial polynomial L256
featherWeight power 3 (cube) or exp(k·(linear−1)) via StitchTuning.featherPower cube only blend sharpness L383-387
overlapBound 2·tan(fov/2), Double.MAX_VALUE at fov ≥ 90° pose-graph overlap gate L786-787
pivotDirection discriminant floored at 0; returns input if ratio ≤ 0 pivot referral L679-700
Equirectangular sampling half-pixel centres; lon centre ± span/2; lat top = centre + span/2 canvas maths L412-461
  • authors' notes:
  • L16-19 / L38: sensor pitch is negative above the horizon; elevationDegrees = −pitch flips it.
  • L25-34: the pose carries a measured rotation matrix because Euler angles collapse at the zenith; dwell is averaged as rotations; CameraBasis.of prefers the matrix.
  • L49-50: camera triple is left-handed (up = right × forward).
  • L87-99: toRotationMatrix stores [right, −up, forward] columns because the left-handed triple is a reflection and would smuggle a 90° rotation through quaternion maths.
  • L185-192 (past bug, history 2b986e8): fromRotationMatrix must read columns (stride 3); reading rows transposed the basis and stacked every level frame on due north — the "frames in all kinds of orientation" bug.
  • L210-216: per-axis focal lengths guarantee full width ↔ full HFOV and height ↔ VFOV; one focal would turn a small FOV inconsistency into systematic gaps/overlaps.
  • L248-255: geometric-mean focal is exact for square pixels, degrades gracefully otherwise.
  • L261-271: focal scale s re-normalises radial terms k1/s², k2/s⁴, k3/s⁶ — otherwise the lens is described by one focal and corrected by another.
  • L352-362: feather measured on the ideal pixel (proportional to off-axis angle); both factors clamped before multiplying, because radial distortion can pull an outside pixel inside and two negatives make a positive weight (history de3ba4e; a single negative also subtracted colour from neighbours).
  • ours L375-382: higher sharpness = fine detail from the photo seeing it nearest its centre (near objects once, not two half-copies); exponential not a higher power because linear^16 underflows to ~1e-8 and the blender epsilon turned those areas black (bench 2026-11-26 00:17); exp never drops below exp(−k) inside the frame. Note: at the frame edge the exp form is exp(−k), then 0 just outside — a small step the cube form does not have (my reading of the code).
  • L385-386: cube by hand, Math.pow per pixel per frame is several times the cost.
  • L393-408: canvas always square pixels; frame facing north lands mid-canvas.
  • L464-473: footprint columns may be negative/past width (unwrapped seam crossing); rows never wrap.
  • L490-500 / L562-568: footprint walks the border (wide-FOV mid-edges reach higher latitude than corners); a frame containing a pole is tested directly and opens to full width, otherwise the border walk would cut it in half.
  • L536-539: border rays are referred to the pivot before reading lon/lat.
  • L688-689: pivot discriminant cannot go negative for k < 1, "the floor costs nothing".
  • L706-708: renderer inlines projectDirection; any change must be mirrored there (and in SeamFinder.sampleInto).
  • L747-761: overlap bound is 2·tan(fov/2), not tan(fov) — at 52° tan(52°) is ~31% too loose; and tan(fov) turns negative past 90°, which used to reject every pair on the ultrawide (silently disabling refinement + gains on the preferred lens; history de3ba4e).
  • what the tests pin (SphericalGeometryTest): level-north and east bases have the expected axes; negative pitch aims up; of prefers a measured matrix; orthonormal at every attitude; project/unproject inverse; canvas centre = north, edges = date line; lon/lat round-trips; col/row lookups invert sampling; ring canvas maps its band across full height; frame centre lands at the aim; behind-camera and past-FOV directions do not project; date-line frame is one unwrapped range; pole frame opens to full width; footprint never claims rows outside canvas and contains every paintable pixel; unwrap branch; column wrap from both sides; FOV → focal; basis round-trips via pose and via matrix; level frames at different yaws get different forwards (transpose regression); optical axis untouched by distortion, off-axis direction moves, barrel frame paints a wider footprint; overlap found / rejected past one FOV / directional / closer = stronger; ultra-wide (104°×120°) still builds a pose graph, 170° away rejected; feather = 1 on axis, 0 at borders, decreasing outward; outside-on-both-axes never weighted (−500,−400 and 900,700 → 0); fromFieldOfView(…180°…) throws.
  • unused features and how to turn them on: EquidistantFisheyeProjection can be selected by passing projection = EquidistantFisheyeProjection(k) and a maxFovDegrees to FrameIntrinsics.forLens — nothing in our app does (grep: no caller outside LensModel/SphericalGeometry). Note fromFieldOfView still caps FOV at 179°, and localWarp is skipped for non-pinhole projections (renderer L778).

MultibandBlender.kt — Burt–Adelson Laplacian-pyramid blend arithmetic, banded reconstruction

  • status: shipped-on (every seam mode renders through it)
  • our changes vs theirs: WEIGHT_EPSILON 1e-6 → 1e-12 (L70).
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const MAX_LEVELS 6 pyramid depth cap L60
const WEIGHT_EPSILON 1e-12 1e-6 (theirs L67) added to weight sums before division L70
coarsest level height ~8 rows (while height > 8) level count = log2(h/8) capped L96
band coarse rows [bandTop/2 − 1, (bandTop+rows)/2 + 1] clamped upsample source rows L137-138
upsample kernel INTER_LINEAR EXPAND step L263-265
  • authors' notes:
  • L15-23: a cross-fade over the whole overlap shows a 1-px misalignment twice; multi-band fades fine detail narrowly and illumination widely.
  • L25-39: recurrence acc_L = ΣG·M/ΣM, acc_l = EXPAND(acc_{l+1}) + ΣL·M/ΣM; a lone frame reconstructs exactly.
  • L53-58: beyond ~6 levels the extra passes cost without gain; 6 levels over 2048 rows leave a 64-row coarse Gaussian.
  • L63-66 + ours L67-69: epsilon only guards 0/0, but at 1e-6 it visibly darkened areas whose weights are small but real (with cube feather, linear 0.01 → weight 1e-6 = half brightness).
  • L88-90: canvas under 8 rows keeps a single level (feathered mean).
  • L118-124: upsampled region sized to localTop + bandRows, not 2×coarseRows — odd level heights (ring canvases) otherwise throw a native CvException in submat.
  • L203-216 (history fa30a56): Laplacian sum recovered from accumulators with factor r_l = WSum_l / (EXPAND(WSum_{l+1}) + ε); without it a pixel just past a frame's border divides a nonzero band by ~ε; mirrors OpenCV's MultiBandBlender.
  • what the tests pin (MultibandBlenderTest): heights 1/4/8 → 1 level; 16→2, 32→3, 64→4, 128→5, 256→6; 2048, 4096, 100 000 → MAX_LEVELS; 0 and −5 → 1; level 0 = canvas, each level halves, odd sizes round down but never to 0; every band fits its upsampled region, odd canvas height keeps last band in bounds at every scale, upsampled region never smaller than the band; empty bands reconstruct to nothing.
  • unused features: none (no switches; MAX_LEVELS is the only depth knob).

SeamFinder.kt — builds the label grid: samples every frame per grid node, data/seam costs, Carve (graph cut) or WinnerTakeAll; hosts our tilt / holder-side penalties

  • status: shipped-on (WinnerTakeAll is our capture default = "Crisp"; Carve = "Careful" restitch)
  • our changes vs theirs:
  • WTA cover penalty = borderPenalty + tiltPenalty + holderSidePenalty (L429-432); theirs is borderPenalty only (theirs L429-431).
  • new tiltPenalty() (L460-467) and holderSidePenalty() (L482-491).
  • Important: these two are applied only in computeWinnerSeams (Crisp), not in computeSeams (Carve/Careful), even though StitchTuning KDoc says "Crisp/Careful". And the renderer's Blend-branch mask does not run when seams exist. So: Balanced = weight mask, Crisp = penalty, Careful = no holder-side rule at all.
  • [groundwork]: sampleInto uses intrinsics.projection.project (L598-603); reverted upstream to inline pinhole + radial.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const LABEL_GRID_WIDTH (private) 512 grid width; scale = ceil(W/512) (4096 → 8, 6144 → 12) L39
const WORK_LONG_EDGE (private) 512 frames downsampled (INTER_AREA) before colour sampling L53
const SMOOTH_LAMBDA 10.0 seam (pairwise) cost weight vs data cost (Carve) L64
const BORDER_PENALTY 1000.0 max data/WTA cost at frame edge; 1000·(1 − across·down), 1000 if outside L76, L628-637
const FEATHER_FULL_RES_PIXELS (private) 12 cross-fade half-width; grid half-width = max(1, 12/scale) (integer) L79, L346, L441
const MOVING_MASK_THRESHOLD 90f RGB distance (0..441) for the debug moving-object mask L89
const MAX_PASSES (private) 2 α-expansion passes L92
const OKLAB_SCALE (private) 255.0 OKLab scaled into the RGB budget L640
packed capacity start max(nodeCount·4, 16), doubles memory of sparse labels L148
holderSidePenalty 3000·min(1, −away/0.15) when frame forwardZ < −0.7 and bearing points to holder absent WTA only L482-491; off with maskBehindNadir=false
tiltPenalty StitchTuning.tiltPenalty (0.0) if fz > 0.65 and −0.77 < dirZ < 0.26 absent
param movingMask false Carve only L114
param perceptualSeamCost false (+DEBUG gate L314) OKLab L124
  • authors' notes:
  • L24-31: decided at reduced resolution — seam needs locating to a few px, cost scales with grid, feather computed where it is wide enough.
  • L42-52: ~512-px working copy keeps colours "identical to within an average" and avoids roughly doubling the stitch peak.
  • L56-63: seam cost is sum of two colour diffs; agreement costs tens, ghosts hundreds; λ≈10 lets the cut follow agreement while data breaks ties.
  • L66-75: border penalty large vs a consensus difference, far smaller than a genuine disagreement — only moves seams with nowhere better to go.
  • L82-88 / L237-246: moving-object mask makes a node neutral (every cover reads the mean, no border penalty) so the cut crosses moving things for free.
  • L95-102: gains applied to sampled colours so the seam is found in the world the renderer paints (gains are 1 unless refinement ran).
  • L133-138: flat byte copy because a per-sample Mat.get is a JNI call.
  • L165-167: last grid block may be short; centre clamped.
  • L341-344: full-turn canvas is a cylinder; solver and feather wrap the ±180° meridian.
  • L355-363: WTA = the prototype's scheme ported 1:1; no averaging so nothing ghosts.
  • ours L449-458: tilt rule exists because chair legs / fridge bases went to a floor-tilted photo shot from a different place → object broke at the join (first Crisp test 2026-11-26). Currently OFF (see StitchTuning note).
  • ours L469-480: holder-side rule assumes the agent turns their whole body for floor photos so the holder is always "behind" the photo; the photo's top edge points away from the person.
  • L494-498: nearestCenter kept pure so a JVM test pins it.
  • L575-581: sampleInto inlines projectDirection; must stay in sync with it and the renderer.
  • L645-652: OKLab is Ottosson's formulation from pano-blend src/colors.cpp; scaled so λ and border penalty stay balanced.
  • Derived from code (not a comment): SeamFeather nearest different label is ≥ 1 cell away, so the loser weight peaks at 0.5·(1 − 1/(hw+1)); at 4096 wide hw = 12/8 = 1 → max 0.25 over one 8-px cell; at 6144 hw = 1 → 0.25 over 12 px. The KDoc's "0.5 on the boundary" is never reached.
  • what the tests pin (WinnerSeamsTest): no covers → −1; lone cover owns; lowest penalty wins regardless of order (400/12/300 → label 5); ties keep the first; entries past count ignored.
  • unused features and how to turn them on: movingObjectSeamMask, perceptualSeamCost (Carve + DEBUG); tilt rule (StitchTuning.tiltPenalty > 0); holder rule for Careful would need adding the two penalties to computeSeams data term (not present).

SeamSolver.kt — pure-Kotlin α-expansion graph cut (Dinic max-flow) over the packed label grid

  • status: shipped-off by default (runs only for SeamMode.Carve: "Careful" restitch, capture debug Seam button, bench carve)
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const EPS (private) 1e-9 residual capacity treated as zero L74
const INF_UNARY (private) 1e15 cost of a label that does not cover a node L77
param solve(maxPasses) 2 (SeamFinder passes MAX_PASSES = 2) passes over labels; stops early if nothing changed L83
param smoothLambda caller (10.0) pairwise weight SeamFinder.SMOOTH_LAMBDA
param wrapLongitude false (SeamFinder passes true for 360°) adds column 0 ↔ last edge L85, L277
MaxFlow initial arrays 16, doubling L444
DFS initial push Double.MAX_VALUE / 4 L529
label order largest coverage first expansion order L177-187
  • authors' notes:
  • L46-56: energy = data (distance to covering mean) + λ·seam cost (how differently the two frames see p and q).
  • L57-66: a frame not covering a pixel is filled with that pixel's mean colour, making the pairwise term a metric → every expansion is submodular and exact min-cut never raises energy.
  • L89-91: big frames first set the context for later moves.
  • L119: four separate scratch colours so an edge never reads a stale one (a bug the tests caught, per history 8ad8721).
  • L193-196: only pixels α covers can move; edges to pinned pixels collapse into unaries.
  • L251-255: n-link weight is the submodularity surplus (B + C − A)/2.
  • L270-276: without the wrap edge the two sides of the meridian could pick different winners at zero cost → hard unfeathered seam when viewed wrapped.
  • L298-301: common offset keeps t-link capacities non-negative without changing the minimiser.
  • L436-440: level graph is shallow (source reaches every moving pixel), so recursive DFS is within stack.
  • what the tests pin (SeamSolverTest): max-flow saturates the min cut on random small graphs; zero-capacity edge carries no flow; reachable set bounds a min cut equal to flow value; solved labelling is locally optimal under single-pixel flips and never below the exhaustive optimum; improves on the data-only start; on a 4×1 strip the seam lands where frames agree ([0,0,1,1], energy = exhaustive minimum, λ=1, 4 passes); a single feasible label is taken everywhere.
  • unused features: energy() is test/diagnostic only; maxPasses > 2 never used by the app.

SeamWeights.kt — label map + loser label/weight lookup (SeamWeights) and the narrow seam feather (SeamFeather)

  • status: shipped-on (WTA and Carve both use it)
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
loser weight formula 0.5·(1 − d/(halfWidth+1)), d = Chebyshev distance ≥ 1 ramp across a cut L125; halfWidth from SeamFinder.FEATHER_FULL_RES_PIXELS
winner weight 1f; loser as above; anyone else 0f per-pixel weight per frame L54-57
param derive(wrapLongitude) false (SeamFinder passes true at 360°) feather crosses meridian L82, L106-107
  • authors' notes:
  • L10-14 / L64-70: grid at reduced resolution; only the loser ramps, winner always 1.
  • L44-47: weightFor maps a pyramid level's coords back to level 0 via sourceScale = 2^level.
  • L71-73: square window scan deliberately, cheaper than a distance transform over the full canvas.
  • L99-104: on a wrapped canvas the column distance is just |dc| because the window is narrower than the grid.
  • what the tests pin (SeamFeatherTest): two-frame split with halfWidth 2 → adjacent pixel's loser is the other frame at weight 0.5·(1 − 1/3); far pixels keep no loser; weight decreases monotonically away from the seam and stays in [0, 0.5]; uncovered (−1) pixels get no feather and do not bridge gaps; weightFor level-0 and level-1 lookups map to the right block, a third frame gets 0.
  • unused features: none; to widen joins raise SeamFinder.FEATHER_FULL_RES_PIXELS (with 12 and scale 8, 12/8 truncates to 1).

PivotModel.kt — lever-arm parallax model (lens ahead of the turning axis)

  • status: shipped-on (callers pass HandheldBodySwivel)
  • our changes vs theirs: none.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const MAX_RATIO 0.25 clamp on lever/scene ratio L58
None lever 0 m, scene 1 m (ratio 0) tripod / turn about the lens L61; bench arm0
HandheldBodySwivel lever 0.35 m, scene 10 m (ratio 0.035) standing, turning on the spot L70-71; bench arm10/arm20 set lever 0.10/0.20
debug scene distance (out of scope) 3.0 m → ratio 0.1167 debug builds only SphereDeviceProfile.kt:235
init requires lever ≥ 0, scene > 0 L39-44
  • authors' notes:
  • L6-11: swivelling your body puts the lens on a ~1/3 m lever; 90° later it has moved ~half a metre sideways — translation, which shows on near objects.
  • L13-25: only the ratio survives; it cancels out of lateral components, leaves depth as the only term.
  • L27-31: default deliberately cautious — too large a ratio bends frames apart; scene distance set beyond a typical room so far scenes gain ≤ ~1°.
  • L49-51: past MAX_RATIO the correction is bigger than the error; a scene within a few lever arms cannot be a sphere at all.
  • L66-68: 0.35 m = chest-to-lens with elbows in; 10 m chosen long rather than typical.
  • what the tests pin (PivotModelTest): only the ratio matters (0.5/20 = 1/40); HandheldBodySwivel.ratio = 0.035 (±1e-4); None.ratio = 0; 0.35/0.35 clamps to MAX_RATIO; no-lever ray unchanged; referred ray is unit length; optical axis unmoved by a lever along it; a 60° frame held out sees a narrower slice (between 25° and 29°); projection and referral are inverses (ratio 0.08); footprint shrinks off-axis but stays > 0.8 of on-axis column span.
  • unused features: nothing hidden; scene distance is the lever (RESULTS/history: prototype used 3.5 m, debug 3.0 m, release 10 m).

LensModel.kt — LensProjection abstraction [groundwork], pinhole + fisheye projections, RadialDistortion (Brown-Conrady) and distort/undistort helpers

  • status: RadialDistortion path shipped-off (distortionEnabled false by default); PinholeLensProjection is the live code path; EquidistantFisheyeProjection unused; LensProjection interface = [groundwork] reverted upstream.
  • our changes vs theirs: added imports atan2, cos, max, sin, sqrt (L4-9) — upstream b5796d7 file did not compile without them (comment L9). Otherwise identical. Upstream 3035b6e deleted L11-155 (interface, Pinhole, Fisheye) and expanded the RadialDistortion KDoc with the LENS_DISTORTION vs LENS_RADIAL_DISTORTION explanation.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
const UNDISTORT_ITERATIONS (private) 12 fixed-point iterations for undistort L250
const UNDISTORT_TOLERANCE_PX (private) 1e-4 stop when estimate moves less L253
isSignificant size ≥ 3 and any coefficient ≠ 0 otherwise treated as pinhole L190-191
pixelCoefficientsFor k1/f², k2/f⁴, k3/f⁶; null if insignificant, non-finite or f ≤ 0 unitless → pixel space L206-216
radialFactor 1 + r²(k1 + r²(k2 + r²k3)) shared polynomial L227-228
undistort bail factor ≤ 0 → last estimate fold-over guard L278-281
Fisheye default coefficients [groundwork] [0,0,0,0] (k1..k4 on θ) removed equidistant r = f·θ L87-89
Fisheye inverse [groundwork] 12 Newton steps, dr = max(1e-6, r·1e-4), |df| < 1e-9 break, tolerance 1e-6 removed L142-154
Fisheye focal floor max(1e-6, f) removed L109, L119
  • authors' notes:
  • L14-17: release defaults must keep pinhole + optional radial; other projections are debug/R&D only.
  • L160-173: camera2 LENS_DISTORTION maps ideal → distorted with coordinates normalised by focal length (x_i = (col − c_x)/f_x), OpenCV convention.
  • History de3ba4e (and upstream's post-revert KDoc): the deprecated LENS_RADIAL_DISTORTION normalised by the farthest array edge (±1); reading one through the other differs by (f/halfEdge)^(2n) per term — >2× on k1, >10× on k3. Earlier bug 8de6f6e: treating unitless coefficients as pixel-space blew a k1 of −0.02 to a corner factor of −124 999, so nothing painted and coverage fell under the floor ("Too little of the scene was captured").
  • History 2b986e8: distortion defaulted OFF pending a convention check — the S23 reports large coefficients of atypical sign.
  • L175-177: tangential terms dropped; tiny on phone lenses.
  • L184-189: all-zero distortion skipped to save three multiplies per pixel.
  • L222-225: one polynomial for renderer, footprints and keypoints so all agree.
  • L258-263: undistort usually settles in ~3 passes; matters because pose refinement calls it per keypoint.
  • what the tests pin (LensModelTest, coefficients [-0.02, 1e-3, -5e-5], 1024×768 at 66°×52°): optical centre unmoved; barrel pulls a corner in proportionally; undistort inverts distort to 1e-3 px; zero coefficients do nothing; pixel coefficients divide by f², f⁴, f⁶ (f = 1234.5); working frame focal = 512/tan 33° and fx ≈ focalPx within 1 px; empty / 2-term / f = 0 / NaN → null; all-zero → isSignificant false and forLens(...).radial == null; scaledBy(1.2) equals re-deriving at 1.2·f; scaledBy(1.0) returns the same instance; 4000×3000 and 1000×750 decodes describe the same lens (÷4); a realistic corner moves 0.1%..10%.
  • unused features and how to turn them on: radial distortion — capture debug toggle (distortionEnabled) or pass radialDistortion; fisheye — FrameIntrinsics.forLens(projection = EquidistantFisheyeProjection(k), maxFovDegrees = …) (no caller; upstream has dropped it, so treat as unmaintained).

RotationMath.kt — pure rotation algebra for PoseRefiner: RANSAC rotation, Procrustes, quaternion mean, rotation averaging, focal refinement

  • status: shipped-off by default (runs only when useRefinement = true: Careful restitch, debug Refine toggle, bench refine)
  • our changes vs theirs: none.
  • levers (values the caller passes live in PoseRefiner.kt, out of scope):
lever value OURS value THEIRS if different what it controls how to change
estimateRotation(minInliers) default 2 consensus floor L170
second-sample retry guard 6 tries RANSAC pair distinct L179
refineFocalLengths(iterations) 8 Gauss–Seidel sweeps L350
refineFocalLengths(maxCorrection) 0.15 (log scale, ~±16%) per-frame focal clamp L351
refineFocalLengths(anchorFrame) 0 gauge-fixed frame L352
Hessian diagonal floor 1e-9 below → delta 0 L388
symmetricEigen3x3 sweeps 32, stop at off-diag < 1e-15 Jacobi L478-488
Procrustes degenerate singular < 1e-9 → zero column L434
rotationBetween identity / anti-parallel thresholds cos > 1 − 1e-12; axis norm < 1e-12 L85-88
weightedMeanRotation magnitude floor 1e-9 L243
normalize3 fallback (0,0,1) under 1e-12 L579-582
averageRotations anchor frame 0 held at sensor value L276
  • authors' notes:
  • L15-18: rotations map camera axes → world, same convention as CameraBasis.toRotationMatrix.
  • L66-71: angle() uses atan2(sin, cos) because acos of a near-1 trace turns roundoff into a phantom angle.
  • L115-118: two-point hypothesis (vs three for a homography) cuts RANSAC iterations.
  • L197-201: refit by Procrustes, not by averaging per-pair rotations — a single vector pair does not fix spin about itself.
  • L229-231: quaternion averaging = first-order Karcher mean, fine for few-degree corrections.
  • L263-267: anchor frame 0 keeps the user's reference frame.
  • L333-343: focal anchor removes the global scale gauge; clamp ±0.15 stops a degenerate solve bending a frame; untouched frames keep their reported focal.
  • L377-379: deltas carry between sweeps deliberately (warm start, "not a bug").
  • L535-538: eigenvector reorder must interleave by row; laying columns back-to-back transposes (same family of bug as fromRotationMatrix).
  • what the tests pin (RotationMathTest): rotationBetween exact, anti-parallel valid; quaternion round-trip; Procrustes recovers from noise; eigen order; basisRotation exact; RANSAC with 1/3 outliers (300 bearings, 0.4° noise, threshold 1.5°, 400 iterations, seed 7, minInliers 100) gets ≥150 inliers and < 0.6° error; rotation averaging recovers absolute rotations; mean of identical rotations is itself; focal-warp derivative matches numeric; per-frame focal corrections recovered; correct focals draw ~0 correction (1e-3); a degenerate correspondence is clamped to exactly 0.15 and untouched frames stay 0.
  • unused features: whole file only runs with refinement. Bench verdicts (RESULTS.md L93-95, L155): wta+refine and wta+refine+sift+det1632 were worse on our captures (tilted photos up to ~3–4°, brightness tiles, cornice steps).

Restitch.kt — result-screen "try another style": StitchStyle mapping, params snapshot, restitch + diagnostics

  • status: shipped-on
  • our changes vs theirs: clears LastSphereInfo.bentPath = null and passes bentOutput = bentSphereWriter(context) (L105-108), so the bent picture follows whichever restitch ran.
  • levers:
lever value OURS value THEIRS if different what it controls how to change
StitchStyle.Balanced SeamMode.Blend wide multi-band blend L27
StitchStyle.Crisp SeamMode.WinnerTakeAll one frame per pixel L28
StitchStyle.Careful SeamMode.Carve + forced useRefinement = true graph-cut seams on content-matched poses L29, L126, L154
restitch canvas lonSpan 360, latCentre 0 (hard-coded); latSpan and lonCentre from params L129-132
GPano for restitch centred lon 0, lat 0 metadata L140-147
floor photo not passed restitch loses the floor patch L107-134
stitchDiagnostics EXIF default NORMAL when unreadable debug text L193-198
  • authors' notes:
  • L19-25: styles are friendly names over the same SeamMode pipeline.
  • L39-42 / L61-63: params frozen at first stitch; frames read at tap time; offer dies when the buffer clears.
  • L92-95: stitch failures rethrown as-is; disk failures wrapped in SphereWriteFailed ("bad photos" vs "no space").
  • L122-125: Careful uses refinement because it falls back to sensor poses when nothing matches; other styles keep sensor poses.
  • L174-181: diagnostics — yaw should sweep, pitch follow rings, roll stay small; a frame that lost its EXIF tag lands 90° off.
  • what the tests pin: none (no Restitch test upstream).
  • unused features and how to turn them on: RestitchParams.debugColors / distortionEnabled / useRefinement are carried from the capture snapshot; to keep the floor patch on restitch, restitchSphere would need a floorShot (not present).
stitching extras (mostly off), their laptop tools, tests, build

engine reference — stitching extras (mostly off), their laptop tools, tests, build

part of the engine reference (master_doc/engine/). written 2026-11-26 by reading every file of our copy (commit 16eb526) against theirs (b5796d7), plus their docs, tests, tools and commit history. line numbers point at our code at 16eb526; the floor-photo commits after it (eff5cd1, 022767a) shift a few. levers were read from the code, not tried on the phone. start at master.md -> "if something goes wrong with the camera".

Scope: (A) the optional / switched-off stitch stages in our vendored copy (apps/mobile/android/photosphere/src/main/java/com/n30dyn4m1c/photosphere/stitching/), diffed against upstream theclumsypirate/photosphere-android at b5796d7; (B) everything in upstream's repo we did not vendor (tools, device profile, CI, Gradle, tests).

Line numbers: ours: = our vendored file, up: = upstream file at b5796d7. File paths are relative to the stitching/ folder unless written out. "unverified" = not checked against the code or a run.

How the switches reach a stitch in OUR build (read from the code, 2026-11-26):

switch (PhotoSphereStitcher.stitchPhotos param) default capture screen result-screen restitch bench (DebugRestitch flag)
useRefinement (PhotoSphereStitcher.kt:348) false refinementEnabled=false (PhotoSphereCameraScreen.kt:483); its toggle sits in DebugSwitches, which we hid with if (false) (PhotoSphereCameraScreen.kt:2231) ON for "Careful" (Restitch.kt:126 params.useRefinement \|\| style == Careful) refine (DebugRestitch.kt:174)
perBlockExposure (:362) false, and also needs BuildConfig.DEBUG (PhotoSphereStitcher.kt:711) toggle hidden (same if (false)) never block (:181)
graphSubsetSelection (:370) false, + BuildConfig.DEBUG (:635) hidden never graph (:182)
localWarpAlignment (:377) false, + BuildConfig.DEBUG + needs refinement (:597) hidden never warp (:183), only does something together with refine
bentOutput (:394) null always passed (PhotoSphereCameraScreen.kt:1413), but a bent picture is made only when seams are a hard assignment (seams != null, PhotoSphereStitcher.kt:870), so on every Crisp (WinnerTakeAll, our default at PhotoSphereCameraScreen.kt:509) and Careful stitch passed (Restitch.kt:108), made for Crisp and Careful bend (DebugRestitch.kt:154)
StitchTuning.refineSift / refineDetectLongEdge (EquirectangularRenderer.kt:1047, :1051) false / 512 — — sift, detN e.g. det1632 (DebugRestitch.kt:113-116)
C++ backend (StitcherBackend) KOTLIN read at PhotoSphereCameraScreen.kt:1323 — —
night burst (NightFrameMerger) off debugNightEnabled=false (:347); its toggle lives in the HUD dropdown, which we set showDebugDropdown = false (:1818; upstream true, up PhotoSphereCameraScreen.kt:1564) — —

PoseRefiner.kt — matches photo pairs on image features and nudges each photo's measured direction (and lens angle) to what the pixels agree on

  • status: shipped-off for normal captures (useRefinement=false, PhotoSphereCameraScreen.kt:483, toggle hidden). Runs on a "Careful" restitch from the result screen (Restitch.kt:126) and on bench flag refine. When off, PhotoSphereStitcher.kt:602-613 builds a RefinementResult with sensor poses, gains all 1, focal scales all 1, so ExposureCompensation also never runs (see next section).
  • our changes vs theirs (ours:9,11,14 imports; ours:185-192; ours:203-205; ours:370):
  • feature detector is a switch: StitchTuning.refineSift true → SIFT.create(3000) + BRUTEFORCE (float) matcher; false → upstream ORB unchanged + BRUTEFORCE_HAMMING (up:182-184, up:195).
  • shrink size is a switch: StitchTuning.refineDetectLongEdge (default 512) instead of the const FEATURE_DETECT_LONG_EDGE (up:360). FEATURE_DETECT_LONG_EDGE (ours:105) is now unused.
  • shrink never enlarges: ours min(1.0, edge/longest) (ours:370); upstream scaled any frame to 512 even if it was smaller (up:360).
  • Everything else (thresholds, solve, focal refinement, local-warp builder) byte-identical to upstream (diff --strip-trailing-cr).
  • levers:
lever value OURS THEIRS if different what it controls how to change
StitchTuning.refineDetectLongEdge 512 (EquirectangularRenderer.kt:1051) const FEATURE_DETECT_LONG_EDGE = 512 (up:105) long edge (px) each photo is shrunk to before feature detection; also the image the mean brightness for gains is taken from (ours:407) set the var; bench detN
StitchTuning.refineSift false (:1047) (ORB only) ORB vs SIFT set the var; bench sift
StitchTuning.REFINE_SIFT_FEATURES 3000 (:1053) — SIFT max features const
ORB_MAX_FEATURES 1500 (ours:108) ORB features per photo const
ORB params scaleFactor 1.2, nlevels 8, edgeThreshold 31, firstLevel 0, WTA_K 2, HARRIS_SCORE, patchSize 31, fastThreshold 20 (ours:191) up:182-184 ORB detector code
RATIO_TEST 0.8 (ours:111) Lowe ratio: keep best match only if < 0.8 × second best const
MIN_MATCHES 16 (ours:121) below this many ratio-test matches a pair is skipped const
MIN_INLIERS 12 (ours:124) RANSAC inliers needed to trust a pair's rotation const
RANSAC_THRESHOLD_DEGREES 2.0 (ours:127) inlier angle const
RANSAC iterations 300 (ours:219) estimateRotation(maxIterations=300) code
RANSAC seed (a*31 + b*17) & 0x7fffffff (ours:688) deterministic per pair code
MAX_EDGES_PER_FRAME 5 (ours:130) neighbours each photo is matched against (strongest overlaps first, ours:676-684) const
MAX_SENSOR_DEVIATION_DEGREES 6.0 (ours:137) a pair whose image rotation is > 6° from the sensor's relative rotation is rejected as a false match const
AVERAGE_ITERATIONS 8 (ours:140) Gauss–Seidel sweeps of rotation averaging over the pose graph const
MIN_FOCAL_CORRESPONDENCES 40 (ours:151) total inliers needed before lens-angle (focal) correction runs const
MAX_FOCAL_CORRECTION 0.15 (ours:162) max ±15% focal change per photo (log space, also clamped in total ours:494-497) const
FOCAL_ITERATIONS 3 (ours:173) Gauss–Newton passes of the focal solve const
focal derivative step 1e-4 (log scale) (ours:610) central difference for the focal solve code
edge confidence inliers / (8.0 + 0.3 × matches) (ours:243-246) OpenCV match confidence, read only by FrameGraphQuality code
MIN_MESH_DEPTH 0.05 (ours:691) LocalWarp builder: skip projections this close to behind the other lens const
pivotRatio param default 0.0 (ours:179); stitch passes pivot.ratio (PhotoSphereStitcher.kt:596) refers feature bearings to the body-swivel pivot before RANSAC (ours:400-404) via PivotModel
buildLocalWarps param false (ours:180); stitch passes localWarpAlignment && BuildConfig.DEBUG (PhotoSphereStitcher.kt:597) builds LocalWarp meshes bench warp (+refine)
  • authors' notes:
  • "The sensor places every frame to within a degree or two … leaves the overlaps soft"; refinement is "a small per-frame correction on top of the measured pose — the sensor stays the anchor" (ours:77-84).
  • "Nothing here is allowed to make a stitch worse": every edge checked against the sensor rotation; frames with no reliable matches keep their sensor pose and reported focal; nothing matched → sensor rotations handed straight back (ours:96-100).
  • MIN_MATCHES "Deliberately low": a sparse but honest set from a low-texture scene is accepted because RANSAC must still agree with the sensor within 6° (ours:113-120).
  • 6° deviation rule: a bigger disagreement "is assumed to be a false match on repetitive texture, not a lens that suddenly moved" (ours:132-136).
  • focal floor 40: "a handful of matches from a low-texture scene would happily explain themselves as a focal shift" (ours:142-150).
  • focal cap 15%: "an order of magnitude more than the residual scale error a loosely-described lens leaves behind" (ours:153-161).
  • FOCAL_ITERATIONS comment says "two passes absorb most of the nonlinearity" but the const is 3 (ours:164-173) — comment/code mismatch, harmless.
  • Frame 0 is anchored for focal scale: the sphere can be scaled uniformly without changing alignment (ours:91-94).
  • Overlap graph is directional on both axes, not one distance: "two aims 55° apart overlap vertically but not at all horizontally" for a portrait frame (ours:651-656).
  • Pivot referral: two body-swivel frames translate, "a pure-rotation RANSAC cannot describe that; two pivot bearings of the same scene point differ by a rotation alone" (ours:348-353).
  • The exposure gains are solved over candidateEdges (every overlapping pair), not only the pairs whose features matched (ours:262-263).
  • Upstream capture screen: refinement "can move frames off the sensor's accurate answer when the scene has parallax (a body-swivel capture of a close scene breaks the pure-rotation feature model), so it starts OFF" (PhotoSphereCameraScreen.kt:476-481, same in upstream).
  • Upstream KNOWN_ISSUES.md:30-34: log "matched 0 edges" is "Expected on plain walls and repetitive texture … sensor poses stand. Not an error."
  • Upstream docs/capture.md:147: "The 35% overlap is what the feature-based pose refinement needs".
  • Upstream docs/stitching.md:59-79 restates the design and the ±15% / ≥40 correspondence gates; docs/status.md:4-6 lists focal refinement under "Still trying to make them better".
  • Upstream tools/restitch_other/README.md:61-67: "v13 (abandoned, file removed)" ran ORB/SIFT rotation refinement with the Kotlin PoseRefiner gates (1500 features, Lowe 0.8, 2° RANSAC, 12+ inliers, max 6° correction) on the all36 indoor set: "0 inliers on every pair, both ORB and SIFT. Indoor texture is too repetitive and parallax breaks the rotation-only model. Sensor poses stand as truth, same as the Kotlin default (refinement OFF)."
  • Our bench (capture-tests/RESULTS.md, 2026-11-25 21:29): refine = "same as base to the eye. only 3 of 36 photo pairs matched; one photo got rolled 6°".
  • Our bench (RESULTS.md 2026-11-26 02:28, 16-ring capture): laptop pair counts of 60 overlapping pairs — ORB 512: 30 (1 s), SIFT 1224: 51 (8 s), SIFT 1632: 54 (12 s), SIFT 3264: 56 (54 s); on the phone wta+refine accepted 19/60 and was worse ("photos tilted up to ~3–4°, brightness tiles, bed cut, cornice steps"); wta+refine+sift+det1632 15/60, worse, +10 s. Verdict: the pure-rotation model is violated by the ~27 cm phone movement between photos, so it stays off.
  • when it might help us: authors say it helps on far / textured scenes and fixes a lens angle that is a few % off; our measurements say it hurts indoors at arm's-length parallax. Note the "Careful" restitch button turns it on.

ExposureCompensation.kt — one brightness gain per photo so overlapping photos agree (Brown & Lowe gain compensation)

  • status: shipped-off in practice. Only called from PoseRefiner.refine (PoseRefiner.kt:263), so it runs only when refinement runs (Careful restitch / bench refine). Normal captures get all gains = 1 (PhotoSphereStitcher.kt:609). Upstream KNOWN_ISSUES.md:19-20 says the app "compensates per-frame gains" — that is true only with refinement on.
  • our changes vs theirs: none (identical).
  • levers:
lever value what it controls how to change
ITERATIONS 12 (ours:30) Gauss–Seidel sweeps of the log-gain solve const
MAX_GAIN 1.6 (ours:47) per-photo gain clamp (symmetric in log space) const
MIN_GAIN 1/1.6 = 0.625 (ours:50) lower clamp follows MAX_GAIN
MIN_USABLE_LUMA 1e-6 (ours:53) blank-frame cut const
brightness measured mean of the shrunk grey photo (PoseRefiner.kt:407), whole frame, not the overlap input code
gauge geometric mean of connected gains = 1 (ours:112-124) sphere overall brightness unchanged code
  • authors' notes:
  • AE lock removes big jumps; what is left is "directional lighting AE cannot fix" — sun vs shade, window vs wall (ours:9-14).
  • The "brightness" is the mean over the whole frame, "which tracks the overall level a frame was recorded at without projecting pixels between frames" (ours:17-20).
  • Clamp 1.6: whole-frame mean is a coarse stand-in, "a frame that is half sky pulls its own gain in a direction the overlap never asked for. A long chain of those compounds" (ours:33-40); "two-thirds of a stop is more correction than an AE-locked session … has any business needing, so the clamp is inert on a healthy run" (ours:42-46).
  • Flat adjacency arrays instead of a pair map because a per-sweep scan would be quadratic (ours:64-67).
  • Frames with no overlap partner "stay exactly neutral" (ours:112-115).
  • Upstream test pins: healthy session [96,104,112,100] stays in 0.85–1.18; [10,240] clamps and keeps geometric mean 1.0 ±1e-3 (ExposureCompensationTest.kt:65-92).
  • Upstream KNOWN_ISSUES.md:16-22: strong directional light "exceeds the correction range"; workaround "start facing the brightest part of the room, avoid bare bulbs".
  • when it might help us: authors' case is brightness steps between photos at a Crisp join (one photo per spot). Getting it without the pose changes would need a code change (call it with sensor poses) — not built.

BlockExposure.kt — debug-only per-block brightness field on top of the per-photo gains

  • status: shipped-off (perBlockExposure=false and requires BuildConfig.DEBUG, PhotoSphereStitcher.kt:710; toggle hidden). Bench flag block. Note it multiplies the scalar gains, which are all 1 unless refine is also on.
  • our changes vs theirs: none.
  • levers:
lever value what it controls how to change
GRID_COLUMNS 64 (ours:38) blocks across the canvas; rows = square blocks (gridRowsFor, ours:62-65) const
ITERATIONS 20 (ours:45) Gauss–Seidel sweeps const
UPDATE_SHRINK 0.7 (ours:53) fraction of each update kept; rest pulls to neutral (regulariser) const
MAX_REFINEMENT 1.6 (ours:56) per-block factor clamp const
MIN_USABLE_LUMA 1e-6 (ours:59) blank block cut const
luma weights 0.2126 R + 0.7152 G + 0.0722 B (ours:247) block brightness, sampled once at block centre through SeamFinder.sampleInto code
wrapColumns longitudeSpan >= 360 (PhotoSphereStitcher.kt:724) field wraps at the ±180° join caller
  • authors' notes:
  • Pilot runs had per-frame gains "spread between 0.840 and 1.379, and that spread landed as visible steps where one frame's blend handed over to its neighbour's … the whole-frame mean … had no way to see a difference that lived inside one frame" (ours:14-20).
  • Each block solved "shrunk toward neutral and clamped to the same rail the scalar solve uses" (ours:22-29).
  • 20 sweeps because the graph is frames × blocks nodes, "a couple of more sweeps keep the worst chain honest" (ours:40-45).
  • Shrink: "a block that only one frame ever covers is dragged back to 1 instead of absorbing that frame's whole error" (ours:47-53).
  • "Debug only … a null return leaves the renderer's behaviour exactly as shipping builds see it (see AGENTS.md)" (ours:31-33). AGENTS.md is not in upstream's repo at b5796d7.
  • Our bench (RESULTS.md 2026-11-25 21:48): wta+block 14 s, "brightness evening helps a little, but the wall still shows a vertical step and the tube light is cut in two → worse than base".

LocalWarp.kt — debug-only "APAP-lite" per-photo mesh that shifts pixels by the parallax left after the global pose solve

  • status: shipped-off (needs localWarpAlignment + BuildConfig.DEBUG + refinement on; PhotoSphereStitcher.kt:597; renderer applies it only for pinhole lenses, EquirectangularRenderer.kt:778). Bench refine+warp.
  • our changes vs theirs: none.
  • levers:
lever value what it controls how to change
CELL_LONG_EDGE_PX 220.0 (ours:41) target cell size in photo pixels const
cell count bounds ≥2 and ≤24 per axis (ours:218-223) mesh resolution code
MAX_CORRECTION_SHARE 0.02 (ours:44) max shift = 2% of photo long edge (2000 px → 40 px, ours:171-173) const
SMOOTH_PASSES 2 (ours:47) 3×3 mean passes over the cell field const
splat bilinear into 4 cells (ours:112-146) residual accumulation code
  • authors' notes:
  • The piano-and-TV case: one rotation per frame "cannot also be the rotation the piano two metres nearer demands" (ours:10-15); APAP's answer is a local subgrid (ours:15-17).
  • Residual per RANSAC inlier = where A's feature lands in B through refined poses minus where B recorded it (ours:19-27).
  • "The correction is intentionally small: it absorbs parallax, not pose" (ours:29).
  • Bilinear splat because nearest-cell counting "would make the mesh staircase at cell boundaries"; edge features clamp to border because "a feature at the very edge is exactly where the parallax correction matters most" (ours:115-121).
  • "A cell grid of hundreds would be a per-pixel warp in disguise; a sparse grid is the point" (ours:220-221).
  • Builder failure is caught: "A debug experiment that cannot run must never sink a stitch" (PoseRefiner.kt:297-300).
  • Our bench (RESULTS.md 2026-11-25 21:29): refine+warp 14 s, "same as base"; refine+warp+carve+mask "worse, blocky". It can only learn from matched pairs, and refinement matched 3 of 36 pairs on that capture.
  • when it might help us: authors aim it at near furniture parallax, our main defect; it is bounded by how many pairs match (ORB at 512 px matches few on plain walls).

FrameGraphQuality.kt — debug-only: drop photos that matched nothing (Brown & Lowe weak-node pruning / OpenCV leaveBiggestComponent)

  • status: shipped-off (graphSubsetSelection=false + BuildConfig.DEBUG, PhotoSphereStitcher.kt:635). Needs refinement for any effect (with no accepted edges nothing is dropped). Bench graph (+refine).
  • our changes vs theirs: none.
  • levers:
lever value what it controls how to change
MAX_DROPPED_SHARE 0.25 (ours:41) select: at most 25% of photos dropped const
MAX_DROPPED_ABSOLUTE 4 (ours:46) select: at most 4 dropped (16 photos → 4, 12 → 3) const
CONFIDENCE_THRESHOLD 1.0 (ours:53) selectLargestComponent: edges below this confidence are cut param confidenceThreshold (ours:118)
MIN_KEPT_SHARE 0.5 (ours:59) if the biggest component is < 50% of photos, keep all const
path chosen selectLargestComponent when confidences align with edges, else select (PhotoSphereStitcher.kt:636-646) code
  • authors' notes:
  • "A frame is dropped only when no overlap edge it takes part in produced an accepted match" (ours:16-17).
  • Cap so "a degraded capture (everything failed to match) does not turn into an empty stitch" (ours:18-20); the doc says the deepest ring frame is preferred when the cap bites (ours:20-21), but select just takes the first N orphans in index order (ours:87) — doc/code mismatch.
  • "On the pilot runs … typically little or nothing is dropped — which is the point"; log format "Frame graph: kept 36 of 38 frames, dropped: 12, 31" (ours:23-26).
  • Confidence formula inliers / (8 + 0.3 * matches) so "repetitive texture cannot buy a node in" (ours:98-105).
  • Safety floor not in OpenCV: "this pipeline's covers are on purpose, not a casual photo heap" (ours:108-112).
  • "a big pruned index list is a bug report, not a cleanup" (ours:36-38).
  • when it might help us: only if a photo is shot at a dead angle or through an obstruction; our bench has no result for it (unverified).

NightFrameMerger.kt — night mode: shoot a burst per target, align, merge to one low-noise photo

  • status: shipped-off / unreachable in our build. Runs only when debugNightEnabled && profile.nightMode != null && nightModeSupported (PhotoSphereCameraScreen.kt:1148); the toggle is in the HUD dropdown, which we hid (showDebugDropdown = false, :1818; upstream true, up:1564). Called via ImageCapture.saveNightBurst (camera/NightCaptureExtensions.kt:27-95).
  • our changes vs theirs: none.
  • levers:
lever value (Config default, ours:44-55) profile overrides (camera/SphereDeviceProfile.kt) what it controls how to change
framesPerTarget 12 default 8 (:58); S23 16 (:124); S21 12 (:153) burst size per target (NightCaptureExtensions.kt:36) profile
maxExposureTimeMs 333 250 / 500 / 333 not read anywhere (grep) — no effect —
maxIso 3200 1600 / 6400 / 3200 not read anywhere — no effect —
mergeMethod Median default WeightedAverage; S23/S21 Median per-pixel median vs sharpness-weighted mean profile
alignMethod ECC ECC everywhere ECC translation / ORB homography / None profile
minFramesForMerge 4 4 / 6 / 5 fewer captured → burst fails profile
alignDownscale 0.5 0.5 ECC runs at half size profile
medianTileSize 512 512 median processed in 512 px tiles profile
ECC translation only, 50 iterations, eps 1e-4, accept if correlation > 0.85 else unaligned (ours:193-206) code
ORB align 500 features, ratio 0.75, ≥8 matches, RANSAC homography 2.0 px (ours:242-280) code
gamma sRGB↔linear as pow 2.2 / 1/2.2 (ours:139, 444) code
weighted-average weights (s + 0.01·max) / (1.01·max) (ours:408) code
output night_merged_<name> JPEG quality 95 next to the first frame (ours:441, 454) code
night support check back camera hardware level 3 or EXTERNAL, or BURST_CAPTURE capability (SphereDeviceProfile.kt:182-205) code
  • authors' notes:
  • "ECC … for fast sub-pixel alignment; per-pixel median merge for ghost-free results; weighted average fallback" (ours:31-39).
  • ECC "Translation only (fast, sufficient for handheld)" (ours:203); 50 iterations "reduced for speed" (ours:196).
  • Median "is the gold standard for night mode: removes moving objects (ghosts), reduces noise by sqrt(N)" (ours:313-316); weighted average "doesn't remove ghosts" (ours:401-402).
  • Code facts: computeSharpness returns the squared mean of the Laplacian, though commented "Variance" (ours:431-432); the median reads every pixel through Mat.get per frame per channel (ours:375-389), i.e. very slow at full size (speed unmeasured).
  • Upstream capture screen: "Debug-only night mode toggle … Off by default; user opts in via the debug dropdown" (PhotoSphereCameraScreen.kt:345-347).

OpenCv360Stitcher.kt — JNI wrapper for a native C++ known-pose 360 stitcher

  • status: dead code. The native library opencv_360_stitcher is not in upstream's repo at b5796d7 nor in ours (no CMake, no .cpp, no externalNativeBuild in either build.gradle.kts — searched). create() catches UnsatisfiedLinkError and returns null (ours:59-74); the capture screen then shows "Native stitcher failed" (PhotoSphereCameraScreen.kt:1371-1378). Reached only if the C++ backend is selected (see StitcherBackend).
  • our changes vs theirs: none.
  • levers (all passed through to native code that does not exist):
lever default (ours:120-129) capture screen passes (PhotoSphereCameraScreen.kt:1352-1362) what it says it controls
outWidth 1024 1024 output width, height = width/2
ssaa 2 2 supersampling ("recommended for poles")
hfovDeg 65.0 debugCaptureFovDegrees first entry, else reported horizontal FOV lens angle
doGain true true gain compensation on the equirect grid
doRefine true true optional SIFT pose refinement
refineIters 4 4 SIFT refinement iterations
poses.json {"hfov_deg", "shots":[{"file","index","yaw_deg","pitch_deg","roll_deg"}]} (ours:93-100), written by SphereImageStore.writePosesJsonForCppStitcher (PhotoSphereCameraScreen.kt:1341) input sidecar
  • authors' notes:
  • Implements "the EXACT pipeline from sphere-100-percent-cpp-kotlin.md": known gyro poses, no feature matching, cv::remap, gain on equirect grid, distance-transform feather, optional SIFT refinement, "Coverage validation per 10° latitude band" (ours:12-19). That .md is not in upstream's repo (only these two .kt files mention it).
  • Convention: world X right, Y down, Z forward; R = Ry(yaw)·Rx(pitch)·Rz(roll) camera→world; pitch positive = up (ours:21-26).
  • "This requires the native library to be built via CMake. The library is only available in debug builds" (ours:44-46).
  • Upstream docs/stitching.md:11-20: org.opencv.stitching is absent from every prebuilt OpenCV for Android incl. 4.12.0 Maven; "a JNI shim would not link"; cv::Stitcher "is, in practice, a desktop API".

StitcherBackend.kt — debug preference: Kotlin stitcher (default) or the C++ one

  • status: shipped-off. Release builds always return KOTLIN (ours:32-34). In debug, reads SharedPreferences debug_prefs / use_cpp_stitcher (default false) (ours:15-16, 37-38). Toggle UI in Settings only when BuildConfig.DEBUG (settings/SettingsScreen.kt:101-103, 568). Read by PhotoSphereCameraScreen.kt:1323 and importer/ImportPhotosScreen.kt:168.
  • our changes vs theirs: none.
  • levers: | PREFS_NAME | "debug_prefs" | ours:16 | | PREFS_KEY | "use_cpp_stitcher", default false | ours:15, 38 | — turn on with setBackend(context, CPP_OPENCV) or the debug Settings rows. Turning it on in our app breaks stitching (library missing, see above).
  • authors' notes: "release builds always use the Kotlin backend" (ours:9-10); the C++ entry is described as "Native pipeline (spherical warp, multiband blend, bundle adjustment)" (ours:71) — differs from OpenCv360Stitcher's own header, which says no feature matching for poses.

SeamBend.kt (ours only) — "bent joins": optical flow at every join nudges both photos half way so details meet

  • status: shipped-on as a second picture. Made on every stitch whose seams are a hard assignment (Crisp = our default WinnerTakeAll, and Careful), handed to bentSphereWriter (PhotoSphereCameraScreen.kt:1413, Restitch.kt:108), stitched at PhotoSphereStitcher.kt:870-930. The normal picture is made first; any failure incl. out-of-memory only loses the bent one (PhotoSphereStitcher.kt:926-929). Not made for Balanced (Blend) because seams == null.
  • our changes vs theirs: whole file is ours (not in upstream). Renderer hook in EquirectangularRenderer.kt:124-128 (param) and :695-746 (per-pixel direction shift before projection).
  • levers:
lever value what it controls how to change
BAND_DEGREES 7.0 (ours:48) how far (degrees of longitude) from a join a photo may bend; also the box padding and the "implausible flow" cut (ours:377) const
MAX_BOX_SHARE 0.6 (ours:51) a join whose box is wider than 60% of the canvas is skipped (runs over a pole) const
MIN_SEAM_PX 20 (ours:54) joins shorter than 20 canvas px skipped const
MIN_MASK_PX 200 (ours:57) fewer bendable pixels → join skipped const
STEP 2 (ours:60) field stored every 2 canvas px, read bilinearly const
min box 32 × 32 px (ours:229) smaller boxes skipped code
flow DISOpticalFlow.PRESET_MEDIUM (ours:200) dense flow A(x) ≈ B(x + F) on grey, gain-matched layers code
layer resample INTER_LANCZOS4, black border (ours:491) how each photo is drawn into the join box code
fade (1 − d/band), half shift 0.5·F·fade; A uses −H, B +H (ours:378-380, 125) bend strength vs distance to join code
multi-join average shifts from every join touching the photo averaged by mask weight (ours:93-135) code
bench bend flag writes <variant>_bent.jpg (DebugRestitch.kt:153-157) flag
  • authors' notes (ours):
  • Why: hand-held capture swings the lens on an arm, photos "~14 cm apart", near and far shift by different amounts "(1-5°)"; solving where every photo stood "was tried and is not reliable at such small steps (capture-tests/RESULTS.md, 2026-11-26)" (ours:21-26).
  • Method of Google Jump / Facebook Surround360, measured on the laptop first as scripts/seam_flow_join.py (ours:28-29).
  • "Each photo's shift is continuous across the join, so wherever the blend mixes A and B they show the same content"; whole normal render (exposure, multi-band, hole fill, sharpening) runs unchanged, "only the sampled direction moves. Every pixel is still sampled once" (ours:36-43).
  • "Laptop bench: 7 beat 4" (ours:47). RESULTS.md 2026-11-26 02:55: 4° band fixed the right wire join and headboard but not the left wire/rod; 7° band with 16 around was best (wire both joins, curtain rod, headboard continuous; small smudges on clothes and curtain top edge); 7° with 12 around was worse ("bigger steps between photos = more to bend than the flow can fix. 16 stays").
  • "An implausibly large flow is a mismatch, not parallax: leave the pixel where it is" (ours:376-377).
  • RESULTS.md 2026-11-26 03:25 (phone, M36): 66 joins measured, 0 skipped, flow 7.2 s; normal 13 s, bent picture +46 s; right wire continuous, left join small kink; curtain rod continuous; headboard step gone; curtain top edge small jaggies; "next tuning: the kink on thin lines over plain wall (flow settings / band)".
  • when it might help us: it is the current fix for steps at joins on near objects; open tuning items are thin lines over plain wall (band, DIS preset).

Not vendored: device-profiles/samsung-sm-g996b/ — a camera dump of a Samsung Galaxy S21+

  • status: not vendored (reference data; a grep of upstream .kt/.md/.py/.kts for "device-profiles" or "sm-g996b" finds only KNOWN_ISSUES.md, which cites the model at lines 68-74).
  • contents:
  • 00-summary.txt (14 lines): "via adb dumpsys media.camera"; 12 camera ids. Back: id 0, 20, 23, 56 = 4032×3024, 5.4 mm (main); id 2, 58 = 4032×3024, 2.2 mm (ultrawide); id 21, 52 = 4864×3648 17.7 MP, 5.9 mm; id 50 = sensor 4624×3468, 5.9 mm, max JPEG only 3840×2160. Front: id 1, 4 = 3648×2736 3.3 mm; id 3 = 3216×2208. Line 14: "BURST_CAPTURE = prerequisite for high-res sizes to exist."
  • 01-capabilities.txt: per camera capability list; camera 0 has MANUAL_SENSOR, MANUAL_POST_PROCESSING, BURST_CAPTURE, PRIVATE_REPROCESSING, RAW, MOTION_TRACKING; 20/21/23 are LOGICAL_MULTI_CAMERA; camera 4 is SECURE_IMAGE_DATA only.
  • 02-samsung-keys.txt (440 lines): "85 distinct samsung.* keys on this phone", listed per camera as truncated prefixes (e.g. samsung.android.control.ae, …sensor.info.full, camera 52 adds …control.noise, …control.scene).
  • camera-<id>-<facing>.txt ×12: sensor size, focal length, JPEG output size list (each ends at 1920×1080 or lower).
  • authors' notes: KNOWN_ISSUES.md:66-74 — on SM-G996B Camera2 exposes at most the binned 4864×3648; the 64 MP 9248×6936 size is in neither normal sizes nor getHighResolutionOutputSizes; "third-party apps cannot capture it"; tracked at issuetracker.google.com/issues/162121234. Upstream's S21 profile (SphereDeviceProfile.kt:144-162) caps capture at 4000 long edge, burst 3, stitch 2000 → 6144, unsharp 0.3.
  • when it might help us: only as a template for dumping our own dev phone (Samsung M36) the same way.

Not vendored: .github/workflows/android.yml — CI debug APK build

  • status: not vendored.
  • triggers: pull_request, workflow_dispatch; never on push (lines 9-11). Concurrency group android-${{ github.ref }}, cancel in progress (13-15).
  • levers:
lever value line
runner ubuntu-latest 19
JDK temurin 17 38-42
SDK packages platforms;android-35 build-tools;35.0.0 platform-tools 46-49
Gradle cache cache-disabled: true 51-54
build ./gradlew :app:assembleDebug -PonlyAbi=arm64-v8a --info tee'd to build-debug.log 59-63
summary APK name + size + last 60 log lines into the run summary 65-82
artifact photosphere-debug-apk-arm64, if-no-files-found: error 84-89
  • authors' notes: Gradle output goes to the run summary "because the run page alone is hard to read when the build is long" (7-8); arm64-v8a only, "the ABI every modern phone runs" (56-58); --info "so the next 'unable to strip' line says exactly why" (58). Line 37 says "AGP 8.7.3 targets JDK 17" but libs.versions.toml pins AGP 9.3.1, and the SDK package is android-35 while app/build.gradle.kts compiles against 37 — stale comment / mismatch (whether CI still builds: unverified).

Not vendored: .github/workflows/release-signed.yml — manual signed release

  • status: not vendored.
  • inputs (lines 24-46): release_type beta|stable (default beta); version (empty = next from tags); notes; beta_as_release (default false); upload_artifact_only (default false). Secrets: KEYSTORE_BASE64, KEYSTORE_PASSWORD, KEY_ALIAS, KEY_PASSWORD (6, 59-63). Concurrency release-signed, no cancel (51-53).
  • steps: keystore decoded with umask 077 (90-99); keystore/alias/key-password checked by signing a throwaway jar — "the only way to tell a wrong key password from a wrong store password" (107-134); version computed from v* tags, beta bumps patch, stable reuses the newest unreleased beta (146-232); fails if tag exists (218-224); versionCode = current + 1, written by sed (211-212, 237-242); build :app:assembleRelease -PonlyAbi=arm64-v8a,armeabi-v7a -PkeystorePath… (244-252); APKs renamed photosphere_android_v<ver>_<abi>.apk, unzip -tqq checked (254-277); log scrubbed of the 5 secret values before going into the summary (281-302); commit + tag + git push origin main <tag> only after a good build (319-329); softprops/action-gh-release@v2, no body (331-341); keystore and raw log deleted if: always() (354-359).
  • authors' notes: "a run that is cancelled or fails therefore leaves no tag and consumes no version number" (12-15); "a run that dies during a long Gradle build is exactly the run whose tail nobody can read" (17-21); no add-mask on purpose because secrets are already masked and the runner "would receive the mask itself and reject it" (71-75); "pushing it again would need a force push, which this repo does not do" (218-220).

Not vendored: gradle/libs.versions.toml + build files — dependency and toolchain versions

  • status: not vendored as files; our apps/mobile/android/photosphere/build.gradle.kts hard-codes the same library versions.
  • versions (libs.versions.toml lines): AGP 9.3.1 (2), Kotlin 2.2.10 (3), core-ktx 1.15.0 (5), lifecycle 2.8.7 (6), activity-compose 1.9.3 (7), Compose BOM 2024.10.01 (8), CameraX 1.4.0 ×4 artifacts "keep all four artifacts on the same version" (10-11), exifinterface 1.3.7 (13), OpenCV 4.12.0 "Official OpenCV Android SDK, published to Maven Central since 4.9.0" (15-16), junit 4.13.2, androidx junit 1.2.1, espresso 3.6.1, test rules 1.6.1, coroutines 1.8.1 (18-25). Gradle wrapper 9.5.0 (gradle-wrapper.properties); daemon toolchain JetBrains JDK 21 (gradle-daemon-jvm.properties); foojay resolver 0.10.0 (settings.gradle.kts:15).
  • app/build.gradle.kts levers: applicationId theclumsypirate.com.photosphere.github (12), compileSdk/targetSdk 37 (9, 16), minSdk 26 (15), versionCode 6 / versionName 0.0.6-beta (17-18), debug applicationIdSuffix ".debug" no minify (39-42), release minify + shrinkResources + proguard (43-53), signing from -PkeystorePath/-PkeystorePassword/-PkeyAlias/-PkeyPassword (23-36), ABI splits on, -PonlyAbi= narrows, default arm64-v8a, armeabi-v7a, x86_64, no universal APK (60-71), Java/JVM 17 (73-80), buildConfig = true "BuildConfig.DEBUG gates the orientation debug screen, so R8 can strip it" (82-87), jniLibs useLegacyPackaging = false (93-96); orbit/MediaPipe code moved to app/orbit-disabled/ with excludes, restore = move files back + com.google.mediapipe:tasks-vision:0.10.14 (100-132).
  • gradle.properties: -Xmx2048m, MaxMetaspace 512m, workers.max 2, parallel false, caching + configuration-cache on, Kotlin daemon -Xmx1536m ("Memory caps for this 15 GiB machine", lines 1-11).
  • ours vs theirs: library module, compileSdk 35 ("the code uses no API newer than 35 (checked: no BAKLAVA / SDK_INT >= 36 gates)"), minSdk 29, VERSION_NAME "0.0.6-beta+pw", release minify off, jvmToolchain(17), Kotlin opt-in flags -Xwhen-guards -Xnon-local-break-continue -Xmulti-dollar-interpolation because the host uses Kotlin 2.1 (ours build.gradle.kts:1-60). No test dependencies.
  • authors' notes: OpenCV AAR "ships native libraries for every ABI (~120 MB unpacked)" — split per ABI or use an App Bundle (app/build.gradle.kts:56-59); a /* glob inside a Kotlin block comment "opens a nested comment … which breaks the whole build script" (108-111); the excludes are not what keeps orbit out, "The move to app/orbit-disabled/ is what keeps them out" (113-117). settings.gradle.kts:37-40 keeps an "Option B" local OpenCV SDK module commented out.

Not vendored: app/src/test, testDebug, androidTest — what each upstream test pins

  • status: not vendored (we have no src/test in our module). Tests run with ./gradlew :app:testDebugUnitTest upstream (task name unverified).
  • one line each:
  • PermissionGateTest (6 tests): empty result = cancellation; grant read from system; re-askable denial → rationale; partial grant → rationale; do-not-ask-again → settings; full grant → grant.
  • camera/AlignmentGateTest (8): fire only inside threshold after dwell, progress, restart on leaving, fire once, reset, no-fix ≠ aligned; pins DEFAULT_THRESHOLD_DEGREES = 2° and DEFAULT_DWELL_MILLIS = 300 (lines 88-93).
  • camera/CameraOpticsTest (13): focal length choice from multi-camera (main not ultrawide; widest if asked; narrowest without sensor size), calibration vs geometry (wrong crop thrown out), stream crop (16:9 on 4:3 loses height).
  • camera/GuidanceProfileTest (11): beep rate rises toward threshold, silent beyond cone / without fix, bounded cadence, halfway-dwell tick, spoken direction (level/centre, up-left, behind, down-right).
  • camera/OrientationSmootherTest (8): smoothing converges, fast pan snaps, yaw wrap short way, magnetometer-only spikes filtered but sustained moves followed, gyro samples snap.
  • camera/SharpnessSelectionTest (4): edges score higher than flat; flat = 0 at any brightness; too-small frames = flat.
  • camera/SphereCaptureCoordinatorTest (19): plan laid once from first bearing; shutter fires and advances only on landing; failed capture stays; undo rules (refused in flight, steps back, under the same lock); late captures after restart/undo ignored; no shot while sensor unreliable (uncalibrated still shoots); shutter waits for exposure lock; pose = mean of dwell samples only.
  • camera/SphereCaptureProfileTest (6): tap-to-focus vs fixed focus, lock support defaults true, OIS only when offered; default profile preferWidestCamera, capture cap ≥ 3000 px, burst ≥ 2.
  • camera/SphereProjectionTest (10): target projection to screen (centre, right, above, roll, behind), angular distance short way / ignores roll, orthonormal axes, marker one FOV across lands on the edge.
  • camera/SphereTargetPlanTest (16): rings inside ±60°, thin toward poles, start at facing bearing, alternate sweep direction, even spacing, FOV-scaled overlap, adaptive rings reach poles, narrower lens → more rings, no duplicate zenith rings on ultrawide, ring capture = horizon only, order horizon → up → down.
  • camera/TargetSelectionTest (8): active target holds, squarely aiming claims another, captured never claimed, hand-over to plan successor / nearer gap / wrap.
  • diagnostics/ReportTest (3): account names, emails and tokens redacted.
  • metadata/GPanoXmpInjectorTest (13): every GPano property written, well-formed xpacket, image bytes untouched, XMP after JFIF/Exif, replaces existing XMP, idempotent, refuses non-JPEG / truncated, ring capture = horizontal slice.
  • orbit/OrbitPlanTest (5): 12 angles from 0, skip captured, tolerance, shortest turn, wrap (orbit feature is disabled in the build).
  • result/PanoramaUvTest (11): viewer yaw/pitch → equirect UV (north centre, east right quarter, south seam, FOV edges, ring band keeps horizon centred).
  • sensor/OrientationMeanTest (7): angle mean unwraps ±180, carries freshest accuracy, zenith dwell averaged as rotations.
  • sensor/OrientationTrackerTest (16): degree normalisation, display-rotation remap, accuracy enum, capture refused only when unreliable, matrix ↔ angles round trip, pan reads as yaw, roll as roll, negative pitch = above horizon.
  • stitching/ExposureCompensationTest (8): pair/chain equalised, unreachable neutral, identical = 1, runaway clamped (geo-mean 1), healthy session within 0.85–1.18, self edge harmless, empty graph neutral.
  • stitching/LensModelTest (12): distortion leaves centre, barrel pulls edges in, undistort inverts distort, coefficients normalised by focal not frame edge, all-zero calibration skipped, focal scale re-normalises coefficients.
  • stitching/MultibandBlenderTest (16): level count (coarsest ~8 rows tall, capped), halving sizes, footprint scaling incl. seam-wrapping, band bounds on odd sizes.
  • stitching/PhotoSphereStitcherTest (12): status code ranges, canvas never wider than frames justify, even width, height follows latitude span, power-of-two decode subsampling, transposed FOV swapped back, loose FOV left alone.
  • stitching/PivotModelTest (9): only arm/scene ratio matters, no arm = no correction, too-close scene clamped, referral and projection inverse, off-axis lens shrinks the footprint.
  • stitching/RotationMathTest (13): rotationBetween, quaternion round trip, Procrustes with noise, eigen solver, RANSAC with 1/3 outliers, rotation averaging, focal derivative vs numeric, per-frame focal recovery, correct focal → no correction, degenerate solve clamped.
  • stitching/SeamFeatherTest (5): half weight at the cut, monotone fall-off, uncovered ignored, pyramid level lookup.
  • stitching/SeamSolverTest (8): max-flow = min-cut on random graphs, labelling locally optimal and ≥ true optimum on tiny grids, beats data-only start, seam follows where frames agree.
  • stitching/SphericalGeometryTest (37): camera basis axes, projection inverses, canvas ↔ lon/lat, footprints (date line, pole, never outside canvas, contains every paintable pixel), distortion widens footprint, directional overlap test, ultrawide pose graph, feather strongest on axis, impossible FOV rejected.
  • stitching/StairsVirtualGridTest (5): locks the virtual stairs grid — 5 pitch rows (−45, −20, 0, 20, 45) × 10 yaws 36° apart + 6 zenith caps at +75 + 6 nadir caps at −75 = 62 frames, yaw step < H_FOV 49, matches coords.json; camera model H_FOV 49, V_FOV 63, lever 0.35 m, scene 3.5 m (header lines 8-22).
  • stitching/WinnerSeamsTest (5): no cover = no owner, lone frame owns, closest-to-centre wins regardless of order, ties keep first.
  • testDebug/extendedcapture/ExtendedGridTest (6): extended plan = 62 targets in 7 rings (5×10 + 6 + 6), no gaps, Kotlin plan matches Python coords (testDebug/resources/virtual_stairs_coords.json), caps near poles; reference FOV band accepts 49×63 and 52×60, rejects 95×115 and 38×63.
  • androidTest/MainActivityUiTest (2, on device): camera granted → capture screen; denied → rationale gate.
  • when it might help us: ExposureCompensationTest, LensModelTest, PivotModelTest, RotationMathTest, SeamSolverTest, SphericalGeometryTest, WinnerSeamsTest are pure-JVM and cover the stitch maths we ship; copying them would guard our edits (they reference only engine classes, which we vendored — compile not verified).

Not vendored: tools/ (offline + lab scripts)

Catalog part: offline / lab tools in theclumsypirate/photosphere-android (not vendored)

Scope: tools/photosphere_lab.py, docs/lab.md, tools/offline_stitch/ (README.md, stitch_offline.py, stitch_openstitching.py), tools/restitch_other/ (README.md, common.py, restitch_v1..v12, v14). Every file read in full. Line refs are file:line in the upstream repo at commit b5796d7. Nothing was run.

Shared facts across the stitch tools (read in code, not run): - Test session for everything: tools/pano_proto/ref/all36 (37 frames with EXIF sensor poses) — restitch_other/README.md:3, stitch_offline.py:762-764. - Pose data lives in the JPEG EXIF UserComment (ExifIFD 0x8769, tag 0x9286), as text: index=N;yaw=..;pitch=..;roll=.. (degrees), optional matrix= 9 comma floats (camera basis, columns = right, minus-up, forward), and on debug builds ;hfov=..;vfov=.. — stitch_offline.py:43-48, 202-241, 286-289. - Sidecar: capture_debug.json beside the frames (debug builds), keys horizontalFovDegrees, verticalFovDegrees (docstring also says "plus the plan type", not read by code) — stitch_offline.py:244-258, 819-822. - Frames are named frame_<index>.jpg — stitch_offline.py:42, 292-309. - restitch_other depends on tools/pano_proto/stitch_all36.py (camera_frame, read_pose) and tools/pano_proto/view360.py (VIEWS, render_view), which are outside this part's scope (common.py:13-15, restitch_v1.py:27-29).


README summary: docs/lab.md — how to use the device-lab script

  • lab.md:3-8 — every app log uses the single tag PhotoSphere; adb logcat -d -s PhotoSphere:* | tail -50 shows everything.
  • lab.md:10-26 — tools/photosphere_lab.py (stdlib only, needs adb + debug build): logcat --out FILE, logcat --follow, sessions, frames --pull DIR.
  • lab.md:24 — EXIF orientation 0/UNDEFINED "is the known Motorola quirk the stitcher fallback handles".
  • lab.md:28-31 — deliberately does NOT drive the capture UI ("guided capture needs a hand turning a real phone — no script can aim it") and does NOT re-run the stitch in Python; placement forensics = EXIF audit + the stitch diagnostics line on the result screen (debug builds).
  • lab.md:33-39 — Settings screen (top-left of entry screen) builds one .txt bug report: app + device line, how the app last ended, saved crashes, last 4 hours of JSON logs, live logcat tail; emails, tokens and account names redacted; leaves the device only via the system picker / share sheet.

README summary: tools/offline_stitch/README.md — offline stitcher v2 (content-refined poses)

  • README.md:3-7 — v1 only stamped EXIF poses over a winner-takes-all render; without EXIF poses: objects shifted between frames, overlaps landed apart, content vanished at seams. v2 refines every pose from matched content before rendering.
  • README.md:9-26 — pipeline: (1) pose seeds from EXIF (angles + debug basis matrix) else even horizon ring; (2) SIFT (or AKAZE) + Lowe ratio + MagSAC on pair homography; (3) inliers unprojected to rays, Horn rotation solve per pair; (4) HFOV scan picks the smallest residual; (5) chain forward, ring-closure residual spread back evenly; (6) winner-takes-all render, blurred crossfade, wrap crossfade at the 180° meridian.
  • README.md:28-32 — verified on a synthetic ring: pair rotations within 0.0001° of truth, chained poses agree within 0.02° pairwise; absolute orientation stays the seed's (matching only sees relative geometry).
  • README.md:38-44 — example runs: python3 stitch_offline.py ../pano_proto/ref/all36 -o ring9.jpg --every 9 --run yeah; no dir argument defaults to all36.
  • README.md:46-57 — options: --w 4096 taller output; --hfov 55 start FOV scan closer; --no-refine = old behaviour for A/B; --matcher superglue (needs torch CPU wheel + weights under models/; SuperGlue sources carry a proprietary banner so they are loaded from a local clone at runtime, never vendored; pipx torch found automatically); --lever 0.35 --scene 3.5 for hand-held pivot referral.
  • README.md:59-69 — multi-row sessions: file order is not a ring; candidate pairs = any two frames whose forward directions are closer than 80% of HFOV; each connected component chains from its anchor; each refined pose clamped to --refine-max degrees of its seed (3 default) so thin sliver matches on texture-poor bands cannot drag structure.
  • README.md:71-77 — default HFOV 48° (~61° vertical at this frame aspect) = the number that framed the room correctly; 65 stretched the room / looked too close; the debug build's calibrated 39.7 left a stretched band along the bottom of the equirect.
  • README.md:79-90 — FOV priority: explicit --hfov → --fov-from-exif (frame ;hfov=..;vfov=.. comment or capture_debug.json) → 48° default scaled by aspect; log always prints the chosen pair and how to use a differing stamped one.
  • README.md:92-93 — FOV scan is opt-in (--auto-fov): "On sliver overlaps it keeps voting for an artificial small FOV, so it is a check, not the default."
  • README.md:95-96 — every run must be confirmed with --run yeah so a stray enter key does not start work.
  • README.md:98-111 — --content-only (ignore all poses, identity seeds, every pair tried, biggest component kept, 180° clamp): on all36 chains 26 of 37 frames, drops the plain wall band, covers 58% of the sphere, comes out incoherent (turquoise walls and ceiling match each other → false pairs). Seeded run matches 32 pairs and frames the room cleanly. "The EXIF seed is what makes the difference here, not the feature detector."
  • README.md:113-124 — OpenStitching attempt (stitch_openstitching.py): same outcome in every configuration — keeps only the biggest matched component (horizon row, or the floor on looser settings); with full connectivity ray adjustment fails or places one frame as a grey blob. "That is the library behaving as designed on a multi-row sphere with large featureless walls, not a settings problem." Kept because it works for a flat pan.
  • README.md:126-132 — phone-portable: Android OpenCV 4.7+ has patent-free SIFT and USAC/MagSAC in findHomography; Horn solve is three numpy lines; "this script is also the design for the app's own stitcher refinement, or for an offline NPU run such as the SuperPoint+LightGlue pairing on the AXERA boards."
  • README.md:139-140 — pano_proto/out/stairs_perfect.jpg stays the quality reference.

README summary: tools/restitch_other/README.md — killing ghosting on the 37-frame room capture

  • README.md:3-4 — source all36 (37 frames, EXIF sensor poses); baseline pano_proto/out/other_v2.jpg + views_other_v2.jpg = 8.5/10 pano.
  • Score table as recorded by the authors:
version what it tried recorded result README line
v1 global cv2.detail_GraphCutSeamFinder + multiband dead: addEdges w>=0 throw on OpenCV 4.13.0, global and pairwise, COLOR and COLOR_GRAD 8-10
v2 incremental pairwise seams (DP fallback), mosaic at 512px 3/10: 4x upscale blur + black dotted seam gaps; zero ghosting 11-12
v3 low-res DP ownership, full-res composite, 2px crossfade 5.5/10: sharp, ghost-free, DP cuts diagonally through objects 13-14
v4 own pairwise graph cut via PyMaxflow 5.5/10, same as v3; narrow overlaps force any pairwise seam through content 15-16
v5 global alpha-expansion, squared data costs 2/10 confetti: data (up to 195k) crushed smoothness 17-18
v6 v5 with Kotlin-scale costs (L1 data, LAMBDA 10) 4.5/10: coherent regions but sliced/duplicated movers; parallax too severe 19-20
v7 feather-center ownership + full-res composite + gains + 2px crossfade 7/10 views: sharp, whole objects, no ghosts; ceiling exposure tiles + dotted seams remain, 10-30px shelf offsets 21-24
v8 v7 ownership + cv2.detail_MultiBandBlender (5 bands, int16 feed) 8.5/10 views: ceiling/walls smooth gradients, dotted seams gone, detail single-source crisp 25-27
v9 wrap-aware circular centroid ownership same look as v8; did not bring the stove back ("ownership was never the cause") 37-38
v10 steep frames excluded from ownership + two mask bugfixes full pano with ceiling and floor, stove still missing 39-41
v11 global alpha-expansion (v6 costs) over horizon frames only, init from data cost, multiband 9/10 views, completeness 9/10 — the winner 29-35, 42-44
v12 critic top-5 fixes: pole bands pinned, 6 bands, 128px wrap, 3px boundary soften no score recorded 56-59
v13 ORB/SIFT rotation refinement of sensor poses (abandoned, file removed) 0 inliers on every pair, ORB and SIFT; output identical to v12 61-67
v14 OpenStitching blind reference not in README; no outcome recorded anywhere in scope —
  • README.md:31-35 — v11 verdict: stove back, no ghosts, no black areas, ceiling/walls smooth; what remains is "honest geometry": ~15px cabinet step (parallax) and the walking person appearing twice (true motion, not ghosting).
  • README.md:46-50 — subagent probe: ECC translation-only refinement is the wrong motion model (consecutive frames differ by yaw rotation); ECC converged to huge inconsistent 15-55px shifts; skipped.
  • README.md:51-54 — multiband needs aligned inputs: on misaligned pairs it equals plain averaging; with v7 ownership it fixes exposure tiles. Working Python bindings: prepare((x,y,w,h)) single tuple, feed int16 image + uint8 mask, blend(None, None).
  • README.md:61-67 — v13 used the Kotlin PoseRefiner gates (1500 features, Lowe 0.8, 2° RANSAC, 12+ inliers, max 6° correction); "Indoor texture is too repetitive and parallax breaks the rotation-only model. Sensor poses stand as truth, same as the Kotlin default (refinement OFF)."

tools/photosphere_lab.py — adb device lab: filtered logcat + capture-frame EXIF orientation audit

  • status: not vendored
  • inputs/outputs: needs adb on PATH and a connected debuggable build (photosphere_lab.py:4). Reads the app's private cache via adb shell run-as <PKG> ls cache/sphere_sessions/ and adb exec-out run-as <PKG> cat cache/sphere_sessions/<session>/<name> (65-67, 70-93). logcat writes to --out FILE or prints the last 8000 chars (54-62). frames audits the newest session only (sorted last, 149) and pulls its .jpg files to --pull DIR or default /tmp/opencode/sphere_frames/<session> (151). Parses EXIF Orientation (tag 0x0112) by hand from the first 1 MiB of each JPEG (96-142). Subcommands: logcat, frames, sessions (171-181).
  • levers:
lever value what it controls how to change
PKG theclumsypirate.com.photosphere.github.debug app id used for run-as photosphere_lab.py:28
APP_TAGS ["PhotoSphere"] logcat tag filter (-s PhotoSphere:V) photosphere_lab.py:29-33
crash filter AndroidRuntime:E adds runtime crashes to the filter photosphere_lab.py:45
logcat format -v threadtime log line format photosphere_lab.py:50, 55
print tail last 8000 chars stdout dump size when no --out photosphere_lab.py:62
session dir cache/sphere_sessions/ where the app caches capture frames photosphere_lab.py:71, 81, 91, 153
default pull dir /tmp/opencode/sphere_frames/<session> local frame destination photosphere_lab.py:151; frames --pull DIR
EXIF read size 1 << 20 bytes (1 MiB) how much of each JPEG is parsed photosphere_lab.py:104
EXIF_ORIENTATION_TAG 0x0112 tag audited photosphere_lab.py:34
logcat --follow flag, default off stream until Ctrl-C vs dump buffer photosphere_lab.py:175
logcat --out default None write dump to file photosphere_lab.py:176
frames --pull default None pull destination photosphere_lab.py:178
  • authors' notes:
  • photosphere_lab.py:7-8 — docstring lists tags PhotoSphere*, OrientationTracker, CameraOptics, PanoramaView, but code filters only PhotoSphere; comment at 30-31 says every log goes through Logging.TAG ("PhotoSphere"), so one filter shows everything.
  • photosphere_lab.py:14-16 — EXIF orientation 0 (UNDEFINED) is "the known Motorola quirk the stitcher's fallback handles -- if you see it, the fallback path is what placed the frame."
  • photosphere_lab.py:73-74 — run-as requires a debuggable build.
  • photosphere_lab.py:78 — "frames are cleared after a stitch", so sessions only exist for captures not yet stitched.
  • photosphere_lab.py:99-100 — EXIF parser never throws; anything unparseable is None.
  • photosphere_lab.py:163-165 — orientation None or 0 is counted as bad and flagged <-- UNDEFINED/MISSING.
  • when it might help us: lab.md:24 + photosphere_lab.py:14-16 say it is the way to spot the Motorola EXIF-orientation-0 quirk on a device's captured frames.

tools/offline_stitch/stitch_offline.py — laptop stitcher: EXIF pose seeds refined by feature matching (SIFT/AKAZE/SuperGlue + MagSAC + Horn), equirect render with 3 composers

  • status: not vendored
  • inputs/outputs: reads frame_<n>.jpg|.jpeg from directory (default ../pano_proto/ref/all36, 762-764); pose per frame from EXIF UserComment matrix= basis (preferred) else index=;yaw=;pitch=;roll= angles else an even ring (770-785, 843-852); FOV from ;hfov=;vfov= comment (median over frames) or capture_debug.json keys horizontalFovDegrees/verticalFovDegrees (812-822). Writes one equirect JPEG -o (default offline_pano.jpg) at --w x --w/2, JPEG quality 92, and prints coverage % (1106-1108). No adb; frames must already be on the laptop. Needs numpy, opencv-python, pillow; SuperGlue needs torch + a local clone (29-31, 99-154).
  • levers:
lever value what it controls how to change
FEATHER_PX 80 per-frame edge feather ramp (capped at half_w//8) stitch_offline.py:49, used 994
WRAP_SEAM_PX 64 crossfade width at the 180° meridian (capped w//4) :50, used 1100
WINNER_BLUR_PX 7 Gaussian sigma on winner masks (winner composer) :51, used 1095
GAIN_BLOCK_PX 256 BlocksGainCompensator block size :52, used 646-647
RUN_CONFIRM "yeah" required --run value :53
DETECT_WIDTH 640 width frames are downscaled to for SIFT/AKAZE :54, used 333
FOV_SCAN_STEP 2.5° auto-FOV scan step :55
FOV_SCAN_HALFSPAN 25.0° scan ± around start HFOV :56
FOV_FLOOR 30.0° lowest scanned HFOV :57
DEFAULT_HFOV 48.0° default horizontal FOV (vertical from aspect, ~61°) :61
MIN_PAIR_INLIERS 12 min Lowe matches and min MagSAC inliers per pair :62
REFINE_MAX_DEG 3.0° clamp of refined pose vs seed :68; --refine-max
SUPERGLUE_SOURCE_CANDIDATES ~/image-stitching-supeglue-main, ~/image-stitching-supeglue, <tool>/third_party/image-stitching-supeglue where the SuperGlue clone is searched (needs models/matching.py) :74-79
SuperPoint config nms_radius 5, keypoint_threshold 0.05, max_keypoints 2048 learned detector :81-85
SuperGlue config weights "outdoor", sinkhorn_iterations 20, match_threshold 0.9 learned matcher :86-90
SUPERGLUE_WIDTH 1024 max side of SuperPoint input :94
pipx torch probe ~/.local/share/pipx/venvs/torch/lib/python*/site-packages, ~/.local/pipx/venvs/torch/... finds torch outside the system python :108-124
MagSAC cv2.USAC_MAGSAC, reproj 3.0 px, maxIters 10000, confidence 0.9999 pair outlier rejection (both backends) :189-190, 368-369
Lowe ratio 0.75 SIFT/AKAZE match filter :360
matcher norm HAMMING for AKAZE, L2 for SIFT, BFMatcher knn k=2 matching :353-354
ring fallback step hfov * 0.65 per frame, pitch 0, roll 0 seed when no EXIF :261-264
candidate pair gate forward-direction arc < hfov * 0.8 which pairs get matched :899
content-only clamp 180.0° pose clamp when --content-only :945
BA iterations 30, prior_weight 0.02, damping 1e-3 (×0.3 on success, min 1e-6; ×10 on fail), finite-diff step 1e-6, 8 damping attempts rotation-only Levenberg-Marquardt over edges :549, 585-586, 602-617
front test ray z > 0.02 which canvas rays a frame can see :1009
render resolution frames resized to half (fw//2, fh//2), coordinates ×0.5 sampling resolution :992, 1012-1013, 1031-1032
median composer band_rows 64, presence weight > 0.01 memory banding for median :663, 676
multiband mask weight > 0.01 which pixels a frame feeds :1056
seam finders graphcut COST_COLOR_GRAD, dp COLOR --seam :1066-1070
output JPEG quality 92 :1106
directory (positional) default None → ../pano_proto/ref/all36 input :687, 762-764
-o/--output offline_pano.jpg output path :688
--w 2048 equirect width (height w/2) :689
--every 0 pick only this many frames, spread evenly (linspace) :690-691, 304-308
--hfov None explicit HFOV override :692-695
--fov-from-exif off use stamped / sidecar FOV :696-699
--auto-fov off scan FOV by median pixel reprojection error :700-703
--no-refine off render raw poses :704-705
--detector sift (choices sift, akaze) "legacy name for --matcher's SIFT/AKAZE half" :706-707
--matcher sift (sift, akaze, superglue) feature backend :708-711
--compose winner (winner, multiband, median) overlap combine :712-719
--bands 4 multiband levels :720-723
--seam graphcut (graphcut, dp) seam finder for multiband :724-727
--gain blocks (none, global, blocks) exposure compensator for multiband :728-732
--ba off joint rotation BA instead of chaining :733-737
--distortion "" Brown-Conrady k1,k2[,k3] (Camera2 LENS_DISTORTION convention) :738-741, 522-535
--content-only off ignore poses, rebuild from pixels :742-744
--refine-max 3.0 clamp degrees :745-747
--lever 0.0 pivot lever arm, scene units :748-749
--scene 3.5 scene radius for pivot referral :750-751
--run "" must equal yeah :752-758
  • authors' notes:
  • stitch_offline.py:12-15 — a pair's motion is a rotation "by construction" because the camera rotates about its pivot; Horn solve gives the exact relative rotation.
  • stitch_offline.py:29-31 — same pieces exist on Android (OpenCV 4.7+ SIFT patent-free, USAC/MagSAC), "so this pipeline is the design the app itself can adopt".
  • stitch_offline.py:58-61 — 48° is "the field of view the renders the user kept were made with", horizontal span of an upright portrait frame.
  • stitch_offline.py:63-68 — seeds carry the multi-row structure content cannot recover (texture-poor bands, pole frames); 3° is the setting that framed the room cleanly; a wider clamp lets thin sliver matches pull rows apart.
  • stitch_offline.py:69-73 — SuperGlue sources carry a proprietary banner, never vendored; tool loads the clone from disk.
  • stitch_offline.py:409-414 — FOV scan uses pixel reprojection error, not ray residual, because only the pixel metric "has a true minimum at the correct field of view".
  • stitch_offline.py:432-435 — content-only keeps only the biggest component: a frame the matches never reach has no pose.
  • stitch_offline.py:504-507 — clamp exists because sliver overlaps or a distorted lens can pull poses far away.
  • stitch_offline.py:552-558 — BA spreads chain noise over the whole graph, "which is what removes the residual drift that shows up as ghosting at the overlaps"; weak prior keeps thin overlaps from dragging a pose.
  • stitch_offline.py:635-643 — blocks gain handles a frame half in window light/half in shade; grid deliberately coarse: "at the 32 px default OpenCV allocates a gain per block per frame per channel, which is what ran the machine out of memory on a 38 frame sphere"; falls back to global gain, then to none.
  • stitch_offline.py:666-670 — median composer: averaging smears a moving person; median drops the outlier frames "so a walking body, a curtain or a screen that scrolled between shots simply is not in the result".
  • stitch_offline.py:715-723 — --bands: fewer bands keep low frequencies tighter, "which is what a pose error of a few pixels needs".
  • stitch_offline.py:806-811 — debug build stamps calibration ~39.7° "where the content frames the room at 48, so it is not the default".
  • stitch_offline.py:878-882 — candidate pairs come from seeded poses, not capture order, because sphere sessions jump between rows.
  • stitch_offline.py:914-919 — FOV scan uses the median over pairs so one noisy pair cannot drag the choice.
  • stitch_offline.py:1003-1005 — pivot referral: the lens sits ahead of the pivot, so the seen ray = point direction minus lever arm, in --scene units.
  • stitch_offline.py:1051-1053 — seams first, as OpenCV does: without them every frame votes in the whole overlap "and the average ghosts objects that moved between shots".
  • stitch_offline.py:1059-1061 — "The capture lets AE drift between frames, and the rows see very different light"; gain compensation is what stops low-frequency banding.
  • Observed in code (no author comment): --detector (706) is parsed but never read — backend selection uses only args.matcher (858, 865-866).
  • Observed in code: the docstring (18-20) and README.md:23-24 say the loop-closure residual is spread back, but main passes an identity spread_ring (lambda ref, anchor, distances: ref, 965-966), so no ring spreading happens in this version.
  • Observed in code: the even-ring fallback (782-785) multiplies args.hfov which defaults to None (692), so a session with no EXIF poses and no --hfov would raise a TypeError at that line.
  • when it might help us: README.md:126-132 and stitch_offline.py:29-31 say this pipeline is "the design for the app's own stitcher refinement"; stitch_offline.py:666-670 says --compose median removes people/objects that moved between shots.

tools/offline_stitch/stitch_openstitching.py — pixel-only stitch via the stitching (OpenStitching) package, no EXIF poses

  • status: not vendored
  • inputs/outputs: reads every *.jpg/*.jpeg/*.png (and upper-case) directly in directory (required here), natural sort (43-60). Optional --order-by-pose reads only the EXIF UserComment matrix= to reorder frames (63-107). Writes resized working copies frame_%03d.jpg (JPEG 95) into --work (default <output>_work, reused on the next run) (110-137, 268, 311-312) and the panorama -o (default openstitching_pano.jpg, JPEG 95, downsampled to --w) (196, 293-298). Needs pip install stitching (imports at 144).
  • levers:
lever value what it controls how to change
DEFAULT_WIDTH 900 frame width the stitcher works at stitch_openstitching.py:40; --width (0 keeps originals)
DEFAULT_FINAL_WIDTH 2048 saved width :41; --w
RUN_CONFIRM "yeah" required --run value (default "no") :35, 244-249
IMAGE_PATTERNS *.jpg, *.jpeg, *.png input globs :43
fixed Stitcher settings matcher_type "homography", refinement_mask "xxxxx", warper_type "spherical", nr_feeds 1, block_size 32, final_megapix -1, try_use_gpu False OpenStitching config :146-172
--every 0 every Nth frame (files[::every]) — note: different meaning from stitch_offline's --every (count) :202-203, 254-255
--work None → <output>_work working copies dir :204-206
--detector sift (sift, orb) features :207-210
--features 2000 nfeatures cap :211-212
--match-conf None (library per-detector default) pair match confidence, only applied for sift/orb :213-215, 173-174
--order-by-pose off greedy nearest-neighbour tour over EXIF forward vectors :216-220
--range-width -1 (all pairs); auto 6 when --order-by-pose reorders index-distance matching window :221-223, 259-263
--estimator homography (homography, affine) camera estimator :224-225
--adjuster ray (ray, reproj, affine) bundle adjuster :226-227
--wave-correct no (no, horiz, vert) wave correction :228-229
--confidence 1.0 image filter threshold; above 1 enables it :230-231
--blend multiband (multiband, feather, no) blender :232-233
--blend-strength 5.0 blend strength :234
--compensator gain_blocks (gain_blocks, gain, channel, channel_blocks, no) exposure comp :235-237
--medium-megapix 0.6 matching resolution :238-240
--low-megapix 0.1 low-res pass :241
--no-crop off keep empty warped borders :242-243
aspect warning ratio < 1.2 "part of the sphere is likely missing" :306-310
  • authors' notes:
  • stitch_openstitching.py:5-12 — reads nothing but pixels; use for a quick look when the pose path is not ready, or to compare two independent answers on the same frames.
  • stitch_openstitching.py:16-17 — --run yeah gate so a stray enter key does not start a multi-minute stitch.
  • stitch_openstitching.py:37-39 — width ~800-1000 keeps the spherical canvas near 5000x2500 "without spending gigabytes in the multiband pyramid".
  • stitch_openstitching.py:87-92 — OpenStitching's range_width is an index distance, so a row-by-row capture hides cross-row pairs; the nearest-neighbour tour fixes that.
  • stitch_openstitching.py:113-117 — resizing up front is what keeps the final spherical canvas and blend within reach; EXIF is not used so re-encoding loses nothing.
  • stitch_openstitching.py:154-156 — horizontal wave correction is for a handheld pan; a capture with rows and poles has no single horizon, so it is off by default.
  • stitch_openstitching.py:168-170 — final_megapix -1 so prepared frames are not rescaled a second time.
  • stitch_openstitching.py:259-260 — pairs further apart than 6 positions in the reordered tour "are not neighbours on the sphere".
  • stitch_openstitching.py:286-289 — usual failure causes: too little overlap or a texture-free band; try --medium-megapix 1.0, --features 4000, or --every 2.
  • stitch_openstitching.py:304-305 — a full sphere is about 2:1; anything far from it is a ring session or an unclosed canvas.
  • offline_stitch/README.md:116-124 — recorded outcome on all36: only the biggest component survives; full connectivity → ray adjustment fails or a grey blob; library behaving as designed, not a settings problem.
  • Observed in code: forward_from_comment takes matrix values [6:9] (80) while stitch_offline reshapes the same 9 numbers to 3x3 and takes column 2 (231-232, 289); the comment says "the third one" of the columns. The two scripts therefore read different numbers as "forward"; this only affects frame ordering here (66-67).
  • when it might help us: README.md:123-124 — "it works for a flat pan"; docstring 11-12 — useful as an independent pixel-only comparison.

tools/restitch_other/common.py — shared sensor-pose equirect warp, Brown-Lowe gains, and the (v13) ORB rotation-refinement code

  • status: not vendored
  • inputs/outputs: load_inputs(src_dir, pattern, hfov) globs frames, reads EXIF poses via pano_proto/stitch_all36.read_pose (else even ring with step hfov*0.65), returns focal lengths (30-48). warp_all inverse-warps every frame to a W x W/2 equirect, returns uint8 frames + uint8 coverage stack (55-90). solve_gains returns per-frame scalar gains (93-131). refine_poses = mosaic-vs-frame ORB rotation correction (195-246; per README the v13 experiment, file removed). No file output itself.
  • levers:
lever value what it controls how to change
ORB_FEATURES 1500 ORB features (Kotlin PoseRefiner value) common.py:21
LOWE_RATIO 0.8 match ratio test :22
RANSAC_DEG 2.0° rotation RANSAC inlier threshold :23
RANSAC_ITERS 300 RANSAC iterations (early exit at >90% inliers, :168) :24
MIN_INLIERS 12 min Lowe matches and min inliers :25
MAX_CORRECTION_DEG 6.0° largest correction trusted :26
MIN_OVERLAP_PX 2000 min frame/mosaic overlap before refining :27
RANSAC rng seed 0, 2-point samples determinism :157-159
ring fallback step hfov * 0.65 seed without EXIF :42-44
warp_all(scale=0.5) 0.5 frames sampled at half resolution :55, 69
front test z > 0.02 visibility :76
solve_gains(iters=12, gw=256) 12 iterations, 256px-wide gain canvas Gauss-Seidel in log space :93, 124-127
overlap minimum (gains) 50 px (at gain res) pairs used in the gain graph :113
gain clamp 1/1.6 .. 1.6 max per-frame gain :129
refine passes passes=1 refine_poses passes :195
  • authors' notes:
  • common.py:1-5 — same geometry as pano_proto/stitch_all36.py (pivot-referred lever), factored so each experiment differs only in gain/seam/blend.
  • common.py:17-20 — refinement gates are the Kotlin PoseRefiner values; bigger corrections "means the match is probably wrong, not the sensor".
  • common.py:58-60 — warped frames kept uint8 on purpose: "37 float64 frames would eat ~2 GB of RAM".
  • common.py:94-98 — gains run at 256px wide because gains only need mean brightness per overlap; full-res overlap tests (37x37 x 2 Mpx x 12 iters) "are what made the old version hang".
  • restitch_v1.py:6 — solve_gains is described as a "Brown-Lowe scalar gains per frame (Kotlin ExposureCompensation clone)".
  • restitch_other/README.md:61-67 — the refinement in this file (as v13) gave 0 inliers on every pair, ORB and SIFT; sensor poses stand as truth, matching the Kotlin default (refinement OFF).

tools/restitch_other/restitch_v1.py — global OpenCV graph-cut seams + multiband (dead)

  • status: not vendored
  • inputs/outputs: all36 (hard-coded SRC, :32), load_inputs(hfov=65.0), warp_all(lever=0.35, scene=3.5) (:42-43); writes out/restitch_v1.jpg (JPEG 92) and a 3x3 out/views_restitch_v1.jpg contact sheet of view360.VIEWS (JPEG 90) (:95-109). No CLI flags (same for every restitch_v script).
  • levers:
lever value what it controls how to change
W 2048 pano width restitch_v1.py:34
SEAM_W 512 seam-finding resolution :35
BANDS 5 multiband levels :36
WRAP_PX 64 wrap crossfade :37
hfov / lever / scene 65.0 / 0.35 / 3.5 warp :42-43
seam finder GraphCutSeamFinder("COST_COLOR") :60
blender MultiBandBlender, prepare([(0,0,W,H)]) list form, float32 feed :77-87
  • authors' notes:
  • restitch_v1.py:6-7 — gains applied before seam search "so fake exposure edges do not attract the cut".
  • restitch_v1.py:8-10 — graph cut "routes around disagreement (movers, parallax) instead of slicing through it" (the intent).
  • restitch_v1.py:57-59 — switched docstring's COST_COLOR_GRAD to COST_COLOR because the gradient cost "overflows the graph edge weights on full-canvas images (addEdges w>=0 assert)".
  • restitch_v1.py:62-63 — the finder needs uint8 (float32 gives getLinearColumnFilter error).
  • restitch_v1.py:82 — feed one frame at a time; all 37 as float64 ≈ 2 GB.
  • README.md:8-10 — outcome: dead, finder throws addEdges w>=0 on OpenCV 4.13.0 for global and pairwise, COLOR and COLOR_GRAD.

tools/restitch_other/restitch_v2.py — incremental pairwise seams (graph cut → DP fallback) at 512px

  • status: not vendored
  • inputs/outputs: as v1; writes out/restitch_v2.jpg, out/views_restitch_v2.jpg.
  • levers: W 2048 (:30), SEAM_W 512 (:31), WRAP_PX 64 (:32), small-overlap shortcut < 50 px just pastes the frame (:70-76), finder GraphCutSeamFinder("COST_COLOR") with DpSeamFinder("COLOR") fallback on cv2.error (:40-46); mosaic is built at 512px and upscaled with INTER_LINEAR to 2048 (:87-88).
  • authors' notes:
  • restitch_v2.py:4-8 — vs v1: never builds the 37-label graph; frames join one at a time in capture order, each join a 2-label seam.
  • README.md:11-12 — 3/10: 4x upscale blur + black dotted seam gaps; zero ghosting.
  • restitch_v3.py:4-8 — what v2 proved: single-source compositing kills all ghosting; 512px loop + 4x upscale blurred everything; DP masks leave 1px gaps (black dotted lines); GraphCutSeamFinder broken in this build (global and pairwise).

tools/restitch_other/restitch_v3.py — low-res DP ownership, full-res composite, 2px crossfade, centre-nearest hole fill

  • status: not vendored
  • inputs/outputs: as v1; writes out/restitch_v3.jpg, out/views_restitch_v3.jpg.
  • levers: W 2048 (:36), SEAM_W 512 (:37), WRAP_PX 64 (:38), CROSSFADE_PX 2.0 (Gaussian sigma on one-hot owner masks, :39, :91), overlap < 50 px shortcut (:70), DP finder "COLOR" (:44); hole fill picks the covering frame with smallest normalised distance from its optical centre (:98-118).
  • authors' notes:
  • restitch_v3.py:10-14 — vs v2: seam decisions stay at 512px but compositing at full 2048px; 2px crossfade "hides the DP staircase"; unclaimed pixels filled from the covering frame closest to its optical centre.
  • README.md:13-14 — 5.5/10: sharp, ghost-free, but DP cuts diagonally through objects.
  • restitch_v4.py:5-6 — v3 seam placement scored 3/10 ("content-blind diagonal cuts through laptops and cabinets").

tools/restitch_other/restitch_v4.py — own 2-label graph cut with PyMaxflow (photomontage costs)

  • status: not vendored
  • inputs/outputs: as v3 (needs pip package PyMaxflow, imported as maxflow, :21); writes out/restitch_v4.jpg, out/views_restitch_v4.jpg.
  • levers: W 2048, SEAM_W 512, WRAP_PX 64, CROSSFADE_PX 2.0, INF 1e9 (:34-38); edge weight = (disagreement at both ends)/6.0 horizontal and vertical (:61-63); 1px context border around the overlap bbox (:49-51); pixels only in mosaic/only in frame get INF terminal edges (:68-71).
  • authors' notes:
  • restitch_v4.py:7-10 — vs v3: solves the 2-label cut with Boykov-Kolmogorov maxflow; "cutting between two pixels costs the color disagreement at both ends, so the seam routes around movers and parallax".
  • README.md:15-16 — 5.5/10, same as v3: "Narrow overlaps force any pairwise seam through content."
  • restitch_v5.py:4-6 — "pairwise seams plateau: each new frame cuts against an already mixed mosaic".

tools/restitch_other/restitch_v5.py — global alpha-expansion labelling (Kotlin "Carve" formulation), squared data cost

  • status: not vendored
  • inputs/outputs: as v4; writes out/restitch_v5.jpg, out/views_restitch_v5.jpg.
  • levers:
lever value what it controls how to change
PASSES 2 expansion passes restitch_v5.py:38
LAMBDA 2.0 smoothness multiplier on L1 disagreement :39, 67-69
BORDER 400.0 max centre-preference penalty (dist² normalised × BORDER) :40, 44-52
data cost squared colour distance to overlap mean × coverage + centre penalty :102-103
init per-pixel argmin data cost :105-107
label order frames sorted by coverage, largest first :113
W/SEAM_W/WRAP_PX/CROSSFADE_PX/INF 2048 / 512 / 64 / 2.0 / 1e9 :34-37, 41
  • authors' notes:
  • restitch_v5.py:6-11 — "This is the Kotlin Carve mode formulation, solved globally": data = colour distance to overlap mean + centre preference; smoothness = cuts pay the disagreement they cross; one binary maxflow per frame, two passes.
  • README.md:17-18 — 2/10 confetti: data (up to 195k) crushed smoothness.

tools/restitch_other/restitch_v6.py — v5 with Kotlin-scale costs

  • status: not vendored
  • inputs/outputs: as v5; writes out/restitch_v6.jpg, out/views_restitch_v6.jpg.
  • levers: PASSES 2 (:38), LAMBDA 10.0 (:39), BORDER 1000.0 (:40); data cost = mean-abs per channel (sum of |diff| / 3.0, 0..255) × coverage + centre penalty (:102-103). Everything else as v5.
  • authors' notes:
  • restitch_v6.py:6 — vs v5: "data is mean-abs per channel (0..255) plus center preference, smoothness is LAMBDA times L1 disagreement, both on the Kotlin scale. v5 used squared distances (up to 195k) that crushed smoothness into confetti."
  • README.md:19-20 — 4.5/10: coherent regions but sliced/duplicated movers; "Parallax too severe."

tools/restitch_other/restitch_v7.py — feather-centre ownership (other_v2 placement), no computed seams

  • status: not vendored
  • inputs/outputs: as v3; writes out/restitch_v7.jpg, out/views_restitch_v7.jpg.
  • levers: W 2048, SEAM_W 512, WRAP_PX 64, CROSSFADE_PX 2.0 (:36-39); ownership score = 1 − normalised squared distance to the frame's (non-wrap-aware) coverage centroid at 512px, argmax (:57-67).
  • authors' notes:
  • restitch_v7.py:2-17 — docstring is the v3 text copied (stale); the real change is in the comment at :49-52.
  • restitch_v7.py:49-52 — "No DP, no graph cut: with this much parallax any computed seam slices content, while center-ownership keeps each object whole inside one frame."
  • README.md:21-24 — 7/10 views: sharp, whole objects, no ghosts; ceiling exposure tiles and dotted seams remain, plus 10-30px shelf offsets.

tools/restitch_other/restitch_v8.py — v7 ownership + OpenCV MultiBandBlender finish

  • status: not vendored
  • inputs/outputs: as v7; writes out/restitch_v8.jpg, out/views_restitch_v8.jpg. Docstring and usage line are stale copies (say v7).
  • levers: W 2048, SEAM_W 512, WRAP_PX 64 (:36-38); CROSSFADE_PX 2.0 defined (:39) but the composite now goes through MultiBandBlender with setNumBands(5), prepare((0,0,W,H)) single tuple, int16 frame feed + uint8 mask, blend(None, None) (:76-91).
  • authors' notes:
  • restitch_v8.py:72-75 — bindings validated by probe; "low frequencies blend wide so the ceiling and wall exposure tiles disappear, high frequencies stay single-source so detail never ghosts".
  • README.md:25-27 — 8.5/10 views: ceiling and walls smooth gradients, dotted seams gone, detail single-source crisp.
  • README.md:51-54 — multiband only works because v7 ownership is aligned by construction; on misaligned pairs multiband equals plain averaging.

tools/restitch_other/restitch_v9.py — wrap-aware circular-centroid ownership

  • status: not vendored
  • inputs/outputs: as v8; writes out/restitch_v9.jpg, out/views_restitch_v9.jpg. Docstring stale (v3 text).
  • levers: as v8 (bands 5, :81); centroid x = circular mean of coverage angles, distance = circular in x (:58-70).
  • authors' notes:
  • restitch_v9.py:49-52 — a plain centroid breaks for frames straddling yaw ±180: "their middle computes to canvas center and they lose every pixel, e.g. the stove frame".
  • README.md:37-38 — same look as v8; did not bring the stove back ("ownership was never the cause").

tools/restitch_other/restitch_v10.py — steep frames excluded from ownership + two mask bugfixes

  • status: not vendored
  • inputs/outputs: as v9; writes out/restitch_v10.jpg, out/views_restitch_v10.jpg. Docstring stale.
  • levers: steep threshold |pitch| > 20.0° → frame is hole-fill only (:65); blender bands 5 (:91); feed mask = owner AND real coverage (:101); holes = covered AND never fed (:116).
  • authors' notes:
  • restitch_v10.py:60-64 — "all36_v5 lesson": steep floor/ceiling-ring frames "reproject close-range pixels onto the horizon band at wrong positions (the scene-depth assumption breaks under a meter)"; horizon frames own the band, steep frames only fill poles.
  • restitch_v10.py:94-95 — argmax never yields "nobody", so without a coverage mask uncovered pixels inherit frame 0's black borders.
  • restitch_v10.py:99-100 — feed only own coverage "otherwise the blender eats its black borders (the v10 pole bug)".
  • README.md:39-41 — full pano with ceiling and floor, stove still missing.

tools/restitch_other/restitch_v11.py — global alpha-expansion (v6 costs) over horizon frames only + v10 masks + multiband — the recorded winner

  • status: not vendored
  • inputs/outputs: as v10 (needs PyMaxflow); writes out/restitch_v11.jpg, out/views_restitch_v11.jpg. Docstring stale (v3 text).
  • levers:
lever value what it controls how to change
PASSES 2 expansion passes restitch_v11.py:40
LAMBDA 10.0 smoothness :41
BORDER 1000.0 centre penalty max (now wrap-aware) :42, 46-61
INF 1e9 forbidden label cost :43
steep threshold pitch > 20.0°
data cost sum img − overlap mean /3 × cov + centre penalty
blender 5 bands :155
W/SEAM_W/WRAP_PX 2048 / 512 / 64 :37-39
hfov / lever / scene 65.0 / 0.35 / 3.5 warp :95-96
  • authors' notes:
  • restitch_v11.py:100-104 — data = colour distance to overlap mean + wrap-aware centre preference; "cuts pay the disagreement they cross, so they route around objects instead of through them (the v11 stove fix)".
  • README.md:29-35, 42-44 — 9/10 views, completeness 9/10; "The content-aware cut routes around the stove instead of through it"; remaining: ~15px cabinet step (parallax), walking person appears twice (true motion).
  • Observed in code: steep frames are removed via co & ~st with a Python bool st (:120); v12 replaces this line with np.zeros_like(co) if st else co (restitch_v12.py:120) without a comment saying why.
  • when it might help us: README.md:29-35 names this the winning recipe for the 37-frame room (EXIF sensor poses + horizon-only global alpha-expansion + multiband).

tools/restitch_other/restitch_v12.py — v11 + critic top-5 polish (pole pinning, 6 bands, 128px wrap, boundary soften)

  • status: not vendored
  • inputs/outputs: as v11; writes out/restitch_v12.jpg, out/views_restitch_v12.jpg. Docstring stale.
  • levers:
lever value what it controls how to change
WRAP_PX 128 (was 64) wrap crossfade restitch_v12.py:39
blender bands 6 (was 5) multiband levels :196
zenith band seam-res rows [:70] of 256 (i.e. pitch above ~40.8°, computed from 90 − 70/256·180) pinned to nearest up-ring frame (pitch > 20°) :156, 177-181
nadir band seam-res rows [175:] of 256 (pitch below ~−33.0°) pinned to nearest down-ring frame (pitch < −20°) :157, 182-186
boundary soften owner-boundary mask dilated 3x3, 50/50 mix with Gaussian blur sigma 1.0 takes the hard 1px edge off ownership steps :222-229
PASSES/LAMBDA/BORDER/INF 2 / 10.0 / 1000.0 / 1e9 as v11 :40-43
  • authors' notes:
  • restitch_v12.py:148-153 — "The zenith star and the nadir jigsaw come from ownership flipping between frames where coverage is thin"; each pole pixel forced to the covering steep frame nearest its centre; falls back to the expansion owner when none covers.
  • restitch_v12.py:219-221 — multiband already hides low-frequency steps; the soften pass removes the hard 1px edge.
  • README.md:56-59 — described as "critic top-5 fixes" with "3px boundary soften" (code: 3x3 dilation + sigma-1.0 blur); no score recorded.
  • README.md:66-67 — v13 (removed) produced output identical to v12.

tools/restitch_other/restitch_v14.py — OpenStitching blind reference on the 37 room frames

  • status: not vendored
  • inputs/outputs: all36 *.jpg (:29, 36), no poses; writes out/restitch_v14.jpg and out/views_restitch_v14.jpg. Needs pip install stitching (:11).
  • levers: Stitcher(detector "orb", matcher_type "hom", range_width -1, try_use_gpu False, adjuster "no", warper_type "spherical", wave_correct_kind "horiz", compensator "gain_blocks", finder "gc_color", blender_type "multiband", blend_strength 5, crop True, final_megapix 2) — restitch_v14.py:40-60.
  • authors' notes:
  • restitch_v14.py:7-9 — expectation from the pano_proto README: blind chaining cannot use poses "and builds a mosaic, not a sphere"; this run checks whether OpenStitching beats that.
  • restitch_v14.py:41-43 — ORB not SIFT: SIFT goes through FLANN "and crashes on texture-poor frames (knn > index size assert, same as stock cv2.Stitcher)".
  • restitch_v14.py:48-50 — adjuster="no" because bundle adjustment fails on these matches "(same reason our own refinement refuses everything)".
  • No recorded outcome for v14 in any file in scope; offline_stitch/README.md:113-124 records the separate stitch_openstitching.py outcome (biggest component only / grey blob).

catalog part: tools/pano_proto + tools/sps/seam_benchmark.py + tools/scratch/refine_chain_test.py

All paths are relative to the upstream repo root theclumsypirate-photosphere-android-b5796d7/. Nothing here was run; every claim comes from reading the file. Line refs are file:line.

tools/pano_proto/README.md — the lab notebook for the throwaway OpenCV stitch experiments

  • status: not vendored
  • what it says (lessons, with lines):
  • purpose: "Throwaway OpenCV experiments that validate stitching ideas before they earn a place in the Kotlin pipeline" (README.md:3-4).
  • example runs: stitch_v3.py --out v6, --images A.jpg B.jpg C.jpg, --focal 830 (README.md:7-9).
  • the ref/ corpus and out/ folder are git-ignored; corpus = clone of SSARCandy/panoramas-image-stitching, or device frames pulled with tools/photosphere_lab.py frames (README.md:12-15).
  • Xue-Mountain loop (f=830):
    • v1: SIFT + full-homography chaining + feather blend DIVERGED (37k-px canvas), "one bad link poisons a naive chain" (README.md:19-20).
    • v2: cylindrical projection + AffinePartial2D + per-pair sanity gates + middle anchor + overlap gain compensation scored 6.5/10; wide feather blending ghosted the sky into translucent vertical bands (README.md:21-23).
    • v3: center seam + 24px crossfade per overlap scored 8.5/10, bands gone (README.md:24).
    • v4: middle-anchored chain halved drift, ~9/10 (README.md:25).
    • v6: global horizon shear (end-to-end drift) scored 9/10, only crop-edge wedges left (README.md:26-27).
  • user's 37 saved frames with true EXIF poses:
    • all36_v1: sensor poses + plain averaging scored 5.5/10, with ghosts, ceiling arcs, nadir smear and a wrap strip (README.md:31-32).
    • all36_v2: adding pivot referral (0.35 m lever / 3.5 m room scale) + feather weights scored 7.5/10, horizon band clean (README.md:33-34).
    • all36_v3: adding room-scale scene + wrap-seam blend scored 8.5/10, no strip, tight ceiling, nadir streaks remain from close-range floor + wild pole rolls (README.md:35-36).
    • all36_v4: ECC content-refinement of near-pole frames scored 8.5/10; one frame genuinely corrected (rho 0.80), the rest refused, a warped mask left a black wedge, lesson "canvas-space warps need care" (README.md:37-39).
    • all36_v5: steep frames contribute only their sharp center (one owner per pole pixel) scored 9/10, clean zenith, readable nadir, continuous horizon, faint corner wedges; "Loop target met" (README.md:40-42).
    • other_v1 (Gemini's idea): winner-takes-all + pure rotation (lever 0) scored 8/10; zero transparency but disagreement moved into seam smears at the door, bed edge and lamp (README.md:43-45).
    • other_v2 (WTA with lever 0.35/3.5) scored 8.5/10; the door smear was gone, "so the lever earns its keep even under WTA"; nadir streaks remain (README.md:46-47).
    • verdict: neither WTA nor feather dominates; content-aware seam placement (graph-cut, the app's SeamFinder) is "the principled union of both" (README.md:47-49).
    • stock cv2.Stitcher crashed on 7 texture-poor frames (FLANN assert); on the other 30 it built a single-viewpoint mosaic, 2/10 as a 360 photo (~8/10 as a patch); "Blind chaining without poses cannot do this job" (README.md:50-54).
  • user's data_set (56 walking frames, no poses):
    • blind ring scored 2/10 "confetti", because the set is not a rotational sweep (README.md:58).
    • SIFT chain was rejected at pair 0→1 (true 4.6° jump) (README.md:59).
    • overlap graph (all 1540 ORB pairs): consecutive frames match with 100–780 inliers at rot≈0 and ~130px pure translation; it is a forward walk, 51/56 frames connect (README.md:60-62).
    • translation mosaics with a direction-consistency filter gave 5 strips (6,6,6,3,2 frames), 7–7.5/10 as maps (README.md:63-66).
    • verdict: "no sphere exists in this data"; forcing 360 geometry onto translation data "is what made every earlier attempt garbage" (README.md:67-69).
  • what it proved for the app: every validated trick has a Kotlin counterpart (PoseRefiner, ExposureCompensation, SeamFinder, sensor poses); "don't replace the pipeline — its bad stitches come from coverage, darkness and EXIF handling, not the blender" (README.md:73-77).
  • headless 360 viewer (view360.py): reproduces the A-Frame a-sky html-360-viewer mapping (same ray-cast, fov 80) (README.md:81-83).
    • v6-as-sphere scored 3/10: a cylindrical strip stretched over a sphere gives black bars, squeezed content and black on any tilt, "flat looks OK, 360 looks deformed" (README.md:92-95).
    • v7 true equirect scored 8.5/10, black only where nothing was shot (README.md:96-97).
  • ported fix: PanoramaView had mapped every canvas as a full sphere, so ring captures stretched vertically. The renderer now derives the latitude span from the canvas aspect (uSpanLat uniform + equirectUvForView span parameter, pinned by PanoramaUvTest) (README.md:99-103).
  • when it might help us: the README's own verdict says seam placement (graph-cut) beats both WTA and feather (README.md:47-49), and that bad stitches come from coverage, darkness and EXIF handling rather than the blender (README.md:75-77).

tools/pano_proto/out/ — committed output folder (README calls out/ git-ignored, README.md:15, but this snapshot contains files)

  • status: not vendored
  • contents (listed, jpgs not opened):
  • out/stairs_perfect.jpg (1,388,191 bytes). It is the default --out name of stitch_closed.py (stitch_closed.py:366), so it is probably that script's output on the virtual stairs set (unverified).
  • out/virtual_stairs/vframe_01.jpg … vframe_62.jpg (62 frames).
  • out/virtual_stairs/coords.json (7,015 bytes).
  • coords.json (read): 62 entries {file, yaw, pitch, roll, hfov, vfov}.
  • rows in file order: pitch -45 (10 frames), -20 (10), 0 (10), 20 (10), 45 (10), each at yaw -180, -144, … 144 (36° step).
  • caps: pitch +75 (6 frames) then -75 (6 frames) at yaw 0, 60, 120, 180, -120, -60.
  • every entry has roll 0.0, hfov 49.0, vfov 63.0.
  • this matches virtual_frames_stairs.py with its default --n 62 (virtual_frames_stairs.py:120).
  • inputs referenced elsewhere but NOT present in this snapshot: tools/pano_proto/ref/ (Xue, all36, html-360-viewer), tools/pano_proto/viewer/stairs_360.jpg, viewer/ooty_360.jpg, and panorama-improvement-report.md (searched the repo, none found).

tools/pano_proto/build_360.py — turns the closed v6 cylindrical Xue stitch into a true 2:1 equirectangular (out/v7.jpg)

  • status: not vendored
  • inputs/outputs:
  • reads ref/Xue/image_list.txt plus its images, and --pano (default out/v6.jpg).
  • writes out/<--out>.jpg (default v7), 2πf × πf px.
  • imports cylindrical, pair_transform, FOCAL from stitch_proto.py (build_360.py:17).
lever value what it controls how to change
SEAM_W 48 width (px) of the linear wrap-blend at the closure seam build_360.py:19
FOCAL (imported) 830.0 cylinder focal; sets W360 = round(2πf) stitch_proto.py:19
W360 / H360 round(2π·830)=5215 / W360//2 output size build_360.py:77,91
JPEG quality 92 output quality build_360.py:100
--out "v7" output name CLI
--pano out/v6.jpg input cylindrical stitch CLI
  • authors' notes:
  • the three steps are: force width to exactly 2πf (full yaw circle), wrap-blend the closure seam, remap rows cylindrical→equirect (build_360.py:4-7).
  • the geometry mirrors v6 exactly: middle rebase + horizon shear (build_360.py:48).
  • sign gotcha: image rows grow downward while elevation grows upward, so sky lives above the horizon row (build_360.py:89-90).
  • the README scores the result (v7) 8.5/10 in the 360 viewer test (README.md:96-97).

tools/pano_proto/check_overlap.py — per-pair "ghost check" for a capture chain (OK / SLAB / PROST)

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/all36) *.jpg sorted, with pairs (i, i+1) plus the closing pair last→first (check_overlap.py:83).
  • writes --out (default out/overlap_check): ghost_<i>-<j>_<VERDICT>.jpg and report.txt (frames, bad count, per-pair lines).
lever value what it controls how to change
LOWE 0.8 ratio test check_overlap.py:20
RANSAC 4.0 estimateAffinePartial2D reproj threshold (px) check_overlap.py:21
OK_INLIERS 60 inliers for "OK" check_overlap.py:22
WEAK_INLIERS 30 inliers for "SLAB" (below = "PROST"); also min good matches before RANSAC check_overlap.py:23
load width 640 frames downscaled to 640 px wide check_overlap.py:26
ORB nfeatures 1500 features per frame check_overlap.py:38
min descriptors 8 pair skipped below this check_overlap.py:46
ghost blend 0.5 / 0.5 B and warped A opacity check_overlap.py:67
--dir / --out ref/all36 / out/overlap_check I/O CLI
  • authors' notes:
  • "Double edges in the ghost mean a bad frame worth retaking" (check_overlap.py:6-7).
  • it only reads the frames, never touches Kotlin or the app (check_overlap.py:10).
  • when no alignment is found it writes the two frames side by side "so the gap is visible" (check_overlap.py:99-101).

tools/pano_proto/graph_overlaps.py — ORB match over ALL pairs of an unordered set, giving the overlap graph + connected components

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/all36) with --pattern (default *.jpg).
  • prints the strong-pair count, the top 40 pairs (inliers, rotation, translation) and union-find components. It writes no files.
lever value what it controls how to change
LOWE 0.8 ratio test graph_overlaps.py:18
RANSAC 4.0 affine RANSAC threshold graph_overlaps.py:19
MIN_INLIERS 30 edge counts as "strong" graph_overlaps.py:20
resize 640 px wide, grayscale matching scale graph_overlaps.py:26-27
ORB nfeatures 1500 per frame graph_overlaps.py:31
top printed 40 pairs listed graph_overlaps.py:71
--jobs os.cpu_count() or 4 multiprocessing pool size CLI
--dir / --pattern ref/all36 / *.jpg input CLI
  • authors' notes:
  • purpose: find which frames overlap and how strongly "so a rotational chain can be extracted for stitch_v3" (graph_overlaps.py:4-5).
  • result on data_set: all 1540 pairs, consecutive frames 100–780 inliers at rot≈0 and ~130 px translation, a forward walk, 51/56 connect (README.md:60-62).

tools/pano_proto/overlap_viewer.py — self-contained HTML contact sheet for check_overlap.py's ghosts

  • status: not vendored
  • inputs/outputs:
  • reads ghost_*.jpg in --ghosts (default out/overlap_check) and takes the verdict from the filename suffix.
  • writes <ghosts>/index.html.
lever value what it controls how to change
grid min card 150px card size overlap_viewer.py:20
verdict colors OK #2c6, SLAB #da0, PROST #c33 border colors overlap_viewer.py:24-26
"bad" count verdict == PROST header count overlap_viewer.py:59
--ghosts out/overlap_check input dir CLI
  • authors' notes:
  • on-page guidance: "Sharp ghost = frames agree. Doubled edges = retake the frame." (overlap_viewer.py:33).
  • no server needed, local only, never touches Kotlin (overlap_viewer.py:6-9).

tools/pano_proto/split_and_restitch.py — round-trip proof: cut posed frames from a public equirect, stamp EXIF poses like the app, restitch with stitch_all36.py

  • status: not vendored
  • inputs/outputs:
  • reads --pano (required; usage example tools/pano_proto/viewer/ooty_360.jpg, CC BY-SA 4.0 per split_and_restitch.py:4; the file is not in this snapshot).
  • writes out/<out>_frames/frame_XX.jpg with the EXIF UserComment index=N;yaw=..;pitch=..;roll=...
  • then runs stitch_all36.py --dir <frames> --out <out> --w <w> and writes out/<out>.jpg (split_and_restitch.py:96-101).
  • needs PIL.
lever value what it controls how to change
FW, FH 1224, 1632 cut frame size (portrait) split_and_restitch.py:33
FOV_H, FOV_V 49.0, 63.0 cut frame FOV (deg) split_and_restitch.py:34
RINGS [(0.0,12),(30.0,8),(-30.0,8)] pitch rows × count (28 frames) split_and_restitch.py:36
JPEG quality 92 frame quality split_and_restitch.py:93
border mode BORDER_WRAP sampling across the 0/W seam split_and_restitch.py:61
--pano required source equirect CLI
--out "proof" name stem CLI
--w 2048 restitch width CLI
  • authors' notes:
  • "If the math is right, the restitch matches the original panorama" (split_and_restitch.py:9-10).
  • the poses are stamped "exactly like the app does" in EXIF tag 0x9286 (UserComment) (split_and_restitch.py:6-7, 68).
  • stitch_all36.py hard-codes intrinsics for 2448×3264 and resizes every frame to 1224×1632 (stitch_all36.py:64, 117), so these 1224×1632 cuts enter at native size (our reading of the code).

tools/pano_proto/stitch_36_but_other_idea.py — "Gemini's idea": winner-takes-all from the highest feather weight + pure rotation, narrow blurred-mask crossfade

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/all36) with --pattern.
  • uses stamped EXIF poses if EVERY file has one, else an even horizon ring (step = hfov·0.65) "same fallback as the app's photo import" (stitch_36_but_other_idea.py:35-44).
  • writes out/<out>.jpg, 2:1.
  • imports read_pose, camera_frame, FEATHER_PX, WRAP_SEAM_PX from stitch_all36.py.
lever value what it controls how to change
BLUR_PX 7 Gaussian sigma on one-hot winner masks (crossfade width) stitch_36_but_other_idea.py:23
FEATHER_PX (imported) 80 edge ramp of the weight mask stitch_all36.py:27
WRAP_SEAM_PX (imported) 64 linear wrap blend width stitch_all36.py:28
even-ring step hfov × 0.65 fallback pose spacing stitch_36_but_other_idea.py:42
front cut z > 0.02 rays behind the camera dropped stitch_36_but_other_idea.py:69
vfov derived from hfov and the frame aspect (square pixels assumed) intrinsics stitch_36_but_other_idea.py:30-34
JPEG 92 output stitch_36_but_other_idea.py:105
--out other_v1 name CLI
--w 2048 canvas width CLI
--lever 0.0 pivot lever arm (m) CLI
--scene 3.5 scene radius (m) CLI
--hfov 65.0 FOV for the even-ring fallback and the intrinsics CLI
--dir / --pattern ref/all36 / *.jpg input CLI
  • authors' notes:
  • WTA picks the frame "closest to a frame center, where parallax and distortion are minimal" (stitch_36_but_other_idea.py:4-6).
  • "Transitions get a narrow crossfade by blurring the winner masks, so seams don't turn jagged" (stitch_36_but_other_idea.py:6-7).
  • other_v1 (lever 0) scored 8/10 with seam smears; other_v2 (--lever 0.35 --scene 3.5) scored 8.5/10 with the door smear gone (README.md:43-47; usage at stitch_36_but_other_idea.py:10-11).
  • note: this script reads --hfov (default 65) for the intrinsics even when EXIF poses exist, unlike stitch_all36.py's fixed 49/63 (our reading of stitch_36_but_other_idea.py:45 vs stitch_all36.py:65-66).

tools/pano_proto/stitch_all36.py — base pose-trusting equirect stitcher for the 37 saved frames (EXIF poses, pivot-referral back-projection, feather average + core window for steep frames)

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/all36) *.jpg; the pose comes from the EXIF UserComment yaw=;pitch=;roll= and frames without a pose are skipped.
  • writes out/<out>.jpg (default all36_v1), W × W/2.
  • prints the coverage %.
lever value what it controls how to change
ATT_RE yaw=(..);pitch=(..);roll=(..) pose stamp format stitch_all36.py:24
H_FOV, V_FOV 49.0, 63.0 "portrait frames, Moto G24 screen FOV" stitch_all36.py:25
LEVER_M 0.35 m handheld body-swivel pivot (lens ahead of pivot) stitch_all36.py:26
SCENE_M 3.5 m room-scale scene radius for the referral stitch_all36.py:26
FEATHER_PX 80 (capped at fw//8) linear edge ramp of the frame weight stitch_all36.py:27,79
WRAP_SEAM_PX 64 (capped at W//4) linear blend across the 0/W closure stitch_all36.py:28,155
fw, fh 2448, 3264 (hard-coded) intrinsics; images resized to fw/2 × fh/2 stitch_all36.py:64,117
core window central 20%–80% of h and w, Gaussian sigma 25 weight for steep frames stitch_all36.py:86-90
steep threshold abs(pitch) > 60 frame uses the core window instead of feather stitch_all36.py:136
front cut z > 0.02 rays behind the camera dropped stitch_all36.py:108
JPEG 92 output stitch_all36.py:162
--dir ref/all36 input CLI
--out all36_v1 name CLI
--w 2048 canvas width CLI
  • authors' notes:
  • the camera basis is reconstructed "exactly like SphereProjection.cameraFrame", and every canvas pixel is back-projected "like EquirectangularRenderer" (stitch_all36.py:4-7).
  • docstring: "Poses are trusted; v1 blends overlaps by averaging. Iterate on the blend." (stitch_all36.py:12). However, the code already contains the README's v5 core-window rule (stitch_all36.py:84-90, 130-131; README.md:40-42), so this file is the v5 state (9/10) under a v1 docstring (our reading).
  • pivot referral: "the lens sits ahead of the pivot, so the ray the camera saw is the scene point minus the lever arm" (stitch_all36.py:103-105). The README credits it with 5.5→7.5/10 (README.md:33-34).
  • core window: "steep near-pole frames contribute only their sharp center, so one frame owns each pole pixel instead of three smeared copies" (stitch_all36.py:84-85). The steep threshold is |pitch| > 60 "where Euler rolls collapse" (stitch_all36.py:130-131).
  • the EXIF UserComment "may decode with undefined-prefix", so the raw tag 0x9286 string is tried as a fallback (stitch_all36.py:40-42).
  • wrap seam: "canvas columns 0 and W-1 are adjacent in yaw but far apart in memory, so feathering never crosses the closure line. Blend it by hand." (stitch_all36.py:153-154).
  • when it might help us: the README credits the lever/scene referral and the core window for steep frames with the jumps to 7.5 and 9/10 (README.md:33-34, 40-42).

stitch_all36 v-series (v6–v15) — shared facts

  • All of v6–v14 are copies of stitch_all36.py. They keep its docstring, which still says "v1 … averaging", and its constants: H_FOV/V_FOV 49/63, LEVER_M 0.35, SCENE_M 3.5, FEATHER_PX 80, WRAP_SEAM_PX 64, fw/fh 2448×3264, core window 20–80% with sigma 25, steep |pitch| > 60, JPEG 92.
  • They also keep the same CLI (--dir default ref/all36, --out default all36_v1, --w 2048). Running any v6–v14 without --out therefore overwrites out/all36_v1.jpg (v6:187, v14:313).
  • v15 changes the default to --out all36_v15 (v15:480).
  • The README records no score for any v6–v15 file. The only recorded outcome in scope is stitch_closed.py:5-6: per-frame gain "only overfits noise and prints tone bands (the v14 defect)", said of the virtual frame set.
  • Lineage, from diffs: v7 builds on v6; v8 builds on v6 (not v7); v9 builds on v6; v10 is v6 with one changed line; v11 builds on v10; v12 builds on v11; v13 builds on v11 (not v12); v14 builds on v13; v15 builds on v14.

tools/pano_proto/stitch_all36_v6.py — WTA ownership + per-frame median-luma gain

  • status: not vendored
  • inputs/outputs: same as stitch_all36.py.
  • changes vs stitch_all36.py:
  • the feather averaging is replaced by winner-takes-all on the highest weight.
  • adds a per-frame gain pass.
  • the wrap seam becomes WTA instead of a blend.
lever value what it controls how to change
luma weights B 0.114, G 0.587, R 0.299 median luma per frame over pixels with w > 0.01 v6:141, 138
gain global_median / frame_median, clamped 0.7–1.4 exposure match v6:160-161
steep mask core if abs(pitch) > 60 else feather weight shape v6:151
wrap seam WTA per row over 64 px (left vs right best_w) closure v6:173-175
  • authors' notes:
  • the gain exists "so WTA ownership changes do not print as exposure steps" (v6:130-132).
  • "winner-takes-all ownership (no averaging, so no translucency) … Each canvas pixel comes from exactly one frame: the one with the highest feather weight there" (v6:146-148).
  • wrap seam under WTA: "each row of the strip is owned wholly by the left or the right edge … No blending, so no translucency at the closure line either" (v6:170-172).
  • recorded outcome: none.

tools/pano_proto/stitch_all36_v7.py — v6 + "multiband-lite" (low frequencies averaged, high frequencies WTA)

  • status: not vendored
  • changes vs v6:
  • each gain-corrected frame is split into low = GaussianBlur sigma 24 and high = frame − low.
  • low is weight-averaged across frames; high comes from the WTA winner; output = low + high.
  • the gain clamp widens to 0.5–2.0.
lever value what it controls how to change
low-pass sigma 24 split between averaged tone and WTA detail v7:167
gain clamp 0.5–2.0 exposure match v7:165
  • authors' notes:
  • "low frequencies averaged (no tone steps), high frequencies winner-takes-all (no translucency). One owner of detail." (v7:157-158).
  • recorded outcome: none.

tools/pano_proto/stitch_all36_v8.py — v6 + second pass of translation-only ECC per frame against the pass-1 canvas

  • status: not vendored
  • changes vs v6:
  • after the v6 WTA render, each frame's owned bounding box is ECC-aligned (MOTION_TRANSLATION) against the canvas at quarter scale.
  • the shift is applied at full scale, then the WTA is re-rendered.
  • v8 drops v7's multiband and keeps the 0.7–1.4 gain clamp (v8:161, 223).
lever value what it controls how to change
S4 4 ECC runs at 1/4 scale v8:177
ECC criteria EPS or COUNT, 40 iterations, eps 1e-3 convergence v8:180
min crop 8 px (quarter scale) per side crop floor v8:189
skip if tpl.size < 200 or std(tpl) < 3 flat or small zones are not aligned v8:196
max shift abs(dx)+abs(dy) > 60 px rejected outlier guard v8:207
  • authors' notes:
  • the pass fixes "few-px parallax/pose offsets that print as seam cuts. Cheap at quarter scale, applied at full scale." (v8:172-174).
  • recorded outcome: none. The README's earlier ECC try (all36_v4) corrected one frame (rho 0.80), refused the rest and left a black wedge from a warped mask (README.md:37-39).

tools/pano_proto/stitch_all36_v9.py — v6 + disagreement-aware ownership at half resolution

  • status: not vendored
  • changes vs v6:
  • instead of max weight, each pixel's owner maximizes w/wmax − 0.6·clip(|frame − stack median|/40, 0, 1) over a half-res stack.
  • the owner map is nearest-upsampled to full res.
  • the gain clamp is 0.5–2.0.
lever value what it controls how to change
ownership res H//2 × W//2 stack scale v9:160
disagreement weight 0.6 penalty vs coverage v9:176
disagreement scale 40 (gray levels) diff normalisation v9:176
min coverage wstack < 0.01 excluded ownership v9:177
gain clamp 0.5–2.0 exposure v9:164
  • authors' notes:
  • "Each pixel goes to the frame that both covers it well AND agrees with the stack median there, so cuts fall on flat/agreeing content instead of through objects." (v9:157-159).
  • recorded outcome: none.

tools/pano_proto/stitch_all36_v10.py — v6 with the gain clamp widened to 0.5–2.0 (the only change)

  • status: not vendored
  • change vs v6: the single line g = min(max(g, 0.5), 2.0) (v10:161), where v6 had 0.7–1.4 (v6:161). The rest is byte-identical.
  • authors' notes: no new comment. Recorded outcome: none.

tools/pano_proto/stitch_all36_v11.py — v10 + owned-pixel gain refinement + agreement-gated border crossfade + Telea hole inpaint

  • status: not vendored
  • changes vs v10:
  • (a) gains are refined 3× on owned pixels only.
  • (b) at ownership borders, the owner and the best alternative are blended 50/50 only where they agree.
  • (c) holes near covered area are inpainted.
lever value what it controls how to change
refine iterations 3 gain refinement passes v11:175
min owned px 500 frames owning fewer px keep their gain v11:177
refined gain clamp 0.5–2.0 per-frame scalar gain v11:182
border zone 9×9 dilation of each owner region ∩ border crossfade area v11:201
alt min weight w2 > 0.05 alternative frame must cover v11:213
agreement threshold mean abs diff < 25 blend vs keep hard edge v11:222
blend 0.5/0.5 border crossfade v11:223 (approx.)
inpaint mask holes within a 41×41 dilation of covered px what gets filled v11:234-235
inpaint radius 21, cv2.INPAINT_TELEA fill method v11:236-238
near-gate kernel 15×15 only decides whether to inpaint v11:228
  • authors' notes:
  • gain refine: "each frame pulled toward the pano it helped build, measured only on pixels it owns (no cross-talk from neighbors)" (v11:172-173).
  • crossfade: "8px along ownership borders blends only where the two owners agree (diff < 25); disagreements keep hard edges" (v11:192-193). The kernel in the code is 9×9 (v11:201).
  • inpaint is for "small uncovered holes (zenith/nadir wedges)" (v11:225).
  • recorded outcome: none.

tools/pano_proto/stitch_all36_v12.py — v11 + ceiling-band smoothing of flat regions

  • status: not vendored
  • changes vs v11: in the top H/4 band, where local gray std < 14, the pixels are replaced by a sigma-30 blur, softened through a blurred flat mask.
lever value what it controls how to change
band height H // 4 top band treated v12:254
local std window Gaussian sigma 9 flatness measure v12:257-258
flat threshold std < 14 what counts as flat v12:260
mask softening sigma 15 flat-mask feather v12:260
replacement blur sigma 30 the smoothed ceiling v12:261
  • authors' notes:
  • "where the top band is flat (local std low), replace with its wide blur so facet edges melt; detail (lamp, corners) is kept by the flatness mask" (v12:250-252).
  • recorded outcome: none. v13 does not carry this step forward (v13 is v11 + ORB).

tools/pano_proto/stitch_all36_v13.py — v11 + ORB affine refinement of each frame against the pass-1 pano

  • status: not vendored
  • changes vs v11: before the final render, each frame is ORB-matched against the canvas inside its owned bounding box. An estimateAffinePartial2D warp is applied when it is trusted.
lever value what it controls how to change
ORB nfeatures 2000 features v13:186
min owned px 2000 frames below this are not refined v13:193
min descriptors 10 each side match attempt v13 (just above 207)
ratio test 0.8 Lowe v13:208
min good matches 15 RANSAC attempt v13:209
RANSAC threshold 4.0 affine fit v13:211-212
min inliers 12 otherwise warp rejected v13:214
max translation abs(dx)+abs(dy) < 80 px outlier guard v13:216
  • authors' notes:
  • "match each frame against the pano inside its dilated owned zone, warp out few-px parallax/pose offsets, then render" (v13:184-185). The code uses the owned bounding box, with no dilation visible (v13:198-202).
  • recorded outcome: none.

tools/pano_proto/stitch_all36_v14.py — v13 + per-channel (RGB) gains

  • status: not vendored
  • changes vs v13:
  • adds per-channel gains gains[path+"0/1/2"] (v14:158-160).
  • the refine loop sets each channel to owned-pano mean / frame mean, clamped 0.5–2.0 (v14:182-187).
  • the final render multiplies by gc (per channel) × g (global-median gain, clamped 0.5–2.0) (v14:237-240).
lever value what it controls how to change
per-channel clamp 0.5–2.0 RGB gain v14:186-187
global gain clamp 0.5–2.0 luma gain v14:238
  • authors' notes:
  • no new comment in the file.
  • recorded outcome: stitch_closed.py:5-6 names "tone bands (the v14 defect)", caused by per-frame gain overfitting noise on the virtual set, where all frames share one exposure.
  • our code reading, not stated by the authors and not verified by running: the per-channel ratio is measured against img * gains[path] (scalar, never updated in v14, stays 1.0) on a pano that already contains the global gain g, and the final render then applies g again on top of gc (v14:185, 237-240). The border crossfade still uses the scalar gains[path] (v14:252).

tools/pano_proto/stitch_all36_v15.py — v14 with the final render swapped for "Kronbii-style" blends (multiband / sharp / feather / none) + gap fill

  • status: not vendored
  • inputs/outputs: same, plus --blend; the default out is all36_v15.
  • changes vs v14:
  • the WTA final render, agreement crossfade and 41×41/radius-21 inpaint are removed.
  • in their place, the gain-corrected frames are passed with binary masks (w > 0) to one of four blenders (v15:438-458).
  • then comes fill_gaps (Telea radius 3 over all uncovered px) (v15:461), then the 64 px WTA wrap seam (v15:464-466).
  • coverage is now computed as non-black output px (v15:469).
lever value what it controls how to change
MULTIBAND_LEVELS 5 ("Kronbii default") Laplacian pyramid levels v15:28
SHARP_BLEND_WIDTH 2.0 px ("Kronbii default (1-3 px)") sharp-blend linear falloff v15:29
distance-weight sigma 50.0 (ksize = 6σ, odd) multiband and feather weights v15:73, 126, 201
fill_gaps radius 3, INPAINT_TELEA hole fill v15:254, 270
feather ramp 80 (now literal) weight used for ownership and gains v15:293
wrap seam min(64, W//4) WTA closure v15:464
--blend multiband (choices multiband, sharp, feather, none) final blender CLI, v15:482-483
--out all36_v15 name CLI
  • authors' notes:
  • the docstring credits Kronbii/360-spherical-stitching src/blend.py and "recommendations from panorama-improvement-report.md". It lists: sequential cut-against-composite order (pano-blend), sharp blend option, OKLab seam cost concept (via weight space), per-component seam solving (MultiViewPano) (v15:4-10).
  • our reading of the whole file: no code implementing the cut-against-composite, OKLab or per-component seam items was found. Only the four blenders + fill_gaps are new.
  • panorama-improvement-report.md is not in this snapshot.
  • the comment says gain compensation is "Brown & Lowe log-space least squares" (v15:336), but the code under it is the v6 median-luma ratio (v15:337-346).
  • recorded outcome: none.

tools/pano_proto/stitch_closed.py — closed-loop stitch for virtual frames (pure geometry, WTA + agreement-gated border crossfade, streamed two-pass to save memory), with optional gain / feather / smart / vignette for real frames

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/all36; usage example out/virtual_stairs) *.jpg.
  • the pose comes from the sidecar <name>.pose first, then the EXIF UserComment (stitch_closed.py:36-60).
  • EXIF orientation 3/6/8 is applied (stitch_closed.py:63-80).
  • writes out/<out>.jpg (default stairs_perfect) at JPEG 95 and prints coverage and holes.
lever value what it controls how to change
H_FOV, V_FOV 49.0, 63.0 default optics stitch_closed.py:28; --hfov/--vfov
LEVER_M, SCENE_M 0.35, 3.5 pivot referral stitch_closed.py:29
FEATHER_PX 80 (cap fw//8) weight ramp stitch_closed.py:30,159
ALT_MIN 0.05 alternative frame weight needed to blend at a border stitch_closed.py:31,340
AGREE_DIFF 12 border blends only if mean abs diff < 12 (v11–v14 used 25) stitch_closed.py:32,340
FLAT_GRADIENT 6.0 smart blend: Sobel magnitude below this counts as flat stitch_closed.py:33,288
estimate_gains iterations 8, eps 1e-3, clip (0.55, 1.8) gain solver stitch_closed.py:83
gain min overlap 64 px (valid and lit) per-frame update skipped below stitch_closed.py:117,122
"lit" floor luma > 8.0 on both sides dark px excluded stitch_closed.py:121
gain solve res 256×128 luma coarse warped images stitch_closed.py:219-220
vignette model v = clip(1 − vig·(r²·0.5), 0.15, 1.0) radial falloff divided out stitch_closed.py:190-194
border zone 9×9 dilation crossfade area stitch_closed.py:322
inpaint holes within a 41×41 dilation, radius 21, TELEA hole fill stitch_closed.py:349-353
front cut z > 0.02 behind-camera rays stitch_closed.py:170
JPEG 95 output stitch_closed.py:357
--dir ref/all36 input CLI
--out stairs_perfect name CLI
--w 4096 canvas width CLI
--fw / --fh 2448 / 3264 frame size used for intrinsics (frames resized to half) CLI
--hfov / --vfov 49.0 / 63.0 optics CLI
--gain off per-frame exposure compensation CLI
--blend wta (choices wta, feather, smart) final blend CLI
--vignette 0.0 radial falloff strength, 0–1 at the corner CLI
  • authors' notes:
  • "NO gain compensation" by default: the virtual frames share one exposure, so "Any per-frame gain only overfits noise and prints tone bands (the v14 defect)" (stitch_closed.py:2-6).
  • "If poses and projection match, output must equal the source." (stitch_closed.py:8).
  • memory: frames are streamed twice, never all held, "so a 4096-wide render stays inside a few hundred megabytes instead of tens of gigabytes" (stitch_closed.py:10-13).
  • sidecar .pose is "the debug capture screen's output", so a frame whose JPEG is never rewritten still carries its pose (stitch_closed.py:39-42).
  • EXIF orientation is applied "so a portrait capture whose pixels are stored landscape is not stitched sideways" (stitch_closed.py:64-65).
  • gains are needed on real runs: each frame auto-exposes, so ownership borders "carry a brightness step even on one flat surface, which is the ceiling fan" (stitch_closed.py:86-89).
  • the gain update uses the median of other/self, not a least-squares mean, "because one bright window in a dark room would otherwise drag every gain towards it". Gains are clamped "so a pathological frame cannot turn the panorama grey", and normalised to geometric mean 1 (stitch_closed.py:89-95, 126).
  • vignette: "Divide out a radial lens falloff, so a flat surface does not darken towards a frame's corners and print petals at the borders" (stitch_closed.py:188-189).
  • smart blend: blend only "where every covering frame is itself flat, so a scene edge (present in one frame, shifted in another) still keeps the winner" (stitch_closed.py:254-256). There "a misregistration is invisible but the per-frame exposure step is not, so smoothing costs nothing. Edges keep the winner, so nothing doubles." (stitch_closed.py:284-287).
  • feather everywhere is "Fine when everything is registered; a real run with parallax ghosts here, which is why it is not the default" (stitch_closed.py:277-279).
  • the default optics "match the virtual set cut from stairs_360.jpg (3:4 portrait, 49 deg horizontal, 63 deg vertical). A real phone capture has its own lens, so override these" (stitch_closed.py:368-370).
  • help text: wta is for the virtual set; feather for real frames; smart for "real frames, no ghosting" (stitch_closed.py:381-384).
  • out/stairs_perfect.jpg exists in the snapshot (see the out/ section); no score for it is written down.
  • when it might help us: the authors' own notes prescribe --gain, --blend smart and --vignette for real auto-exposed phone frames (stitch_closed.py:375-387), with median-ratio gains robust to a bright window (stitch_closed.py:92-94).

tools/pano_proto/stitch_opencv.py — reference baseline: stock cv2.Stitcher over ref/all36

  • status: not vendored
  • inputs/outputs:
  • reads ref/all36/*.jpg (hard-coded, no --dir) (stitch_opencv.py:52).
  • writes out/<out>.jpg; exits 1 if the status is not OK.
lever value what it controls how to change
MODES pano → Stitcher_PANORAMA, scans → Stitcher_SCANS stitcher mode stitch_opencv.py:12
texture drop frames with < 15 ORB keypoints dropped avoids texture-poor frames stitch_opencv.py:30
--out ref_cv2 name CLI
--w 2048 frames wider than this are downscaled CLI
--mode scans mode CLI
JPEG 92 output stitch_opencv.py:39
  • authors' notes:
  • it is "same engine family xpano uses" (stitch_opencv.py:2).
  • README result: crashed on 7 texture-poor frames (FLANN assert); on 30 it made a single-viewpoint mosaic, 2/10 as a 360 (~8/10 as a patch) (README.md:50-54). The 15-keypoint drop at stitch_opencv.py:30 is presumably the guard for that crash (unverified).

tools/pano_proto/stitch_proto.py — prototype v2 for the Xue set: cylindrical + AffinePartial2D chain, middle anchor, Brown-Lowe-style overlap gains, sanity gates, feather blend

  • status: not vendored
  • inputs/outputs:
  • reads ref/Xue/DSC_0171.jpg … DSC_0178.jpg (hard-coded names, stitch_proto.py:159).
  • writes out/v2.jpg. There is no argparse.
  • its functions are imported by build_360.py and stitch_v3.py.
lever value what it controls how to change
FOCAL 830.0 px cylindrical focal (Xue image_list.txt) stitch_proto.py:19
LOWE_RATIO 0.75 SIFT ratio test stitch_proto.py:20
RANSAC_THRESH 3.0 affine RANSAC stitch_proto.py:21
MIN_INLIER_RATIO 0.15 pair rejected "LOW-RATIO" stitch_proto.py:22
MAX_ROT_DEG 3.0 pair rejected "WARP-INSANE" stitch_proto.py:23
scale gate 0.9 < scale < 1.1 pair rejected otherwise stitch_proto.py:61
min good matches 10 pair fails stitch_proto.py:46
overlap_gains iters 20, px > 8, min 500 px, sqrt nudge, gains[0]=1, clip 0.5–2.0 exposure stitch_proto.py:66-90
divergence guard canvas W > 12000 or H > 6000 means FATAL catches a runaway chain stitch_proto.py:131
feather ramp 60 px (horizontal only) blend stitch_proto.py:136
JPEG 92 output stitch_proto.py:150
  • authors' notes:
  • v1 lesson: "full-homography chaining on perspective frames accumulates fatal drift", having diverged to a 37k-px canvas (stitch_proto.py:4-5).
  • v2 recipe: cylindrical first ("pano-native geometry, like the app's sphere"), AffinePartial2D ("no perspective wobble"), middle-anchored chain ("drift grows both ways, halved"), per-image gains "like ExposureCompensation", sanity gates per pair (stitch_proto.py:5-10).
  • gain update: "nudge the pair toward equal means, anchored: gains[0] stays 1" (stitch_proto.py:84).
  • README score: 6.5/10, "wide feather blending ghosts the sky into translucent vertical bands" (README.md:21-23).

tools/pano_proto/stitch_v3.py — prototype v3–v6 for rotational sweeps: middle-out composite with a hard seam at each overlap center + 24px crossfade, middle rebase, global horizon shear

  • status: not vendored
  • inputs/outputs:
  • reads --dir (default ref/Xue) with names from --images, else image_list.txt, else --pattern glob.
  • writes out/<out>.jpg (default v5), cropped to the valid area.
lever value what it controls how to change
SEAM_HALF 12 (24 px crossfade) seam transition width stitch_v3.py:17
horizon shear trigger abs(slope × x-span) > 2.0 px apply the global shear stitch_v3.py:59
composite order mid, then right, then left middle-out stitch_v3.py:78
divergence guard W > 12000 or H > 6000 FATAL stitch_v3.py:72
imported gates/gains from stitch_proto.py see above stitch_proto.py:19-23
--out v5 name CLI
--images none explicit ordered list CLI
--focal 830.0 cylinder focal CLI
--dir ref/Xue input CLI
--pattern *.jpg glob fallback CLI
  • authors' notes:
  • v2 critique (6.5/10): wide feather blending ghosts the sky. The fix is a "hard seam at each overlap's center + narrow 24px crossfade (the poor man's seam carving)" (stitch_v3.py:4-7).
  • "Rebase the chain on the middle frame: drift grows both ways, halved." (stitch_v3.py:43).
  • horizon: "fit a line through the warped image centers and shear it flat (end-to-end drift correction). Purely global, no seams." (stitch_v3.py:49-50).
  • README scores: v3 8.5/10, v4 ~9/10, v6 9/10 "one continuous photo, only crop-edge wedges left" (README.md:24-27). The README runs it as --out v6 (README.md:7).
  • the docstring says "L-to-R", but the composite order is middle-out (stitch_v3.py:2 vs :78).

tools/pano_proto/translation_mosaic.py — strip mosaics for forward-walk (translation) frame sets

  • status: not vendored
  • inputs/outputs:
  • reads --dir (required) with --pattern (default *.png).
  • writes out/<out>_<segment>.jpg (default stem mosaic), one per run of consecutive kept links, at JPEG 90.
lever value what it controls how to change
LOWE 0.75 SIFT ratio translation_mosaic.py:19
RANSAC 4.0 affine RANSAC translation_mosaic.py:20
MIN_INLIERS 60 link accepted translation_mosaic.py:21
MAX_ROT 2.0 deg link rejected above translation_mosaic.py:22
DIR_TOL_DEG 25.0 link kept if its motion direction is within this of the median translation_mosaic.py:23
canvas guard > 20000 px either side means skip insane canvas translation_mosaic.py:112
feather 40 px all edges blend translation_mosaic.py:117
--dir required input CLI
--pattern *.png glob CLI
--out mosaic stem CLI
  • authors' notes:
  • "repetitive texture lies about which frames overlap, but true motion keeps one direction" (translation_mosaic.py:4-5).
  • the result "is a top-down-style strip MAP, not a 360 sphere" (translation_mosaic.py:7).
  • canvas placement has an inverted sign because "content moves opposite to camera" (translation_mosaic.py:106).
  • README: 5 coherent strips (6,6,6,3,2 frames), 7–7.5/10 as maps; "no sphere exists in this data" (README.md:63-69).

tools/pano_proto/view360.py — headless 360-viewer test: renders a 3×3 contact sheet of perspective views from an equirect

  • status: not vendored
  • inputs/outputs:
  • reads --pano (required, relative to tools/pano_proto).
  • writes out/<out>.jpg (required), a 3×3 sheet of 640×360 views at JPEG 90.
lever value what it controls how to change
VIEWS (0,0),(60,0),(120,0),(180,0),(-60,0),(-120,0),(0,25),(0,-25),(90,10) yaw/pitch of the 9 views view360.py:17-18
FOV 80.0 vertical FOV, matching a-sky / html-360-viewer view360.py:19
VW, VH 640, 360 view size view360.py:20
border BORDER_WRAP sampling view360.py:42
--pano / --out required I/O CLI
  • authors' notes:
  • it reproduces html-360-viewer (a-sky full-sphere texture, fov 80, drag-to-look) without a browser (view360.py:4-6).
  • README scores: v6-as-sphere 3/10 ("flat looks OK, 360 looks deformed"), v7 true equirect 8.5/10. That finding led to the uSpanLat latitude-span fix in PanoramaView (README.md:92-103).
  • when it might help us: the README says it caught the "flat looks OK, 360 looks deformed" class of bug without a browser (README.md:92-95, 99-103).

tools/pano_proto/virtual_frames_stairs.py — cuts posed virtual capture frames from viewer/stairs_360.jpg, stamps EXIF poses, writes coords.json

  • status: not vendored
  • inputs/outputs:
  • reads tools/pano_proto/viewer/stairs_360.jpg (not in this snapshot).
  • writes out/virtual_stairs/vframe_NN.jpg (JPEG 100, EXIF UserComment yaw=;pitch=;roll=0.0 via piexif) and coords.json (present in the snapshot, 62 entries).
lever value what it controls how to change
PITCH_ROWS [-45, -20, 0, 20, 45] ring rows virtual_frames_stairs.py:26
CAPS 6 at pitch +75 and 6 at -75, yaw 0/60/120/180/-120/-60 pole caps virtual_frames_stairs.py:27-28
FOV 60.0 defined but not used by render_view (our reading) virtual_frames_stairs.py:29
FW, FH 1224, 1632 frame size = warp_one's native fw//2 × fh//2, "so no resample here" virtual_frames_stairs.py:30
H_FOV, V_FOV 49.0, 63.0 "Must match stitch_all36.py exactly or the loop cannot close" virtual_frames_stairs.py:31-32
LEVER_M, SCENE_M 0.35, 3.5 forward model with pivot referral virtual_frames_stairs.py:33
ring size (n − 12) // 5 per row, yaw from -180 in 360/ring steps ring yaws virtual_frames_stairs.py:85-90
--n 62 (docstring says [--n 36]) total frames incl. 12 caps CLI, virtual_frames_stairs.py:120 vs :11
  • authors' notes:
  • "The internet pano has no capture coords, so we define the grid ourselves (yaw ring + pitch rows, like the orbit plan)". The frames are stamped "exactly like the app does", making the set "a drop-in input for stitch_all36_v*.py --dir, which proves the loop closes: known coords in, best stitch out" (virtual_frames_stairs.py:4-9).
  • the forward render "mimics the stitcher's inverse model exactly". Rays leave the lens at C = LEVER_M·fwd and hit a scene sphere of radius SCENE_M centred on the pivot. This is "bit-exact math with stitch_closed.py's warp_one" (virtual_frames_stairs.py:51-54, 64-72).
  • it only writes under out/virtual_stairs/ and never touches Kotlin (virtual_frames_stairs.py:12).
  • when it might help us: the authors built it as a known-pose ground-truth set to check that a stitcher closes the loop (virtual_frames_stairs.py:8-9; stitch_closed.py:8).

tools/sps/seam_benchmark.py — CI-only seam-quality metric on the SPS spherical-superpixel dataset (fraction of seam pixels crossing human segment boundaries)

  • status: not vendored
  • inputs/outputs:
  • convert <data_dir> <out_png_dir>: reads the dataset .mat files (scipy) and writes <stem>_labels.png (mode "I") and <stem>_boundary.png.
  • stats <png_dir> <report_json>: writes per-image segment stats and latitude-band occupancy as JSON.
  • seams <png_dir> <seams_dir> <report_json>: reads <stem>_seams.png and writes per-image crossing share, missing maps and the mean.
lever value what it controls how to change
PNG_DIR_LABEL_SUFFIX _labels.png label file naming seam_benchmark.py:52
PNG_DIR_BOUNDARY_SUFFIX _boundary.png boundary naming seam_benchmark.py:53
SEAM_SUFFIX _seams.png seam map naming seam_benchmark.py:54
labels pick first 2-D array with max > 1 .mat field heuristic seam_benchmark.py:75
boundary pick first bool/uint 2-D array with max ≤ 1, else the label gradient fallback seam_benchmark.py:76-86
latitude bands equator rows/3–2rows/3; north 0–rows/6; south 5rows/6–rows occupancy report seam_benchmark.py:119-121
90% share stat size at which 90% of pixels are reached segment stats seam_benchmark.py:149
boundary threshold > 127 boundary PNG to mask seam_benchmark.py:204
seam threshold > 0 seam PNG to mask seam_benchmark.py:205
rounding 4 decimals report seam_benchmark.py:126,216,226
exit codes 2 on bad usage or missing scipy; 1 on empty input CLI seam_benchmark.py:237-255
  • authors' notes:
  • "CI-only tooling, never run locally" (seam_benchmark.py:2).
  • dataset: SPS (cic.tju.edu.cn, ACCV 2018), 75 spherical panoramas at 1024×512, with MATLAB human segmentations. The terms are "GNU GPL style with commercial use prohibited, so this corpus stays internal: nothing derived from it may ever reach the APK or a release asset" (seam_benchmark.py:4-9).
  • it implements "research report sections 3.15 and 5.1" (seam_benchmark.py:11); that report is not in scope here.
  • the stats sanity-check "the polar pinching assumptions SphericalGeometry carries" (seam_benchmark.py:16-19).
  • metric: lower is better, "the seam should cut in the background, not across the piano" (seam_benchmark.py:20-23). It "ignores the image entirely, so it runs at CI cost alone" (seam_benchmark.py:184).
  • single panoramas only, so it "cannot exercise multi-frame registration; that regression stays on the app's own run 7 numbers plus StitchBench" (seam_benchmark.py:33-35).
  • a .mat whose arrays cannot be told apart is skipped, "rather than guessed at: a wrong mask silently poisons every downstream metric" (seam_benchmark.py:63-65).
  • a seam map of the wrong size is reported as an error, not stretched: "a pipeline bug worth surfacing, not papering over" (seam_benchmark.py:207-209).
  • licence gotcha from the authors: the SPS data is non-commercial and must never ship (seam_benchmark.py:7-9).

tools/scratch/refine_chain_test.py — tiny no-I/O unit test of the offline stitcher's rotation fit and chain refinement

  • status: not vendored
  • inputs/outputs:
  • imports tools/offline_stitch/stitch_offline.py as so (outside this scope; camera_frame, pair_measured_rotation, refine_components exist at stitch_offline.py:267, 423, 454).
  • prints per-pair and per-frame errors, then "PASS", or fails an assertion.
lever value what it controls how to change
FW, FH 160.0, 120.0 synthetic frame size refine_chain_test.py:24
HFOV 65.0 synthetic FOV refine_chain_test.py:25
RNG seed 7 world rays refine_chain_test.py:55
ring 10 frames, yaw i·35° test geometry refine_chain_test.py:59
pitches [0,0,-12,0,6,0,0,-5,0,4] per-frame pitch refine_chain_test.py:60
world rays 3000 random unit directions correspondences refine_chain_test.py:67
front cut z > 0.1 projection refine_chain_test.py:43
min pair coverage > 30 shared rays assert refine_chain_test.py:77,87
yaw perturbations [3,-2,4,-3,2,1,-2.5,3.5,-1,0.5] starting guesses (deg) refine_chain_test.py:110-111
pitch perturbations [2,-1.5,3,-1,0.5,-2,1.5,1,-1,0.5] starting guesses (deg) refine_chain_test.py:112-113
max_deg 6.0 refine clamp passed to refine_components refine_chain_test.py:122
pass bar < 1.0° measured-vs-true per pair and closure; < 1.0° worst pairwise error after offset removal; < 1.0° first-two spread asserts refine_chain_test.py:98,104,139-141
  • authors' notes:
  • it checks that the Horn rotation fit recovers the true relative rotation, and that refine_chain + loop spreading lands every frame within a degree from perturbed guesses with noisy measurements (refine_chain_test.py:3-8). "Light by construction: dozens of tiny matrix solves." (refine_chain_test.py:10).
  • the 35° yaw step is chosen so that "the closure edge is real overlap" (refine_chain_test.py:57-58).
  • "The guesses are perturbed by up to 4 degrees, so the clamp has to allow at least that much for the chain to converge here." (refine_chain_test.py:119-120).
  • "The absolute orientation is a gauge … frame 0 keeps its guess and every other frame can only agree with it", so the assert strips the common offset (refine_chain_test.py:123-126).
  • our code reading: the closure pair is measured and asserted (refine_chain_test.py:99-104) but is not passed into refine_components. Only the 9 consecutive edges are (refine_chain_test.py:116-122), and the spread callback is the identity lambda ref, a, d: ref (refine_chain_test.py:121). Not verified by running.
  • the docstring says the measurements "carry noise", but the code builds the correspondences from exact projections with no added noise (refine_chain_test.py:6-8 vs 70-78; our reading).

lessons from all 310 of their commits

engine reference — lessons from all 310 of their commits

part of the engine reference (master_doc/engine/). written 2026-11-26 by reading every file of our copy (commit 16eb526) against theirs (b5796d7), plus their docs, tests, tools and commit history. line numbers point at our code at 16eb526; the floor-photo commits after it (eff5cd1, 022767a) shift a few. levers were read from the code, not tried on the phone. start at master.md -> "if something goes wrong with the camera".

source: docs/photosphere-upstream/history/commits.md (310 commits, github.com/theclumsypirate/photosphere-android, newest first). we vendored b5796d7 (2026-11-23). everything below is paraphrased from commit messages only; nothing was checked against code. many commits are title-only (no body) and are catalogued from the title alone.


newer than our copy

  • 3035b6e · 2026-11-25 — Remove fisheye debug R&D UI and projection foundation. reverts what b5796d7 added: the debug "Capture fisheye" entry and screens, and the LensProjection abstraction in stitching/geometry; "restore default pinhole+radial stitching path"; reason given only as "per request". matters: yes, structurally. our copy carries the LensProjection groundwork that upstream threw away. b5796d7's own message says it preserved default pinhole+radial behaviour, so runtime output should be unchanged, but our geometry/stitch code now diverges from upstream head (any future upstream sync will conflict here, and the abstraction is dead R&D code upstream no longer maintains). unverified against code.
  • d68a1c4 · 2026-11-25 — Add debug-only stitch harness lab. home-screen "Harness tests" entry (debug) + activity/screen that imports or loads capture frames, runs several stitch configurations, auto-scores results and swipe-compares the equirectangular outputs. release gets a no-op stub; no release behaviour change. matters: not to the engine at runtime; useful as a method (A/B several configs on the same frames and score) if we tune stitch settings.
  • 997af42 · 2026-11-25 — Add debug harness camera capture flow. debug-only harness camera screen reusing the normal PhotoSphere capture flow; "Capture with camera" loads the captured session's frames into the harness. matters: debug tooling only.
  • b5b95a4 · 2026-11-25 — Auto-run full harness after debug camera capture. after a harness capture, frames load and the full suite runs automatically; harness configs now include the debug colour-frame stitch modes, and colour-debug results are marked diagnostic (never best-photo candidates). matters: debug tooling only.
  • 524e864 · 2026-11-25 — Fix Little Planet crash on non-equirectangular import. rejects non-2:1 imports before setting the source bitmap; preview/save conversion wrapped in runCatching so failures show feedback instead of crashing. matters: only if we ship the Little Planet editor (not part of capture+stitch).

timeline

  • 2026-08-02 — scaffold (AGP 8.7.3 / Kotlin 2.0.21, minSdk 26), rotation-vector orientation tracker, guided capture (44 targets, auto shutter), frame buffer + OpenCV Stitcher attempt, GPano XMP + gallery export, CI (PRs #1-#5).
  • 2026-08-03 — OpenCV Stitcher replaced by an orientation-driven equirectangular renderer (stitching module absent on Android); AGP 9.3 / Kotlin 2.2; AE/AWB/focus lock + burst-of-two.
  • 2026-08-04 — the big stitch-quality day: ORB pose refinement, lens distortion, exposure compensation, S23 profile, ring/sphere scope, pivot model, FOV reconciliation, tap-to-focus, two distortion-unit fixes, the pose-matrix transpose bug, multiband blending, graph-cut seams, focal refinement.
  • 2026-08-05 – 08-06 — SphereCaptureCoordinator (capture vs undo serialised), camera-bind retry, AE/AWB converge-before-lock, pose carried as rotation matrix (zenith), handedness fix.
  • 2026-08-13 — one design system, permission-cancel bug, discard confirmation, docs; stop committing APKs.
  • 2026-09-25 — any-order capture, game rotation vector (no magnetometer), per-shot burst poses, seam wrap at ±180°, merge of capture-quality-s23.
  • 2026-10-13 — overlay anti-flicker/smoothing, JSON logging, photo import, pano_proto scored prototype loop (all36 to 9/10), winner-takes-all seams, signed release workflow, v0.0.1-beta, settings diagnostics report.
  • 2026-10-14 — restitch loop v1-v13 (Balanced / Crisp / Careful), person/object orbit walk, v0.0.2-beta, README work.
  • 2026-10-15 – 10-16 — Samsung S21 64 MP / ultrawide tests (debug), pinhole gap fill, Careful restitch uses refinement; orbit lab with ML Kit / MediaPipe; video screen added and removed.
  • 2026-10-17 – 10-19 — closed-loop pano lab (62-frame virtual stairs grid), debug stairs grid capture → renamed Extended capture, on-phone stitch of the grid, gyro-less marker fix, 2048 default + 4096 rerun.
  • 2026-10-21 – 10-22 — Material You, lag tracker, orbit code moved out of build, extended-capture AE/AWB lock, offline-stitcher gain/blend/vignette options, release workflow repairs (v0.0.3-beta, v0.0.4-beta, reset, v0.0.3-beta), API-35 crash fix, pose report.
  • 2026-10-26 – 10-28 — debug A/B round (moving-object mask, block exposure, graph pruning, APAP-lite local warp, OKLab seam cost, solved-FOV baking, 3.0 m pivot), SPS seam benchmark, offline stitcher (EXIF poses, SIFT/MagSAC/Horn, SuperGlue, pose-neighbour pairs, FOV precedence, content-only + OpenStitching attempts).
  • 2026-10-30 — v0.0.5-beta; release build + lens model restored, lens distortion kept behind the debug switch; open 360 photos from other apps.
  • 2026-11-07 – 11-09 — Little Planet and GPano editors, night mode, HUD dropdown, debug/release gating flip-flops.
  • 2026-11-10 – 11-12 — C++ OpenCV 360 stitcher as debug backend, a run of CMake/AGP DSL fixes, v0.0.6-beta, then C++ stitcher removed from main.
  • 2026-11-13 — README.
  • 2026-11-23 — fisheye debug UI + LensProjection groundwork (b5796d7, our vendored point).
  • 2026-11-25 — fisheye reverted; debug stitch harness lab; Little Planet crash fix.

lessons by area

sensors / orientation

  • first tracker: TYPE_ROTATION_VECTOR (fused, no manual filtering) → getRotationMatrixFromVector → yaw/pitch/roll StateFlow; events on a private HandlerThread with reused scratch buffers; listening tied to composition lifecycle so the gyro is never left on in background (29464a8, 2026-08-02)
  • remapCoordinateSystem applied twice: once for display rotation, once for a "Camera" reference (AXIS_X/AXIS_Z) because Android's default "level = screen flat" puts an upright phone at pitch -90, the gimbal-lock pose, which is exactly how a sphere is shot; Camera reference moves the singularity to straight up/down (29464a8, 2026-08-02)
  • HIGH_SAMPLING_RATE_SENSORS declared for >200 Hz attitude; it is a normal permission so excluded from the runtime request (41c3985, 2026-08-02)
  • bug: the remap + getOrientation shortcut produced angles that did not match the axis construction SphereProjection/CameraBasis use; a level pan was reported as roll with yaw pinned near zero, so every ring frame landed on one longitude, each rotated differently; fix reads angles straight off the device-to-world matrix as the exact inverse of that construction (9026359, 2026-08-04)
  • bug: CameraBasis.fromRotationMatrix read rows where toRotationMatrix wrote columns (a transpose); every level frame's forward collapsed to due north, all frames stacked on longitude 0 — "the sensor poses were correct all along; the pipeline dropped the yaw" (2b986e8, 2026-08-04)
  • shutter was gated on isUsable, which stranded indoor users whose compass never reached medium accuracy; now only Unreliable blocks, since the plan is anchored on the starting bearing so a miscalibrated magnetometer shifts every target together at no cost (de3ba4e, 2026-08-04)
  • read sensor accuracy off each event, because many HALs never call onAccuracyChanged (de3ba4e, 2026-08-04)
  • a truncated/malformed rotation vector is skipped instead of throwing on the sensor thread (de3ba4e, 2026-08-04)
  • pose window cleared after each capture so the next frame's pose cannot average two aims (de3ba4e, 2026-08-04)
  • refuse the shutter while the fused sensor reports unreliable; stamp each frame with the dwell-window mean pose (946c988, 2026-08-04)
  • pose-window leak: samples aimed at the previous target could survive into the first pose mean after a stitch; fixed (d260a3f, 2026-08-04)
  • samples taken while the fused sensor calls itself unreliable no longer enter the pose-averaging window; a walked-out plan clears the window so a later undo cannot average stale samples (39cbef7, 2026-08-05)
  • pose carried as a rotation matrix so stitching survives the zenith (title only) (56de257, 2026-08-06)
  • handedness bug: camera (right, up, forward) is left-handed (up = right × forward), so matrices built from it had det = -1; quaternion mean (dwell averaging) and rotation refinement assume proper rotations and silently came out ~90° wrong for every frame; exchange format now carries right-handed [right, -up, forward] (c21a8f8, 2026-08-06)
  • RotationMath.angle used acos of the trace, which turns roundoff into a phantom 2e-8 rad angle for identical matrices; now atan2(sin, cos) with skew-derived sine (c21a8f8, 2026-08-06)
  • switched capture attitude to the game rotation vector (gyro + accel, no magnetometer), "as Street View and GCam's Photo Sphere do": indoors the compass could jump a still phone's heading by degrees, misplacing frames; shutter no longer waits on a figure-eight calibration (b857ef3, 2026-09-25)
  • OrientationTracker logs full 50 Hz VERBOSE attitude + 1 Hz INFO summary (e99b45a, 2026-10-13)
  • overlay draws a snap-limited smoothed pose (OrientationSmoother) so noise and tremor stop shaking markers; capture decisions and stamped poses keep raw samples (d99d427, 2026-10-13)
  • pole lesson from the prototype: wild pole rolls came from Euler collapse; the app's cameraBasis matrices already dodge it (c91426a, 2026-10-13)
  • orbit targets/hints/voice had an inverted pitch convention; fixed (title only) (d6a7153, 2026-10-16)
  • gyro-less phones (Honor 90 Lite): attitude falls back to geomagnetic rotation vector whose yaw jumps several degrees between samples; the overlay's 3° snap test passed jumps through so the marker wandered; samples now carry isGyroAssisted=false and the display smoother runs a short window median + slightly heavier average before the snap; gyro phones untouched; display-only (26351bd, 2026-10-17; documented in KNOWN_ISSUES 6fcc927, 2026-10-17)
  • stairs grid convention: negative pitch is up (b27021c, 2026-10-17)
  • debug stairs walk gates the shutter on compass accuracy like SphereCaptureCoordinator (c3339f5, 2026-10-17)
  • camera basis matrix appended to EXIF UserComment (debug) so offline tools get full orientation at the poles where yaw/pitch collapse (9861bd5, 2026-10-27)
  • Kotlin stores pitch "negative above horizon" (elevation = -pitch); C++ expected positive = up; poses.json writer negates pitch (b5dbdbe, 2026-11-10; 83ee6d7, 2026-11-10)
  • shot yaw/pitch/roll must be read via frame.pose.<angle>, not frame.<angle> (dfbadac, 2026-11-12)

lens & field of view

  • target markers use the same rectilinear projection the lens performs; focal length from the camera's reported optics with a fallback when the camera will not describe itself (16e7d1d, 2026-08-02)
  • read the device's intrinsic calibration for accurate FOV; Lanczos resampling (946c988, 2026-08-04)
  • describe the lens actually streaming: FOV had been read from a guessed camera id and the sensor array, which on a three-lens phone can describe the ultrawide while the main lens shoots (targets nearly twice too far apart, no overlap); now optics re-read from the bound camera2 id (edd3dc5, 2026-08-04)
  • two independent FOV estimates (intrinsic calibration vs pre-correction array, and sensor geometry) are reconciled; the calibration is discarded past a 25% disagreement (edd3dc5, 2026-08-04)
  • main lens picked out of a logical camera's focal lengths by diagonal FOV, not list order (edd3dc5, 2026-08-04)
  • FOV cropped to the stream's aspect; Preview and ImageCapture both pinned to 4:3 so one number describes viewfinder and stills (edd3dc5, 2026-08-04)
  • android.util.Log is a throwing stub in JVM unit tests, so logging inside reconcileFieldOfView made the key case untestable; decision kept pure, caller logs (eb9902a, 2026-08-04)
  • stitcher self-checks FOV against the first decoded frame and swaps the angles if implied focal lengths disagree more than a real lens could (9026359, 2026-08-04)
  • a swapped FOV was corrected for render but not for refinement — the pose graph was still built from transposed angles; fixed (de3ba4e, 2026-08-04)
  • LENS_DISTORTION units, attempt 1: pipeline treated coefficients as pixel-space and rescaled them UP by (calibrationEdge/decodedEdge)^2n; k1 -0.02 became -0.08 and the corner radial factor computed to -124,999 instead of ~0.97, so nothing painted, coverage fell below the 0.2% floor and stitch failed "Too little of the scene"; fix divides each term by (decodedLongestEdge/2)^(2n), k1 -0.02 → -2e-8 (8de6f6e, 2026-08-04)
  • LENS_DISTORTION units, attempt 2 (supersedes attempt 1): LENS_DISTORTION normalizes by focal length; the deprecated LENS_RADIAL_DISTORTION normalized by the array's farthest edge and that was the convention the code applied; the two differ by (f/halfEdge)^(2n) per term (>2× on k1, >10× on k3); RadialDistortion now carries the unitless polynomial converted against the working frame's focal length via FrameIntrinsics.forLens (de3ba4e, 2026-08-04)
  • radial distortion then defaulted off, pending a convention check: the S23's coefficients are large and of atypical sign; "the pinhole stitch is the reliable core either way" (2b986e8, 2026-08-04)
  • focal length refined from matched bearings alongside poses (title only) (276c2ed, 2026-08-04)
  • pose-graph overlap test bounded separation by tan(fov), negative past 90°, so every pair was rejected on a wide lens — and the default profile preferred the widest rear camera, so refinement and gain compensation were silently off on exactly that hardware (de3ba4e, 2026-08-04)
  • overlap bound corrected to 2·tan(fov/2) (b857ef3, 2026-09-25)
  • auto-pick: Extended capture picked the widest back lens so a sphere needs fewer frames (ed7d93f, 2026-10-18); later reversed to bind the default back camera directly, dropping the manual lens switch, wide-lens note and widest-lens selector (add8eb1, 2026-10-19)
  • orbitCameraFieldOfView reads the shortest focal length the bound camera id lists — on a logical rear camera that is the ultrawide, so a note could record a FOV never shot; now records the stitch's own optics.fieldOfView (d186d07, 2026-10-17)
  • FOV grows with the physical axis, so the longer image side takes the larger reading; portrait = landscape rotated; virtual 3:4 set is 49 × 63° (3015400, 2026-10-17)
  • frame size recorded upright (EXIF rotation applied) to match the offline tool (d186d07, 2026-10-17)
  • the camera reports the whole active array but guided stills are cropped output: a run solved its focal at 1186 px on an 857 × 1142 decode = 39.730 × 51.444° where the camera claimed 49.297 × 62.918°; a plan laid on the reported FOV leaves less overlap than intended and pushes the shortfall into the refiner; solve rescales FOV per axis behind a debug flag + device prefix match (b6923f9, 2026-10-26)
  • offline: EXIF focal 4.266 mm on a 1/2.55" sensor ≈ 65° FOV; the reprojection-metric FOV scan on sliver matches kept voting for an artificially small FOV, so --auto-fov became opt-in (81acad7, 2026-10-28)
  • bake capture FOV into each frame's EXIF UserComment (;hfov=..;vfov=.., debug) because guessing from sensor size made a 48° session render at 65° (ca63fe4, 2026-10-28)
  • offline FOV precedence: frame ;hfov/;vfov comment, then capture_debug.json, then --hfov scaled by aspect; render and refinement use the exact h/v pair instead of re-deriving vertical from aspect; pose-neighbour radius and FOV scan follow that horizontal; a calibrated session skips the scan (d6dace0, 2026-10-28)
  • explicit --hfov overrides EXIF and sidecar; default unset; --auto-fov still scans even with baked FOV, to cross-check a wrong calibration (56f3eb7, 2026-10-28)
  • offline default 48° horizontal: the render the user kept was made at 48 and frames the room correctly; 65° stretched the room and looked too close; 39.7° (the debug build's calibration) leaves a stretched band along the bottom; so the capture's stamped FOV is no longer the default; --fov-from-exif opts back in (7feddae, 2026-10-28)
  • lens model restored on the shipping path (title only) (19a6cc1, 2026-10-30); then lens distortion kept behind the debug A/B switch, off in release (fb92072, 2026-10-30)
  • fisheye LensProjection groundwork added (b5796d7, 2026-11-23), removed (3035b6e, 2026-11-25)

capture plan & guidance

  • first plan: 44 targets on rings at 0, ±30, ±60° elevation; yaw spacing widened by 1/cos(elevation); rings alternate direction; plan rotated to the user's starting bearing (16e7d1d, 2026-08-02)
  • roll rotates markers with the scene but is excluded from the distance measure (16e7d1d, 2026-08-02)
  • AlignmentGate: 2° held for 300 ms; any sample outside the window clears the timer; trigger consumed so a steady hand does not fire twice (16e7d1d, 2026-08-02)
  • ±60° plan covers 360 × 120° (b53dd38, 2026-08-02)
  • adaptive target rings covering the poles for any vertical FOV; 35% overlap (946c988, 2026-08-04)
  • MIN_FRAMES 6 → 3 and coverage floor 2% → 0.2%: frames are placed by measured pose so the pipeline never needed a chain of matches (edd3dc5, 2026-08-04)
  • ring scope (horizon only, a dozen-odd frames) vs sphere; plan records ring start/end so the HUD can offer stitch at a closed band; plan spends 90% of reported FOV (edd3dc5, 2026-08-04)
  • ring/sphere selection dropped: plan always walks the whole sphere, coverage inferred from frames, stitch any time (4790132, 2026-08-04)
  • main-lens frames came back with no shared view: plan spent the full FOV at 35% overlap and a high FOV estimate pushed targets past each other; overlap target 35% → 50% of FOV, plan spends 80% of claimed FOV; equator spacing ~30° → ~21° on a ~52° lens, vertical ring step ~39° → ~26° (1ca1068, 2026-08-04)
  • GCam-style reticle: large ring that warms toward accent as aim closes, dwell arc on its rim; targets as circles (hollow to-do, filled green done); live target as pulsing ring with guide line; Street View-style undo drops newest frame and re-targets it (d260a3f, 2026-08-04)
  • sphere/ring modes back as a HUD toggle, canvas sized to mode (2:1 sphere, band-trimmed strip for ring); overlap 50% → 35%, FOV safety factor 80% → 90%, because FOV now comes from the bound lens's calibration: ~32% fewer frames per ring at ~41% real overlap (8f9608e, 2026-08-04)
  • capture rule + run position moved into SphereCaptureCoordinator (no camera/Compose, unit-tested); capture, undo and "start over" all go through one lock; undo during a shutter is refused (button dims); a capture returning after restart/undo is discarded by token (39cbef7, 2026-08-05)
  • any-order capture: aiming within 6° of an uncaptured dot claims it; after a shot the nearest gap takes over, biased to the plan's path; undo takes back the most recent shot; adaptive rings run horizon, up, then down; stitched sphere centred on the first shot's bearing (b857ef3, 2026-09-25)
  • target selection reads captured indices under the coordinator lock so a sample queued behind an undo cannot steer the reticle off the undone target; exposure-lock gate = onSample(canTrigger): reticle holds, shutter waits; plan anchor saved across recreation (7e1fe42, 2026-09-25)
  • target-claim hysteresis + clamped edge marker stop overlay flicker (62fe360, 2026-10-13)
  • hold hint waits 400 ms before dropping so gate flapping stops strobing text (d99d427, 2026-10-13)
  • shutter gate needs the first AE lock, not a held lock (2b84445, 2026-10-13)
  • orbit walk dwell 4° / 500 ms, MediaPipe init moved to background (title only) (18590fc, 2026-10-16)
  • 62-point reference grid: five rows of ten bearings at 36° plus six zenith and six nadir caps (b27021c, 2026-10-17)
  • debug grid walk: target overlay + reticle, tap-to-focus, compass-accuracy gate, resume across recreation by reading captured set from disk, wait for pose sidecars before stitching, ring progress, spoken/beeped next target, burst-and-keep-sharpest with pose at each shot's own shutter, on-screen message when camera refuses to bind (c3339f5, 2026-10-17)
  • extended capture: 62-point grid when the bound lens matches it, else production's FOV plan generator (ed7d93f, 2026-10-18)
  • debug target plan types: Full Sphere, Horizon Ring, Tiny Planet, Asteroid, Freeze Frame, Surrounding, Three Steps, Forward Overturn (4c3b670, 2026-11-10)
  • SHOT_POSE_TOLERANCE_DEGREES exists as a top-level const (ea91935, 2026-11-10)

shutter / burst / focus / exposure (capture side)

  • capture confirmed with system shutter sound + haptic tick (16e7d1d, 2026-08-02)
  • lock AE/AWB/focus to the converged values so frames do not re-meter (exposure/colour seams); infinity focus where possible, one-shot focus lock otherwise; each target burst twice, sharpest kept (c521acd, 2026-08-03)
  • S23: burst three (946c988, 2026-08-04)
  • focus parked at infinity read as blur on anything nearer than the horizon; phones have fixed aperture so focus is the variable; tap-to-focus holds that distance for the whole session; until first tap the lens holds the centre of the first scene; FIXED_INFINITY/LOCK_ON_FIRST collapse into FOCUS_POINT (4790132, 2026-08-04)
  • frame captured while Finish was tapped was silently dropped; startStitch waits for the in-flight shutter (c21a8f8, 2026-08-06)
  • saveFrame reported success when commitBestFrame dropped a superseded-session frame, skipping a target never captured (c21a8f8, 2026-08-06)
  • let AE/AWB converge before locking so the night viewfinder brightens (d26cf2c, 2026-08-05)
  • each burst shot records its own pose at onCaptureStarted (a sharper later shot was stamped with the first shot's aim); sharpness scored on frame centre at the stitch's ~2000 px input size, not a 320 px thumbnail where handshake blur was invisible (b857ef3, 2026-09-25)
  • 3A convergence gate on main (7e1fe42, 2026-09-25)
  • shutter flash limited to once per 1.5 s (chained captures strobed white); EV slider + AE lock toggle in HUD (2b84445, 2026-10-13); white shutter flash then removed entirely (6477d67, 2026-10-13)
  • extended capture: per-frame auto exposure leaves a brightness step at every ownership border = a fan of light/dark wedges across a flat ceiling; AE and AWB locked once the walk starts, released when the screen goes; non-camera2 camera runs as before; debug only (1dde4f2, 2026-10-21)
  • night mode: debug HUD toggles night burst; EV unchanged (36b6d97, 2026-11-09); compatibility via Camera2 hardware level 3 + burst capability, "Night mode (unsupported)" otherwise (37ee332, 2026-11-09); made available in release (c029e07, 2026-11-09)
  • NightFrameMerger had OpenCV resize/types/submat/meanStdDev bugs; NightCaptureExtensions coroutine/callback flow fixed (5c540e9, 2026-11-09)
  • shutter sound removed (3e8198c, 2026-11-09)

device-specific

  • Galaxy S23: SphereDeviceProfile captures on the 50 MP main camera, bursts three, stitches 2000 → 6144 with light sharpening (946c988, 2026-08-04)
  • S23: LENS_DISTORTION coefficients large and of atypical sign → distortion defaulted off (2b986e8, 2026-08-04)
  • S23: capture-quality-s23 branch (any-order capture, per-shot burst poses, game rotation vector) merged (7e1fe42, 2026-09-25)
  • Samsung: 64 MP high-res test and ultrawide toggle (6adeaa0, 2026-10-15)
  • S21: capabilities and Samsung vendor-keys dump (50a89cc, 2026-10-15)
  • SamsungHighRes: probe returns Result; unsupported session pre-check dropped (d4fe4fb, 2026-10-15)
  • S21 bits gated behind debug builds (ac01b1e, 2026-10-15)
  • Samsung full-sensor limit documented with upstream tracker link (title only) (0b72f8c, 2026-10-16)
  • Honor 90 Lite (no gyroscope): marker wander from magnetometer yaw jumps; median smoother (26351bd, 2026-10-17)
  • solved-lens FOV applied by device prefix match (b6923f9, 2026-10-26)
  • SphereDeviceProfile.forDevice() takes a Context (c029e07, 2026-11-09)
  • no commit mentions Motorola, MediaTek or any Pixel/Xiaomi device

pose refinement / matching

  • ORB features between overlapping frames, per-frame pose corrections on top of sensor rotations, sensor as anchor and fallback (946c988, 2026-08-04)
  • PoseRefiner applies the pivot referral to its bearings so pure-rotation RANSAC solves a problem that is one (edd3dc5, 2026-08-04)
  • MIN_MATCHES 24 → 16, MIN_INLIERS 16 → 12 for sparse/low-texture scenes; sensor-deviation guard still rejects disagreeing pairs (1ca1068, 2026-08-04)
  • overlap judged directionally (aim projected into the other camera frame, within one FOV on both axes) instead of a widest-FOV distance that matched portrait frames with no shared horizontal view (9026359, 2026-08-04)
  • one DescriptorMatcher per pass, not per pair (de3ba4e, 2026-08-04)
  • pose refinement defaulted off: its pure-rotation model breaks on a body-swivel capture of a close scene (frames relate by parallax), where it moved frames off the sensor pose and softened every seam (2b986e8, 2026-08-04)
  • prototype: stock cv2.Stitcher crashes on 7 texture-poor frames and builds a single viewpoint, not a sphere; true-pose spherical stitch scored v1 5.5, v2 7.5, v3 8.5 (fb7dfc4, 2026-10-13)
  • prototype: v4 ECC corrected 1 frame but left a black wedge (c91426a, 2026-10-13)
  • walking data_set: 1540-pair ORB graph shows forward translation (~130 px/frame, rot 0), not rotation; repetitive pavers + translation break the rotation model; no sphere exists in that data (3712b76, ec18a59, 2026-10-13)
  • restitch v13: refinement "refused by data" (title only) (d42ca11, 2026-10-14)
  • Careful restitch uses feature refinement; standard path unchanged (c5d69bf, 2026-10-15)
  • grid stitch deliberately uses measured poses with no refinement "so a bad grid cannot be quietly corrected"; frames missing a sidecar are dropped, not guessed (5be8de7, 2026-10-17)
  • reference stitch placed on planned grid coordinates instead of drifting sensor yaw/pitch, then refined with production PoseRefiner — "what makes a phone run align like the script that had exact coordinates" (21a8055, 2026-10-19)
  • refinement now logs accepted vs matched pairs, since a low count alone could not distinguish a sparse overlap graph from matching that rejected everything (b414bf3, 2026-10-22)
  • debug graph pruning (Brown & Lowe weak-node): frames with no accepted overlap edge dropped, capped at a quarter of the run or four frames; gains remapped to kept order (11623d9, 2026-10-26)
  • debug APAP-lite LocalWarp: per-frame cell mesh from RANSAC inlier residuals, smoothed, clamped at 2% of long edge, added before the radial push (11623d9, 2026-10-26)
  • debug selectLargestComponent (OpenCV leaveBiggestComponent): edge confidence = inliers / (8 + 0.3 × matches), threshold 1, keep biggest component, but keep whole run if that component is under half of it; LocalWarp splats residuals bilinearly over four cell centres (2cac94f, 2026-10-27)
  • offline: without EXIF attitudes, guessed poses showed as shifted objects, broken overlaps, content vanishing at seams; added SIFT/AKAZE on consecutive pairs + ring closure, MagSAC homography outlier gate, inliers → rays, Horn exact pair rotation, chain + spread loop-closure residual; FOV scanned by smallest total residual (2bf1d94, 2026-10-27)
  • offline: Lowe ratio loop crashed (TypeError) on rich frames by unpacking the first DMatch then indexing it; pair best/second explicitly (62249fa, 2026-10-27)
  • offline SuperPoint/SuperGlue backend: 2048 keypoints, NMS radius 5, outdoor weights, 0.9 match threshold, same MagSAC/Horn/chain path; never vendored because the sources carry a proprietary banner (e7d1547, 2026-10-27)
  • offline: on a five-row sphere, consecutive files are not sphere neighbours — consecutive-only graph failed on 22 of 36 edges; pairs now from seeded poses within 80% of FOV; refined poses clamped within 6° of seed so texture-poor bands cannot drag the structure (81acad7, 2026-10-28)
  • clamp became --refine-max (6° default) so a gentler run can be asked for (d6dace0, 2026-10-28)
  • --refine-max default moved to 3° to match the kept render (7feddae, 2026-10-28)
  • content-only rebuild (drop all poses, identity seeds, match every pair, biggest component, clamp 180°): chains 26 of 37 frames and comes out incoherent — plain walls match each other and the unseeded chain follows false pairs; the seeded run matches 32 pairs and frames the room — "the case for the EXIF seed" (077e745, 2026-10-28)
  • OpenStitching (pixels only) cannot hold the multi-row sphere: keeps only the biggest component, or fails camera adjustment when all are connected; kept for flat pans/comparison (077e745, 2026-10-28)
  • synthetic chain test must set its clamp explicitly because default moved to 3° while it perturbs seeds by 4° (077e745, 2026-10-28)
  • C++ stitcher (debug): ORB, bundle adjustment, wave correction, spherical warp, multiband (819ec18, 2026-11-10)

exposure / gains

  • ExposureCompensation equalises per-frame brightness over the overlap graph (946c988, 2026-08-04)
  • gain compensation solves over adjacency arrays and clamps a runaway gain (de3ba4e, 2026-08-04)
  • gain compensation was silently disabled on wide lenses by the tan(fov) bug (de3ba4e, 2026-08-04)
  • multiband blending: broad illumination fades across the whole overlap, fine detail across a few pixels (fa30235, 2026-08-04)
  • closed-loop lab stitch uses no gain because virtual frames share one exposure by construction (d969bba, 2026-10-17)
  • real 62-frame walk frames disagree in exposure; WTA shows that as a fan of wedges; offline options: robust per-frame gain, feather only where every covering frame is flat, radial vignette correction; default untouched (33f58b7, 2026-10-21)
  • lock AE/AWB for the walk so borders have nothing to disagree about (1dde4f2, 2026-10-21)
  • debug per-block exposure: 64-block canvas-wide grid per frame refines scalar gains from what overlaps measured in the same block, shrunk toward neutral, clamped to the same 1.6 rail, bilinear per-pixel multiplier; exposure steps the whole-frame mean could not see (gains spread 0.840 to 1.379 on run 7) become gradual instead of bands; solve failure falls back to scalar gains (d64cc06, 2026-10-26)
  • C++ LOGI had dereferenced min/max_element iterators to Shot objects; logs gains via ->gain (dfbadac, 2026-11-12)

seams & blending

  • first renderer: feathered weighted mean so seams cross-fade (73594bb, 2026-08-03)
  • masked unsharp pass on the finished canvas (946c988, 2026-08-04)
  • feather could go positive for pixels the frame never saw: both factors go negative outside the frame and distortion can pull a pixel back in; two negatives → positive weight, one negative → subtracts colour; factors clamped in a unit-tested featherWeight (de3ba4e, 2026-08-04)
  • feather cubed by hand rather than Math.pow per pixel per frame (de3ba4e, 2026-08-04)
  • Burt-Adelson multiband (Laplacian) blending replaces feathered mean, because the wide cross-fade doubled misaligned edges at high contrast; numerical pitfalls: recovered Laplacian sum scaled by WSum_l / EXPAND(WSum_{l+1}) so uncovered pixels divide by nothing; banded upsample sized to the band so odd canvas heights stay in bounds (fa30235, 2026-08-04)
  • graph-cut seam carving: each pixel to the one frame that agrees best with neighbours, fade only a few px across each cut; energy = data term (frame closest to covering frames' mean) + seam cost (how differently two frames see the pixels); missing frames filled with the pixel mean so the cost is a metric and alpha-expansion subproblems are submodular; exact s-t min-cut (Dinic); frames downsampled to ~512 px; JVM-tested against exhaustive search (8ad8721, 2026-08-04)
  • seams and feathering wrap across the ±180° meridian (b857ef3, 2026-09-25)
  • WTA prototype: other_v1 (lever 0) 8/10, no ghosts but seam smears where poses disagree; other_v2 (lever 0.35) 8.5/10; neither beats feather v5's 9; "content-aware seams are the union of both" (ade681d, 2026-10-13)
  • pole core-selection: steep frames get only their sharp centre → 9/10 with clean zenith, readable nadir; "winner-take-all pole ownership beats averaging" (c91426a, 2026-10-13)
  • Kotlin WTA seams: argmin border penalty (optical-centre closeness) per grid node, same narrow SeamFeather crossfade; SeamMode Blend / Carve / WinnerTakeAll (eda048b, 2026-10-13); selectable on import (8e96fdf, 2026-10-13)
  • restitch loop v1-v7: "ghost-free room panorama" (title only) (e9012d7, 2026-10-14)
  • v8: multiband finish, smooth ceiling (title only) (4ca1915, 2026-10-14)
  • v9-v11: "stove back via global graph cut" (title only) (79833a4, 2026-10-14)
  • v12: critic fixes, pole bands and wrap (title only) (bba3e21, 2026-10-14); v12 fixes (d42ca11, 2026-10-14)
  • result screen restitch as Balanced / Crisp / Careful (title only) (679952a, 2026-10-14)
  • fill pinhole gaps on near-complete spheres instead of black slivers (title only) (4815e04, 2026-10-15)
  • closed-loop lab: pure WTA + agreement-gated crossfade on ownership borders reconstructed the source at MAD 1.83/255 (eye band 1.90), 100% coverage, zero structural defects (d969bba, 2026-10-17)
  • grid stitch uses WTA painting rather than cross-fade, matching the proven prototype (5be8de7, 2026-10-17)
  • exact script crossfade: walk every owner, take border pixels in a 9×9 zone, blend 50/50 in float against the best other frame, repeat at junctions in ascending owner order; float canvas then truncate (old port blended each border pixel once with integer average) (6ae61e3, 2026-10-18)
  • a near object lands in a different place in each frame → doubles under WTA (33f58b7, 2026-10-21)
  • debug moving-object mask: grid nodes whose gain-corrected covers disagree past a 90-point RGB distance are "seen-through"; they read the mean colour on every cover so the cut crosses a moving person for free instead of snaking around it (d64cc06, 2026-10-26)
  • debug OKLab seam cost: colours and node means converted in place, scaled to the RGB budget, graph cut in perceptual space (2cac94f, 2026-10-27)
  • SPS dataset seam benchmark (CI only, GPL page terms keep it out of the APK): scores seam maps by share of human-segmentation-boundary crossings (bda10c9, 2026-10-26)
  • offline WTA recipe: feather weights, one winner per pixel, blurred crossfade across winner changes, wrap crossfade at the meridian (c502b34, 2026-10-27)

pivot / parallax

  • PivotModel: lens on a lever ahead of the turning axis (holding the phone out and turning on the spot); lever is parallel to the optical axis so referral costs one subtraction in the renderer's inner loop (edd3dc5, 2026-08-04)
  • body-swivel close scenes relate by parallax not rotation; pure-rotation refinement made it worse (2b986e8, 2026-08-04)
  • WTA lever 0 vs 0.35: lever validated (ade681d, 2026-10-13)
  • lab cuts virtual frames through the exact pivot camera model (rays from lens, scene sphere centred on pivot) (d969bba, 2026-10-17)
  • shipped HandheldBodySwivel = 0.35 m over 10 m; prototype pivot = 0.35 m over 3.5 m; production can be cautious because PoseRefiner absorbs the residual, but with refinement off a close room bends at the seams (d186d07, 2026-10-17)
  • debug pivot scene distance pulled in to 3.0 m (pilot room ~3 m away; shipped profile nominally 10 m); release untouched (8a140dd, 2026-10-26)
  • pivotFor needs a Context (7b11e51, 2026-11-09)

geometry & projection

  • Android OpenCV has no stitching module, so the renderer uses measured poses: SphericalGeometry (camera basis, canvas↔direction, footprint by walking the frame border, handles ±180 straddle and poles), every output pixel a direction rotated into each frame and divided by depth (73594bb, 2026-08-03)
  • footprint test walks all 120,000 pixels of a frame across 72 attitudes (73594bb, 2026-08-03)
  • EquirectangularFit (later removed) did not stretch: ±60° capture = 360 × 120°, stretching puts pixels at wrong latitude (b53dd38, 2026-08-02)
  • geometry/footprints/renderer take a longitude/latitude span and centre, not a fixed 360 × 180; ring tagged in GPano as CroppedArea* slice (8f9608e, 2026-08-04)
  • ring latitude span could exceed GPano's 180° ceiling and throw, discarding the render; clamped (c21a8f8, 2026-08-06)
  • viewer mapped every canvas as a full sphere, stretching ring bands vertically; renderer derives latitude span from canvas aspect (uSpanLat) (80c429f, 2026-10-13)
  • flat preview left showing black wedges deliberately: "the honest picture of what was captured" (5483353, 2026-08-13)
  • frame decoding: CameraX records rotation in EXIF rather than applying it; rotate upright first (b53dd38, 2026-08-02)
  • EXIF rewrite silently dropped ORIENTATION; now read and written back; a frame still transposed vs its pose is rotated into portrait using sensor-derived rotation (2b986e8, 2026-08-04)
  • EXIF ORIENTATION_UNDEFINED treated as missing so the portrait-rotation fallback applies (62fe360, 2026-10-13)
  • Little Planet: non-2:1 input must be rejected (524e864, 2026-11-25)

memory / performance

  • frame buffer keeps paths + metadata, pixels on disk (forty-odd full-res bitmaps = several hundred MB heap); decode subsampled to 1024 px (b53dd38, 2026-08-02)
  • renderer accumulates in horizontal bands: a few MB vs ~100 MB for a full float canvas (73594bb, 2026-08-03)
  • unsharp mask ran on four full-canvas buffers (~200 MB native at 6144 wide); now bands against one copy, identical result (de3ba4e, 2026-08-04)
  • renderer reuses per-segment scratch (was tens of MB per band) (de3ba4e, 2026-08-04)
  • overlay builds camera basis once per draw, targets cache their direction (a plan = a few hundred markers at display rate) (de3ba4e, 2026-08-04)
  • multiband accumulated band by band, full-canvas only for small coarse levels (fa30235, 2026-08-04)
  • graph cut frames at ~512 px, working set a few MB (8ad8721, 2026-08-04)
  • attitude read inside the draw lambda so sensor rate invalidates drawing, not recomposition (16e7d1d, 2026-08-02)
  • grid stitch decodes at 1024 px not 2000: stitcher holds every frame at once, 62 frames vs ~33 normal; a ring still carries ~7500 px around 360° for a ~5500 px canvas (5be8de7, 2026-10-17)
  • Python reference kept every warped frame float64: ~4 GB at 2048, 16 GB at 4096; streaming winner + second-best + border-sized buffer; byte-identical at 2048 (c3205b6, 2026-10-18)
  • on-phone: 2048 default, 4096 rerun behind warning (lots of RAM, >5 min); second-best keeps an index not an image; crossfade on border-sized float buffer; debug manifest requests large heap (098946d, 2026-10-18)
  • Material You flag lived above the theme so each flip invalidated the whole tree incl. camera preview; moved into one observable holder (80c4afa, 2026-10-21); palette read once per composition (efe9bc4, 2026-10-21)
  • lag log measured gap since last frame, so background returns read as 6 s / 8 s / 2.8 s freezes; now measures lateness vs due time (607be2b, 2026-10-21)
  • LagTracker (debug) writes each >50 ms frame to the JSON log immediately (in-memory list died with the process) (b414bf3, 2026-10-22)
  • SystemClock.uptimeNanos is API 35+; app minSdk 26 → NoSuchMethodError on first frame on Android 14; use System.nanoTime (714e288, 2026-10-22)
  • Little Planet/GPano decode bounded to 4096 px via inSampleSize ("Canvas: trying to draw too large bitmap", 128 MB+) (9df1564, 2026-11-07)
  • frames and cache: wipe cached pictures after backgrounding (2b734d6, 2026-10-14); auto-clean cached photos after one hour (be9810c, 2026-10-18)

output / GPano / export

  • GPanoXmpInjector writes eight GPano properties into an APP1 XMP segment by walking JPEG markers — no decode/re-encode; replaces existing XMP; scan bytes identical (dc316c1, 2026-08-02)
  • MediaExporter: Pictures/360Panoramas via MediaStore (pending row, byte copy, publish on API 29+; DATA indexing on 26-28); byte copy keeps GPano intact (dc316c1, 2026-08-02)
  • SphereImageStore writes EXIF first, GPano last (dc316c1, 2026-08-02)
  • new sphere built under a temp name and atomically swapped (old code deleted the last good sphere before encoding, and a failed GPano rewrite could destroy output); delete-then-rename windows replaced by Files.move(REPLACE_EXISTING) (c21a8f8, 2026-08-06)
  • session ids gain millisecond precision so a config change within a second cannot mix sessions (c21a8f8, 2026-08-06)
  • exports fail loudly instead of leaving pending rows; orphaned spheres pruned at launch; unused READ permissions dropped (b857ef3, 2026-09-25)
  • frame attitude in EXIF UserComment seeds the stitcher (16e7d1d, 2026-08-02); FOV and basis appended in debug (ca63fe4, 9861bd5)
  • EXIF read back after saveAttributes() to catch silently dropped tags (debug) (1d8dd77, 2026-10-28)
  • reference raw written with Imgcodecs.imwrite quality 95; org.opencv:opencv:4.12.0 carries imgcodecs, not org.opencv.stitching (c0ff7b2, 2026-10-18)
  • frames survive stitch for opt-in per-photo export (30fcf23, 2026-10-13)
  • open 360 photos from other apps in the viewer (32126c8, e427e36, 2026-10-30)

UI / accessibility

  • RequirePermissions: plain denial vs "don't ask again", re-check on resume (41c3985, 2026-08-02)
  • cancelled permission dialog delivers an empty map and emptyMap().values.all{} is vacuously true → black viewfinder; grant now asked of the system; cancel routes to retry, not Settings (5483353, 2026-08-13)
  • "New photo" beside "Share" and back both deleted the only copy; now confirm while unexported (5483353, 2026-08-13)
  • disabled selector still clickable; pass enabled to the Surface (5483353, 2026-08-13)
  • status bar pinned to light icons; progress pill speaks one sentence to screen readers; one palette, dark always, Material You off so it cannot repaint the two signal colours (5483353, 2026-08-13)
  • guided capture still cannot be driven without sight (b4d6b12, 2026-08-13)
  • failed camera bind → retry card (39cbef7, 2026-08-05)
  • welcome card removed (8efa9e6, 2026-10-21)
  • Material You switch: debug (30fcf23, 2026-10-21) → release on Android 12+, off by default (9464860, 2026-10-22); app keeps its own neutrals to avoid cold-start dark flash (c6f03e1, 2026-10-21)
  • result screen: column scrolls, preview 16:9, diagnostics collapsed (8c3d2e0, 2026-10-13)
  • FRAMES pill removed; dropdown centred (37ee332, 2026-11-09)
  • crash log line was Romanian; now English, original throwable still rethrown (a97cea2, 2026-10-17)

build / CI / release

  • AGP 8.7.3 → 9.3.1, Gradle 8.14.3 → 9.5.0, Kotlin 2.0.21 → 2.2.10 (52a7b7c, 2026-08-03; b4d6b12, 2026-08-13)
  • ABI split creates no per-ABI install task; installDebug only (db66a5c, 2026-08-02)
  • Kotlin 2.2 removed stdlib toFloatArray/toDoubleArray used in a test (c21a8f8, 2026-08-06)
  • OpenCV debug APK ~43 MB; stop committing APKs (b4d6b12, 2026-08-13)
  • CI arm64-only via -PonlyAbi, manual/PR only (62fe360, 2026-10-13)
  • R8: keep JNI natives + SourceFile/LineNumberTable (d63174f, 2026-10-13); mapping.txt check dropped (5a058fa, 2026-10-13)
  • applicationId com.n30dyn4m1c.photosphere → theclumsypirate.com.photosphere.github (aefe494, 2026-10-13)
  • release workflow committed/tagged before build so cancelled runs burned 0.0.2 → 0.0.4; now tag only after success (bad3b27, 2026-10-22)
  • jarsigner check looked in workspace not temp folder → false "password mismatch" (050e231, 2026-10-22)
  • add-mask on secret-store values rejected "Invalid format" (68ff120, 2026-10-22)
  • AGP 9 ignores kotlin.exclude; files moved to app/orbit-disabled/ (f7c4679, 2026-10-21); removing the source-set block gave an empty compile classpath (7edda11) — later found the real cause was a nested /* in a comment glob (383eea8, d4a3ef5, 2026-10-21)
  • Lint deliberately out of CI; tools/scratch/audit_new_api.py replaces the NewApi check (714e288, 2026-10-22)
  • Gradle build cache disabled in CI (504ad30, 2026-11-07)
  • C++ build: CMake args DSL churn (2913d28 → 51d8f76 → 44fcc29 → a7f575a → 38fbfc0 → 15dde5b → 90db65f, 2026-11-10); -DANDROID_STL=c++_shared (1aa5f4d); prefab OpenCV (3b7866e); JNI return jobject (9997649); pickFirst **/libc++_shared.so (9d34885, 2026-11-12)
  • C++ poses.json parsing read file paths as a space (whitespace/quote skipping) (1715498, 2026-11-12)
  • DebugTargetPlans must live in src/debug with a release stub (9d34885, 2026-11-12)
  • local functions cannot carry private; const cannot be inside a function (2ebd3e9, 8196b26, ea91935)

debug tools

  • OrientationDebugScreen (29464a8, 2026-08-02); debug A/B toggles: distortion, refinement, solid-colour frames (2b986e8, 2026-08-04)
  • tools/photosphere_lab.py (2b84445, 2026-10-13); JSON logs (c1d777d, 2026-10-13); single PhotoSphere tag (ac9cecf, 2026-10-13)
  • settings diagnostics report (c1c0723, 2026-10-13)
  • view360.py / build_360.py (80c429f, 2026-10-13); pano_proto loop (fec4ebe, 2026-10-13)
  • check_overlap.py + overlap_viewer.py ghost-pair checker (d969bba, 2026-10-17)
  • pose report from EXIF (1496e2d, 2026-10-22)
  • offline stitcher stack (c502b34 … 077e745, 2026-10-27/28)
  • stitch harness lab (d68a1c4, 997af42, b5b95a4, 2026-11-25)

reverted or abandoned

  • OpenCV Stitcher PANORAMA (b53dd38, 2026-08-02) → replaced (73594bb, 2026-08-03): no stitching module on Android
  • EquirectangularFit → removed (73594bb)
  • distortion via edge normalisation (8de6f6e) → focal normalisation (de3ba4e) → default off (2b986e8) → off in release (fb92072)
  • pose refinement default on → off (2b986e8, 2026-08-04): parallax
  • ring/sphere choice: added (edd3dc5) → dropped (4790132) → re-added (8f9608e)
  • overlap 35% → 50% → 35% (946c988, 1ca1068, 8f9608e)
  • FIXED_INFINITY / LOCK_ON_FIRST focus → FOCUS_POINT (4790132): blur
  • magnetometer rotation vector → game rotation vector (b857ef3): indoor compass jumps
  • white shutter flash rate-limited (2b84445) → removed (6477d67)
  • shutter sound added (16e7d1d) → removed (3e8198c)
  • splash screen (53cfcd5) → dropped (dbe42d9)
  • F-Droid listing (8bbb855) → dropped (c1ba77f)
  • orbit / person-object walk with ML Kit / MediaPipe (Oct 14-16) → excluded (4d5bf8e) → moved out of build (f7c4679); pose_landmarker_lite.task deleted (a668834)
  • debug video screen (c6b2324) → removed (41e18f9)
  • widest-lens auto-pick (ed7d93f) → main-lens only (add8eb1)
  • welcome card removed (8efa9e6); FRAMES pill removed (37ee332)
  • RELEASE_PAT workflow → GITHUB_TOKEN (ffce934)
  • --auto-fov default → opt-in (81acad7)
  • content-only rebuild + OpenStitching (077e745): did not hold the sphere
  • prototype ECC (c91426a): black wedge; WTA alone (ade681d): below feather v5
  • v13 refinement refused by data (d42ca11)
  • SuperGlue never vendored (e7d1547): licence
  • C++ OpenCV stitcher (819ec18) → removed (8e5076a, c25cc21, 15daf83, 2026-11-12): no reason stated
  • fisheye + LensProjection (b5796d7) → reverted (3035b6e): "per request"
  • 65° and 39.7° offline defaults rejected for 48° (7feddae)