Skip to content
Draft
117 changes: 117 additions & 0 deletions agents/HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,3 +427,120 @@ source filtering, timeouts and the actual refused-port error. Positive discovery
with a real currently advertising ADB service is still unverified. These source
changes are a development preview, not a newly verified TV capture release;
alpha.3 remains the published Windows download.

## 2026-11-30 failed-start recovery guard

Reviewed current main and the latest successful build runs. Alpha.3 remains
the latest Windows release; the later direct mDNS discovery commit is source
and CI-artifact only. The owner reports Wireless debugging may simply have
been off and is retrying alpha.3 with it enabled. That is not yet confirmation
of a successful connection or capture. Do not interfere with that live test.

Fixed a separate host lifecycle bug: a failed explicit Start previously left
`wanted=True`, allowing the watchdog to repeat failed connection/filesystem
setup. Explicit Start now cleans up and stays stopped on startup failure,
preserving its diagnosis. A new explicit Start resets the recovery budget;
automatic recovery retains its existing bounded budget. Invalid configuration
is rejected before stopping a currently running stream.

Validation: 26 unit/HTTP tests passed on Windows, including five new startup
regressions. No app, capture or recording was launched on this PC. This change
has not passed a packaged live TV test and is not a new release.

## 2026-11-30 Windows green corruption and console windows

The owner re-enabled Wireless debugging and connected successfully with alpha.3.
Their screenshot shows about 28 fps but a heavily corrupted green preview, plus
two blank Windows terminal windows after Start. Current local runtime logs also
contain H.264 slice/decode errors. Successful frame counting is not image health.

A read-only probe over the existing authorized connection reproduced byte
corruption: remote printf emitted bytes 0 through 255; Windows `adb shell -T`
returned 257 bytes, replacing LF with CRLF, while `adb exec-out` returned all 256
unchanged. This is a confirmed transport defect, not evidence of a bad raw NV12
layout. No capture or recording was started for the probe. Both raw audio and
H.264 must use exec-out on Windows. Other platforms retain shell-v2. The shared
selection is in media_pipeline.adb_stream_args; tools/check-adb-transport.py
repeats the exact-byte live check without TV file writes or capture.

The capture worker also lacked CREATE_NO_WINDOW on its ADB/FFmpeg children.
Applied it to setup, streaming, diagnostics and cleanup calls, and handled
ConnectionAbortedError as a normal disconnected preview client.

Validation: 29 unit/HTTP tests and JavaScript syntax/diff checks passed. The fixed
production transport passed the live 256-byte probe on Windows. Full packaged
picture/audio and hidden-console validation remain outstanding; do not call
this a verified capture release.

Additional validation for code commit b70a6e3: 3,634 bytes of synthetic H.264
were emitted by TV printf and returned unchanged through the selected Windows
transport; the production FFmpeg conversion decoded all 12 test frames without
errors. Everything stayed in memory; no capture, recording or TV file writes.
Windows Actions job in run 46447978598 passed unit tests, packaged dependency/
HTTP/worker/media/ADB smoke tests, native-window shutdown regression and ZIP
upload. The downloaded ZIP passed integrity checks and its capture_engine.py
exactly matched tested source. This is a development artifact on PR #1, not a
published release. The owner still needs to verify the real picture, audio,
absence of child console windows and Stop/Start with that artifact.

## 2026-11-30 cancellation and worker identity follow-up

Owner is available in chat but away from the TV, and requested continued work.
Keep the earlier restriction against starting capture/recording on this PC.

Stop now signals startup cancellation before waiting on the manager lock.
Startup checks that signal after connection/setup operations and before/after
worker startup, so a pending Stop cannot be overwritten by a late wanted=True.
The worker serializes media-child creation and termination with CaptureChildren;
once Stop begins, no new FFmpeg/ADB media child can be added. Exited children
are reaped, with a bounded forced-exit fallback. Worker startup checks stop
between remote staging operations.

Startup and status also require the worker's unique session ID to match the
manager's current session. A stale worker on the preview port cannot report a
successful new start or supply healthy frame counters for another session.

Validation: 35 unit/HTTP tests passed on Windows. New tests exercise actual
thread interleavings during blocked connection, TV mkdir and child creation,
plus rejection of a foreign worker during startup/status. All subprocess and
TV operations in these regressions are mocked; no capture was started.
Development version is 0.1.0-dev.20261130.3. Packaged validation is next;
live picture/audio and 60 fps remain unverified.

