diff --git a/agents/HANDOFF.md b/agents/HANDOFF.md index 1be2872..9b1cd93 100644 --- a/agents/HANDOFF.md +++ b/agents/HANDOFF.md @@ -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. diff --git a/app.py b/app.py index 2bd6484..6c8c8c3 100644 --- a/app.py +++ b/app.py @@ -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:] @@ -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 @@ -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')) @@ -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: @@ -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']) @@ -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(): @@ -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() @@ -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 {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) diff --git a/capture_engine.py b/capture_engine.py index f0e5ee6..aa0d35d 100644 --- a/capture_engine.py +++ b/capture_engine.py @@ -3,9 +3,10 @@ Requires Python 3, adb, ffmpeg and the adjacent libsharp_loop.so. No APK, root, or TV setting changes. Tested on Sharp MT5896 Android 14. """ -from media_pipeline import preview_command -from desktop_lifecycle import session_cleanup_command,own_windows_children +from media_pipeline import preview_command,adb_stream_args +from desktop_lifecycle import session_cleanup_command,own_windows_children,CaptureChildren import argparse, re, collections, http.server, json, os, pathlib, shutil, signal, subprocess, threading, time, uuid +CHILD_FLAGS=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0 p=argparse.ArgumentParser(description=__doc__) p.add_argument('--session',help='Unique session path owned by the desktop host') p.add_argument('--fps',type=int,choices=[30,60],default=30) @@ -15,7 +16,7 @@ p.add_argument('--width',type=int,default=1280); p.add_argument('--height',type=int,default=720) p.add_argument('--port',type=int,default=8765); p.add_argument('--bind',default='127.0.0.1') p.add_argument('--mode',choices=['native','snapshot'],default='native') -p.add_argument('--transport',choices=['shell-v2','exec-out'],default='shell-v2',help='Binary non-PTY shell transport; exec-out is retained for comparison') +p.add_argument('--transport',choices=['shell-v2','exec-out'],help='Default: byte-preserving exec-out on Windows, non-PTY shell-v2 elsewhere') p.add_argument('--duration',type=int,default=600,help='Stop after this many seconds; 0 means unlimited') a=p.parse_args() if a.width<176 or a.height<144 or a.width>1920 or a.height>1080 or a.width%2 or a.height%2: p.error('Use even dimensions between 176x144 and 1920x1080') @@ -26,8 +27,8 @@ framebytes=a.width*a.height*3//2 source_args='-p 10' if a.source=='tv' else f'-E 0 -P {a.hdmi} -p 2' point=10 if a.source=='tv' else 0 -cv=threading.Condition(); stop=threading.Event(); latest=b''; count=0; arrivals=collections.deque(maxlen=60); error=''; started=time.monotonic(); procs=[]; remote_stopped=False -stop_lock=threading.Lock() +children=CaptureChildren() +cv=threading.Condition(); stop=children.stopped; latest=b''; count=0; arrivals=collections.deque(maxlen=60); error=''; started=time.monotonic(); remote_stopped=False def status(): with cv: fps=(len(arrivals)-1)/(arrivals[-1]-arrivals[0]) if len(arrivals)>1 else 0 @@ -37,22 +38,19 @@ def cleanup_remote(): global remote_stopped cmd=session_cleanup_command(remote) try: - result=subprocess.run([adb,'-s',a.device,'shell',cmd],timeout=5,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + result=subprocess.run([adb,'-s',a.device,'shell',cmd],timeout=5,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,creationflags=CHILD_FLAGS) remote_stopped=result.returncode==0 except Exception:pass def stop_capture(): - with stop_lock: - if stop.is_set(): return - stop.set() - # Unblock the media pipes before waiting for the TV. The native - # adapter handles EPIPE and SIGTERM by closing its own HAL handle. - for proc in procs: - if proc.poll() is None: proc.terminate() - cleanup_remote() - with cv: cv.notify_all() + # Child creation and termination share one lock. No child can be added + # after this cleanup begins, even if Stop arrives during startup. + if not children.terminate():return + cleanup_remote() + with cv: cv.notify_all() def capture(): global latest,count,error + if stop.is_set():return # stdin must be /dev/null: otherwise fd 0 is an adbd socket rejected by the vendor HAL. # Each command overwrites one raw frame; only a complete, size-checked frame is transmitted. cmd=(f'd={remote}; mkdir "$d" || exit 1; trap \'rm -rf "$d"\' EXIT HUP INT TERM; ' @@ -65,8 +63,10 @@ def capture(): if not lib.exists(): error='Missing libsharp_loop.so next to sharp_preview.py';stop_capture();return try: - subprocess.run([adb,'-s',a.device,'shell',f'mkdir -p {remote}'],check=True,timeout=10) - subprocess.run([adb,'-s',a.device,'push',str(lib),remote+'/libsharp_loop.so'],check=True,timeout=10,stdout=subprocess.DEVNULL) + subprocess.run([adb,'-s',a.device,'shell',f'mkdir -p {remote}'],check=True,timeout=10,creationflags=CHILD_FLAGS) + if stop.is_set():return + subprocess.run([adb,'-s',a.device,'push',str(lib),remote+'/libsharp_loop.so'],check=True,timeout=10,stdout=subprocess.DEVNULL,creationflags=CHILD_FLAGS) + if stop.is_set():return except Exception as e: error=str(e);stop_capture();return cmd=(f'd={remote}; ' @@ -82,11 +82,12 @@ def capture(): log.write(('\n--- Session '+remote+' ---\n').encode()) session_log_offset=log.tell() input_args=['-flags','low_delay','-probesize','32','-analyzeduration','0','-f','h264'] if a.mode=='native' else ['-f','rawvideo','-pixel_format','nv12','-video_size',f'{a.width}x{a.height}','-framerate','4'] - enc=subprocess.Popen(preview_command(ffmpeg,input_args),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log) - procs.append(enc) - transport=['shell','-T'] if a.transport=='shell-v2' else ['exec-out'] - cap=subprocess.Popen([adb,'-s',a.device,*transport,cmd],stdin=subprocess.DEVNULL,stdout=enc.stdin,stderr=log) - procs.append(cap); enc.stdin.close() + enc=children.start(preview_command(ffmpeg,input_args),stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,creationflags=CHILD_FLAGS) + if enc is None:return + transport=adb_stream_args(a.transport) + cap=children.start([adb,'-s',a.device,*transport,cmd],stdin=subprocess.DEVNULL,stdout=enc.stdin,stderr=log,creationflags=CHILD_FLAGS) + enc.stdin.close() + if cap is None:return buf=b'' while not stop.is_set(): chunk=os.read(enc.stdout.fileno(),65536) @@ -103,8 +104,9 @@ def capture(): except Exception as e: error=str(e) finally: stop_capture() + children.reap() try: - diagnostic=subprocess.run([adb,'-s',a.device,'shell',f'cat {remote}/native.log'],capture_output=True,timeout=5) + diagnostic=subprocess.run([adb,'-s',a.device,'shell',f'cat {remote}/native.log'],capture_output=True,timeout=5,creationflags=CHILD_FLAGS) with logpath.open('ab') as saved: saved.write(diagnostic.stdout) except Exception:pass if error: @@ -119,7 +121,7 @@ def capture(): except Exception:pass # Delete only this session's randomly named scratch directory. try: - if remote_stopped:subprocess.run([adb,'-s',a.device,'shell',f'rm -rf {remote}'],timeout=5,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + if remote_stopped:subprocess.run([adb,'-s',a.device,'shell',f'rm -rf {remote}'],timeout=5,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,creationflags=CHILD_FLAGS) except Exception: pass HTML='''Sharp HDMI preview

Sharp · HDMI preview

Experimental · video onlyConnecting…
''' class Handler(http.server.BaseHTTPRequestHandler): @@ -143,12 +145,12 @@ def do_GET(self): continue previous=count;data=latest self.wfile.write(b'--frame\r\nContent-Type: image/jpeg\r\nContent-Length: '+str(len(data)).encode()+b'\r\n\r\n'+data+b'\r\n');self.wfile.flush() - except (BrokenPipeError,ConnectionResetError): pass + except (BrokenPipeError,ConnectionResetError,ConnectionAbortedError): pass return else: self.send_error(404);return self.send_response(200);self.send_header('Content-Type',mime);self.send_header('Content-Length',str(len(data)));self.send_header('Cache-Control','no-store');self.end_headers() try: self.wfile.write(data) - except (BrokenPipeError,ConnectionResetError): pass + except (BrokenPipeError,ConnectionResetError,ConnectionAbortedError): pass def do_POST(self): # Local browser stop only; prevent cross-origin pages from triggering it. if self.path!='/stop': self.send_error(404);return diff --git a/desktop_lifecycle.py b/desktop_lifecycle.py index c1e413f..cc053e8 100644 --- a/desktop_lifecycle.py +++ b/desktop_lifecycle.py @@ -1,10 +1,42 @@ """Browser leases and Windows process ownership for the desktop host.""" import os import re +import subprocess import threading import time +class CaptureChildren: + """Serialize Stop with child creation so cleanup cannot miss a late child.""" + def __init__(self): + self.stopped = threading.Event() + self.lock = threading.Lock() + self.processes = [] + + def start(self, command, **options): + with self.lock: + if self.stopped.is_set():return None + child = subprocess.Popen(command, **options) + self.processes.append(child) + return child + + def terminate(self): + with self.lock: + if self.stopped.is_set():return False + self.stopped.set() + for child in self.processes: + if child.poll() is None: + try:child.terminate() + except ProcessLookupError:pass + return True + + def reap(self): + for child in self.processes: + try:child.wait(timeout=2) + except subprocess.TimeoutExpired: + child.kill();child.wait(timeout=2) + + def session_cleanup_command(path): return owned_cleanup_command(path,r'/data/local/tmp/sharpcapture-[0-9a-f]{12}','CaptureCmd.bin','capture.pid') diff --git a/media_pipeline.py b/media_pipeline.py index a4a3c6d..d3ac728 100644 --- a/media_pipeline.py +++ b/media_pipeline.py @@ -1,4 +1,15 @@ """Host video conversion. Re-time frames without duplicating or dropping pictures.""" +import os + + +def adb_stream_args(transport=None, windows=None): + """Preserve media bytes: Windows shell stdout translates LF into CRLF.""" + if windows is None:windows=os.name=='nt' + if transport is None:transport='exec-out' if windows else 'shell-v2' + if transport=='exec-out':return ['exec-out'] + if transport=='shell-v2':return ['shell','-T'] + raise ValueError('Unknown ADB stream transport') + def preview_command(ffmpeg,input_args): return [ffmpeg,'-hide_banner','-loglevel','error']+input_args+[ '-i','pipe:0','-map','0:v:0','-an','-vf','setpts=N/30/TB','-enc_time_base','1:30', diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py index 9eb3c45..c6eaa1a 100644 --- a/tests/test_lifecycle.py +++ b/tests/test_lifecycle.py @@ -4,7 +4,7 @@ import app class LifecycleTests(unittest.TestCase): def manager(self): - m=app.Manager.__new__(app.Manager);m.lock=threading.RLock();m.wanted=True;m.audio=None;m.proc=Mock(pid=42);m.proc.poll.return_value=None;m.capture_remote='/data/local/tmp/sharpcapture-012345abcdef';m.settings={'device':'tv.local:5555'};m.log=None;m.remote=None;m.adb=Mock(return_value='');return m + m=app.Manager.__new__(app.Manager);m.lock=threading.RLock();m.cancel_start=threading.Event();m.wanted=True;m.audio=None;m.proc=Mock(pid=42);m.proc.poll.return_value=None;m.capture_remote='/data/local/tmp/sharpcapture-012345abcdef';m.settings={'device':'tv.local:5555'};m.log=None;m.remote=None;m.adb=Mock(return_value='');return m def test_stop_cleans_tv_before_terminating_worker(self): m=self.manager();events=[] class Response: diff --git a/tests/test_media_transport.py b/tests/test_media_transport.py new file mode 100644 index 0000000..a37cbb7 --- /dev/null +++ b/tests/test_media_transport.py @@ -0,0 +1,24 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from media_pipeline import adb_stream_args + + +class MediaTransportTests(unittest.TestCase): + def test_windows_media_avoids_shell_stdout_translation(self): + self.assertEqual(adb_stream_args(windows=True), ['exec-out']) + + def test_other_platforms_keep_shell_v2(self): + self.assertEqual(adb_stream_args(windows=False), ['shell', '-T']) + + def test_explicit_diagnostic_transport_is_preserved(self): + self.assertEqual(adb_stream_args('exec-out', windows=False), ['exec-out']) + self.assertEqual(adb_stream_args('shell-v2', windows=True), ['shell', '-T']) + with self.assertRaises(ValueError): + adb_stream_args('invalid') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_start_cancellation.py b/tests/test_start_cancellation.py new file mode 100644 index 0000000..ce97120 --- /dev/null +++ b/tests/test_start_cancellation.py @@ -0,0 +1,104 @@ +import pathlib +import sys +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import app +from desktop_lifecycle import CaptureChildren + + +class StartupCancellationTests(unittest.TestCase): + def test_stop_during_connection_or_tv_setup_never_launches_worker(self): + for stage in ('connection', 'mkdir'): + with self.subTest(stage=stage), tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + with patch.object(app, 'CONFIG', root/'settings.json'), \ + patch.object(app, 'SESSION_FILE', root/'session.json'), \ + patch.object(app, 'FFMPEG', 'unused'), \ + patch.object(app.subprocess, 'Popen') as launch: + manager = app.Manager() + manager.settings['device'] = '192.0.2.1:40000' + entered = threading.Event() + release = threading.Event() + errors = [] + + def blocked(*args, **kwargs): + entered.set() + if not release.wait(3):raise RuntimeError('Test timed out') + return '' + + manager.connect = Mock(side_effect=blocked if stage=='connection' else None) + manager.adb = Mock(return_value='') + if stage=='mkdir': + def adb(*args, **kwargs): + if 'mkdir -p' in str(args):return blocked() + return '' + manager.adb.side_effect = adb + + def start(): + try:manager.start({}) + except RuntimeError as error:errors.append(str(error)) + + starter = threading.Thread(target=start) + stopper = threading.Thread(target=manager.stop) + starter.start() + try: + self.assertTrue(entered.wait(2)) + stopper.start() + self.assertTrue(manager.cancel_start.wait(2)) + finally: + release.set() + starter.join(3) + if stopper.ident is not None:stopper.join(3) + self.assertFalse(starter.is_alive()) + self.assertFalse(stopper.is_alive()) + self.assertEqual(errors, ['Capture start cancelled.']) + self.assertFalse(manager.wanted) + self.assertIsNone(manager.proc) + launch.assert_not_called() + + +class ChildCancellationTests(unittest.TestCase): + def test_stop_during_child_creation_includes_that_child(self): + children = CaptureChildren() + entered = threading.Event() + release = threading.Event() + child = Mock() + child.poll.return_value = None + + def launching(*args, **kwargs): + entered.set() + if not release.wait(3):raise RuntimeError('Test timed out') + return child + + with patch('desktop_lifecycle.subprocess.Popen', side_effect=launching) as launch: + starter = threading.Thread(target=lambda: children.start(['fake-media'])) + stopper = threading.Thread(target=children.terminate) + starter.start() + try: + self.assertTrue(entered.wait(2)) + stopper.start() + finally: + release.set() + starter.join(3) + if stopper.ident is not None:stopper.join(3) + self.assertFalse(starter.is_alive()) + self.assertFalse(stopper.is_alive()) + child.terminate.assert_called_once() + self.assertIsNone(children.start(['late-adb'])) + launch.assert_called_once() + + def test_stop_is_idempotent_and_prevents_first_child(self): + children = CaptureChildren() + self.assertTrue(children.terminate()) + self.assertFalse(children.terminate()) + with patch('desktop_lifecycle.subprocess.Popen') as launch: + self.assertIsNone(children.start(['fake-media'])) + launch.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_start_failures.py b/tests/test_start_failures.py new file mode 100644 index 0000000..fa8c548 --- /dev/null +++ b/tests/test_start_failures.py @@ -0,0 +1,74 @@ +"""Failed setup must stay stopped; recovery belongs to established streams.""" +import pathlib +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import app + + +class StartFailureTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + root = pathlib.Path(self.directory.name) + for name, value in [('CONFIG', root/'settings.json'), + ('SESSION_FILE', root/'session.json'), + ('FFMPEG', 'unused-ffmpeg')]: + patcher = patch.object(app, name, value) + patcher.start() + self.addCleanup(patcher.stop) + self.manager = app.Manager() + self.manager.settings['device'] = '192.0.2.1:40000' + self.manager.connect = Mock(return_value=self.manager.settings['device']) + self.manager.adb = Mock(return_value='') + + def test_connection_failure_stays_stopped_and_preserves_diagnosis(self): + self.manager.connect.side_effect = RuntimeError('Connection port changed') + with self.assertRaisesRegex(RuntimeError, 'Connection port changed'): + self.manager.start({}) + self.assertFalse(self.manager.wanted) + self.assertEqual(self.manager.status()['error'], 'Connection port changed') + self.manager.adb.assert_not_called() + + def test_invalid_settings_do_not_stop_an_existing_stream(self): + self.manager.wanted = True + with patch.object(self.manager, 'stop') as stop: + with self.assertRaisesRegex(ValueError, 'Unsupported quality'): + self.manager.start({'quality': 'invalid'}) + stop.assert_not_called() + self.assertTrue(self.manager.wanted) + + def test_failed_tv_setup_is_cleaned_and_not_retried(self): + self.manager.adb.side_effect = [RuntimeError('TV filesystem unavailable'), '', ''] + with self.assertRaisesRegex(RuntimeError, 'TV filesystem unavailable'): + self.manager.start({}) + self.assertFalse(self.manager.wanted) + self.assertIsNone(self.manager.remote) + self.assertIsNone(self.manager.proc) + self.assertEqual(self.manager.last_failure, 'TV filesystem unavailable') + + def test_explicit_start_gets_a_fresh_recovery_budget(self): + self.manager.retries = 3 + self.manager.last_retry = 123 + self.manager.last_failure = 'old encoder error' + with patch.object(self.manager, '_start'): + self.manager.start({}) + self.assertEqual(self.manager.retries, 0) + self.assertEqual(self.manager.last_retry, 0) + self.assertEqual(self.manager.last_failure, '') + + def test_automatic_recovery_keeps_its_budget_and_intent(self): + self.manager.wanted = True + self.manager.retries = 2 + self.manager.connect.side_effect = RuntimeError('TV temporarily unavailable') + with self.assertRaisesRegex(RuntimeError, 'TV temporarily unavailable'): + self.manager.start({}, recovery=True) + self.assertTrue(self.manager.wanted) + self.assertEqual(self.manager.retries, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_worker_identity.py b/tests/test_worker_identity.py new file mode 100644 index 0000000..f7b7da9 --- /dev/null +++ b/tests/test_worker_identity.py @@ -0,0 +1,66 @@ +import io +import json +import pathlib +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +import app + + +class WorkerIdentityTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + root = pathlib.Path(self.directory.name) + for name, value in [('CONFIG', root/'settings.json'), + ('SESSION_FILE', root/'session.json'), + ('DATA', root), ('FFMPEG', 'unused')]: + patcher = patch.object(app, name, value) + patcher.start() + self.addCleanup(patcher.stop) + self.manager = app.Manager() + self.manager.settings['device'] = '192.0.2.1:40000' + self.manager.connect = Mock() + self.manager.adb = Mock(return_value='') + + def response(self, value): + return io.BytesIO(json.dumps(value).encode()) + + def test_foreign_worker_cannot_make_start_succeed(self): + foreign = {'session': '/data/local/tmp/sharpcapture-ffffffffffff', + 'frames': 9000, 'fps': 30, 'stopped': False} + child = Mock() + child.poll.return_value = None + with patch.object(app.subprocess, 'Popen', return_value=child), \ + patch.object(app, 'terminate_worker') as terminate, \ + patch.object(app.LOCAL_HTTP, 'open', side_effect=lambda *a, **k: self.response(foreign)): + with self.assertRaisesRegex(RuntimeError, 'different capture session'): + self.manager.start({}) + self.assertFalse(self.manager.wanted) + self.assertIsNone(self.manager.proc) + terminate.assert_called_once_with(child) + + def test_foreign_or_malformed_status_cannot_report_healthy_frames(self): + self.manager.proc = Mock() + self.manager.proc.poll.return_value = None + self.manager.capture_remote = '/data/local/tmp/sharpcapture-012345abcdef' + for value in [[], {'session': 'foreign', 'frames': 9000, 'stopped': False}]: + with self.subTest(value=value), patch.object(app.LOCAL_HTTP, 'open', side_effect=lambda *a, **k: self.response(value)): + status = self.manager.status() + self.assertEqual(status['frames'], 0) + self.assertEqual(status['fps'], 0) + self.assertTrue(status['stopped']) + self.assertIn('different capture session', status['error']) + + def test_current_worker_status_is_accepted(self): + self.manager.capture_remote = '/data/local/tmp/sharpcapture-012345abcdef' + state = {'session': self.manager.capture_remote, 'frames': 42} + with patch.object(app.LOCAL_HTTP, 'open', return_value=self.response(state)): + self.assertEqual(self.manager.worker_status(), state) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/check-adb-transport.py b/tools/check-adb-transport.py new file mode 100644 index 0000000..dbc4a74 --- /dev/null +++ b/tools/check-adb-transport.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Optional live byte-integrity check. No capture, TV files or settings changes.""" +import argparse +import pathlib +import subprocess +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from media_pipeline import adb_stream_args + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--adb', default='adb') + parser.add_argument('--device', required=True) + parser.add_argument('--server-port', default='15037') + args = parser.parse_args() + expected = bytes(range(256)) + command = "printf '" + ''.join('\\%03o' % n for n in expected) + "'" + result = subprocess.run( + [args.adb, '-P', args.server_port, '-s', args.device, + *adb_stream_args(), command], + capture_output=True, timeout=10, + creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) + if result.returncode or result.stdout != expected: + raise SystemExit('FAIL: ADB did not preserve the 256-byte test payload.') + print('PASS: platform-default media transport preserved all 256 bytes exactly.') + + +if __name__ == '__main__': + main()