Updated Windows Actions job in run 46449268530 passed all packaging, smoke,
HTTP, dependency, worker/media/ADB and native shutdown checks at code commit
2db5db4. Its downloaded development ZIP passed archive integrity and its worker
source matched the tested checkout exactly. This supersedes the earlier
b70a6e3 development artifact. No release/tag was published and no local app,
capture or recording was started. Live picture/audio validation remains open.

## 2026-11-30 live follow-up: source-dependent corruption

The owner confirmed dev3 still showed a badly corrupted picture, then explicitly
authorized short controlled capture diagnostics on this PC. Run one session at
a time and verify cleanup; do not change TV inputs or settings for these tests.
The owner controls the input and later provided an unprotected Xbox screen.

Stock NV12 and the normal adapter initially returned corrupt pixels before
encoding. RGB produced clean settings-menu pictures, so an RGB conversion
experiment was compiled with the official NDK and the TV's existing libyuv.
However, the owner was changing between the Apple TV and other screens during
those comparisons. On the subsequent Xbox test BOTH NV12 and RGB produced clean
pictures. The earlier inference that RGB fixed the problem was not established.
RGB code/default and its temporary native build workflow are reverted from the
final implementation. Do not add a slower RGB path as a purported protection fix.

The Apple TV/HDMI 2 corruption is source-dependent and consistent with content
protection, but actual HDCP state was not read or proven. No secure capture,
policy change or protection bypass was attempted. A healthy frame counter does
not establish a valid image. Apple TV remains unresolved; preserve this limit.

Exact Windows dev3 artifact (2db5db4) was compared against the installed EXE,
worker and native library byte-for-byte, then tested on the owner's unprotected
Xbox dashboard. Three bounded whole-TV Start/Stop cycles passed: 720p received
28.61 fps at 120 frames; 1080p received 25.69 fps at 121 frames; 720p received
28.18 fps at 122 frames. Snapshots from all three cycles were visually clean.
Each running session had one capture process; every Stop left zero. Quit closed
host, worker and private ADB ports. These short dashboard runs do not establish
gameplay cadence, long-term stability, frame uniqueness, HDR fidelity or audio.
Capture is stopped. Private screenshots/logs stayed local and are not committed.
97 changes: 65 additions & 32 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import argparse,array,atexit,errno,http.server,ipaddress,json,os,pathlib,re,runpy,secrets,shutil,subprocess,sys,threading,time,urllib.parse,urllib.request,webbrowser
from desktop_lifecycle import ViewerLeases,own_windows_children,session_cleanup_command,audio_cleanup_command
from adb_discovery import discover_at
from media_pipeline import adb_stream_args
ROOT=pathlib.Path(getattr(sys,'_MEIPASS',pathlib.Path(__file__).resolve().parent))
if '--capture-worker' in sys.argv:
sys.argv=[str(ROOT/'capture_engine.py')]+sys.argv[sys.argv.index('--capture-worker')+1:]
Expand All @@ -17,7 +18,7 @@ def binary(name):
DATA.mkdir(parents=True,exist_ok=True)
os.environ['SHARPCAPTURE_LOG_DIR']=str(DATA)
CONFIG=DATA/'settings.json';TOKEN=secrets.token_urlsafe(24)
VERSION='0.1.0-dev.20261130.1'
VERSION='0.1.0-dev.20261130.3'
# Each app uses its own local ADB server, never a remote/shared host.
os.environ['ADB_SERVER_SOCKET']='tcp:15037'
ADB_USED=False
Expand Down Expand Up @@ -61,6 +62,7 @@ def __init__(self):
except (OSError,ValueError):pass
self.settings['rate']='30'
self.capture_remote=None
self.cancel_start=threading.Event()
self.previous_session=None
self.last_failure=''
try:self.previous_session=json.loads(SESSION_FILE.read_text(encoding='utf-8'))
Expand Down Expand Up @@ -106,7 +108,8 @@ def connect(self,address,save=True):
self.error=''
return address
def stop(self,reset=True):
if reset:self.wanted=False
if reset:
self.wanted=False;self.cancel_start.set()
with self.lock:
if reset:self.wanted=False
if self.audio:
Expand Down Expand Up @@ -140,7 +143,7 @@ def cleanup_owned_capture(self):
if SESSION_FILE.exists():SESSION_FILE.unlink()
self.capture_remote=None
except Exception:pass
def start(self,config):
def start(self,config,recovery=False):
with self.lock:
if SHUTTING_DOWN.is_set():raise RuntimeError('SharpCapture is closing.')
v={**self.settings,**{k:config[k] for k in self.settings if k in config}};endpoint(v['device'])
Expand All @@ -149,50 +152,80 @@ def start(self,config):
if v['rate']!='30':raise ValueError('60 fps is not yet verified; use the stable 30 fps mode.')
if not isinstance(v['switch_input'],bool):raise ValueError('Invalid input preference')
if not FFMPEG:raise RuntimeError('FFmpeg is missing. Use the complete app download.')
if not recovery:
self.cancel_start.clear()
self.retries=0;self.last_retry=0;self.last_failure=''
try:
self._start(v)
except Exception as error:
# A rejected manual Start must not schedule background retries.
# Only recovery of an established stream keeps that intent.
self.stop(reset=not recovery)
self.error=str(error);self.last_failure=str(error)
raise
def check_start_cancelled(self):
if self.cancel_start.is_set() or SHUTTING_DOWN.is_set():
raise RuntimeError('Capture start cancelled.')
def _start(self,v):
with self.lock:
self.stop(reset=False)
self.check_start_cancelled()
if self.capture_remote:raise RuntimeError('The previous TV session could not be stopped. Check the TV connection and press Stop again.')
self.settings=v;self.error='';self.wanted=True
self.connect(v['device'],save=False)
self.check_start_cancelled()
if self.previous_session:
old=self.previous_session
if str(old.get('device','')).split(':')[0]==v['device'].split(':')[0]:
self.adb('-s',v['device'],'shell',session_cleanup_command(old.get('path','')),timeout=5)
self.adb('-s',v['device'],'shell','rm -rf '+old['path'],timeout=5)
self.previous_session=None
self.check_start_cancelled()
# Dedicated private temporary directory; never modify the vendor executable.
self.remote='/data/local/tmp/sharpcapture-audio-'+secrets.token_hex(6)
try:
self.adb('-s',v['device'],'shell',f'mkdir -p {self.remote}')
self.adb('-s',v['device'],'push',str(ROOT/'assets'/'sharp_audio'),self.remote+'/sharp_audio')
self.adb('-s',v['device'],'shell',f'chmod 700 {self.remote}/sharp_audio')
if v['source']!='tv' and v['switch_input']:
hw=int(v['source'])+1
self.adb('-s',v['device'],'shell','am','start','-a','android.intent.action.VIEW','-d',f'content://android.media.tv/passthrough/com.mediatek.tis%2F.HdmiInputService%2FHW{hw}','-n','com.google.android.tv.inputplayer/.player.PassthroughPlayerActivity')
width,height={'360':(640,360),'720':(1280,720),'1080':(1920,1080)}[v['quality']]
self.capture_remote='/data/local/tmp/sharpcapture-'+secrets.token_hex(6)
SESSION_FILE.write_text(json.dumps({'device':v['device'],'path':self.capture_remote}),encoding='utf-8')
args=['--capture-worker','--session',self.capture_remote,'--device',v['device'],'--source','tv' if v['source']=='tv' else 'hdmi','--hdmi',v['source'] if v['source']!='tv' else '3','--width',str(width),'--height',str(height),'--fps',v['rate'],'--port','18765','--duration','0']
command=[sys.executable]+([] if getattr(sys,'frozen',False) else [str(ROOT/'app.py')])+args
self.log=(DATA/'capture.log').open('ab',buffering=0)
self.proc=subprocess.Popen(command,stdout=self.log,stderr=self.log,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
for _ in range(40):
if self.proc.poll() is not None:raise RuntimeError('Capture could not start. See the capture log in '+str(DATA))
try:
with LOCAL_HTTP.open('http://127.0.0.1:18765/status',timeout=.3) as r:
state=json.load(r)
if state.get('error'):raise RuntimeError(state['error'])
if state.get('frames',0)>0:break
except (OSError,TimeoutError):pass
time.sleep(.25)
else:raise RuntimeError('No TV picture arrived. Check that the TV is on and a supported unprotected source is visible.')
CONFIG.write_text(json.dumps(v,indent=2),encoding="utf-8")
except Exception:self.stop(reset=False);raise
self.adb('-s',v['device'],'shell',f'mkdir -p {self.remote}')
self.check_start_cancelled()
self.adb('-s',v['device'],'push',str(ROOT/'assets'/'sharp_audio'),self.remote+'/sharp_audio')
self.check_start_cancelled()
self.adb('-s',v['device'],'shell',f'chmod 700 {self.remote}/sharp_audio')
self.check_start_cancelled()
if v['source']!='tv' and v['switch_input']:
hw=int(v['source'])+1
self.adb('-s',v['device'],'shell','am','start','-a','android.intent.action.VIEW','-d',f'content://android.media.tv/passthrough/com.mediatek.tis%2F.HdmiInputService%2FHW{hw}','-n','com.google.android.tv.inputplayer/.player.PassthroughPlayerActivity')
self.check_start_cancelled()
width,height={'360':(640,360),'720':(1280,720),'1080':(1920,1080)}[v['quality']]
self.capture_remote='/data/local/tmp/sharpcapture-'+secrets.token_hex(6)
SESSION_FILE.write_text(json.dumps({'device':v['device'],'path':self.capture_remote}),encoding='utf-8')
args=['--capture-worker','--session',self.capture_remote,'--device',v['device'],'--source','tv' if v['source']=='tv' else 'hdmi','--hdmi',v['source'] if v['source']!='tv' else '3','--width',str(width),'--height',str(height),'--fps',v['rate'],'--port','18765','--duration','0']
command=[sys.executable]+([] if getattr(sys,'frozen',False) else [str(ROOT/'app.py')])+args
self.log=(DATA/'capture.log').open('ab',buffering=0)
self.check_start_cancelled()
self.proc=subprocess.Popen(command,stdout=self.log,stderr=self.log,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
for _ in range(40):
self.check_start_cancelled()
if self.proc.poll() is not None:raise RuntimeError('Capture could not start. See the capture log in '+str(DATA))
try:
state=self.worker_status(timeout=.3)
if state.get('error'):raise RuntimeError(state['error'])
if state.get('frames',0)>0:break
except (OSError,TimeoutError):pass
time.sleep(.25)
else:raise RuntimeError('No TV picture arrived. Check that the TV is on and a supported unprotected source is visible.')
self.check_start_cancelled()
CONFIG.write_text(json.dumps(v,indent=2),encoding="utf-8")
def worker_status(self,timeout=1):
with LOCAL_HTTP.open('http://127.0.0.1:18765/status',timeout=timeout) as response:
state=json.load(response)
if not isinstance(state,dict) or not self.capture_remote or state.get('session')!=self.capture_remote:
raise RuntimeError('A different capture session is using the preview port. Close the other SharpCapture instance and try again.')
return state
def status(self):
s={'app':'SharpCapture','version':VERSION,'frames':0,'fps':0,'stopped':True,'error':self.error,'settings':self.settings,'recovering':self.recovering,'dependencies':{'adb':bool(ADB),'ffmpeg':bool(FFMPEG)}}
if self.proc and self.proc.poll() is None:
try:
with LOCAL_HTTP.open('http://127.0.0.1:18765/status',timeout=1) as r:s.update(json.load(r))
s.update(self.worker_status())
except OSError:pass
except (RuntimeError,ValueError) as error:s['error']=str(error)
return s
M=Manager()
def shutdown_host():
Expand All @@ -219,7 +252,7 @@ def watch_capture():
try:
if not M.wanted:continue
M.recovering=True;M.last_retry=time.monotonic();M.retries+=1
M.start({})
M.start({},recovery=True)
except Exception as e:M.error=str(e)
finally:M.recovering=False;M.lock.release()
threading.Thread(target=watch_capture,daemon=True).start()
Expand Down Expand Up @@ -258,7 +291,7 @@ def do_GET(self):
with M.lock:
if not M.wanted or not M.remote:self.send_error(409,'Start capture first');return
d=M.remote;cmd=f'echo $$ >{d}/audio.pid; SHARP_AUDIO_STEREO=1 SHARP_AUDIO_BLOCKS=36000 exec {d}/sharp_audio 4 10 1 </dev/null 2>{d}/audio.log'
proc=subprocess.Popen([ADB,'-s',M.settings['device'],'shell','-T',cmd],stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0);M.audio=proc
proc=subprocess.Popen([ADB,'-s',M.settings['device'],*adb_stream_args(),cmd],stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0);M.audio=proc
self.send_response(200);self.send_header('Content-Type','application/octet-stream');self.send_header('Cache-Control','no-store');self.end_headers()
while True:
b=proc.stdout.read(19200)
Expand Down
Loading