Repository navigation
Expand file tree
/
Copy pathVideoDepthRuntime.java
More file actions
287 lines (285 loc) · 15.3 KB
/
Copy pathVideoDepthRuntime.java
File metadata and controls
287 lines (285 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package dev.denver.dressroomadvanced;
import android.app.Application;
import android.app.KeyguardManager;
import android.content.*;
import android.graphics.Rect;
import android.graphics.Point;
import android.os.*;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
/** Opt-in runtime. No calibrated config = no rendering, no playback sampling. */
final class VideoDepthRuntime {
private static final String TAG = "OneUIDepthMask";
private static final Handler MAIN = new Handler(Looper.getMainLooper());
private static final Set<View> CLOCKS = Collections.newSetFromMap(new WeakHashMap<>());
private static final ExecutorService IO = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r,"OneUI-video-depth"); t.setDaemon(true); return t;
});
private static Context context;
private static boolean initialized, loading, enabled, inFlight;
private static long generation;
private static long confirmedAt, retryUntil;
private static long nextHashAttempt;
private static String lastStatus = "", lastWorkerStatus = "";
private static boolean applied;
private static String lastSamplePath;
// Worker-owned after initial load. Configuration is immutable until SystemUI restart.
private static Config config;
private static VideoMaskPack pack;
private static String verifiedPath;
private static long verifiedLength, verifiedModified;
private static boolean identityValid;
private static int preparedId = -1;
private static DepthEffects.PreparedVideo prepared;
private static volatile boolean staticPack, autoPackLoaded;
private static final VideoAutoClient AUTO = new VideoAutoClient();
private static final Runnable TICK = VideoDepthRuntime::tick;
private static final class Config {
final Rect crop, surface;
final int displayWidth, displayHeight;
Config(File dir) throws IOException {
File file = new File(dir,"config.properties");
if (!file.isFile() || file.length()>8192) throw new IOException("No opt-in configuration");
Properties p = new Properties();
try (InputStream in = new FileInputStream(file)) { p.load(in); }
if (!"true".equals(p.getProperty("enabled"))) throw new IOException("Disabled");
crop = rect(p,"crop",0,4096); surface = rect(p,"surface",-8192,8192);
displayWidth = VideoMaskPack.number(p,"display.width",1,4096);
displayHeight = VideoMaskPack.number(p,"display.height",1,4096);
}
private static Rect rect(Properties p,String prefix,int lo,int hi) throws IOException {
Rect r = new Rect(VideoMaskPack.number(p,prefix+".left",lo,hi),
VideoMaskPack.number(p,prefix+".top",lo,hi),
VideoMaskPack.number(p,prefix+".right",lo,hi),
VideoMaskPack.number(p,prefix+".bottom",lo,hi));
if(r.isEmpty()) throw new IOException("Empty "+prefix);
return r;
}
}
private VideoDepthRuntime() {}
static boolean renderEnabled() { return enabled || loading; }
private static void status(String message) {
if (!message.equals(lastStatus)) { lastStatus = message; Log.i(TAG, message); }
}
private static void workerStatus(String message) {
if (!message.equals(lastWorkerStatus)) { lastWorkerStatus = message; Log.i(TAG, message); }
}
// Called on the main looper from the actual Samsung video visibility hook.
static void nativeVisibilityChanged(boolean visible) {
if (!enabled) return;
if (visible) poke(100); else stop();
}
private static void poke(long delay) {
if (!enabled) return;
retryUntil = SystemClock.elapsedRealtime() + 10_000;
schedule(delay);
}
private static boolean lockInteractive() {
if (!enabled || context == null) return false;
try {
PowerManager pm = context.getSystemService(PowerManager.class);
KeyguardManager km = context.getSystemService(KeyguardManager.class);
return pm != null && km != null && pm.isInteractive() && km.isKeyguardLocked();
} catch (RuntimeException error) { return false; }
}
private static void retryIfWaiting() {
if (lockInteractive() && SystemClock.elapsedRealtime() < retryUntil) schedule(250);
}
static int displayWidth() { return config == null ? 1080 : config.displayWidth; }
static int displayHeight() { return config == null ? 2340 : config.displayHeight; }
static void watch(View v) {
if (Looper.myLooper()!=Looper.getMainLooper()) { MAIN.post(() -> watch(v)); return; }
if (!"com.android.systemui".equals(Application.getProcessName()) || !VideoAutoGeometry.supportedDevice()) return;
try { if (!DepthBinding.provider(v)) return; }
catch (RuntimeException | LinkageError error) { return; }
if (CLOCKS.add(v)) {
v.addOnLayoutChangeListener((view,l,t,r,b,ol,ot,or,ob) -> {
if (l!=ol || t!=ot || r!=or || b!=ob) poke(0);
});
Log.i(TAG, "VIDEO_CLOCK_WATCH " + v.getClass().getSimpleName());
v.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override public void onViewAttachedToWindow(View view) { poke(0); }
@Override public void onViewDetachedFromWindow(View view) { DepthEffects.clearVideo(view); if(!anyEligible()) { clear(); retryIfWaiting(); } }
});
}
if (!initialized && !loading) initialize(v.getContext());
else if (!applied) poke(0);
}
private static void initialize(Context host) {
loading = true;
try {
context = host.createPackageContext("com.android.systemui",0).createDeviceProtectedStorageContext();
} catch (Exception e) { initialized=true; loading=false; return; }
IO.execute(() -> {
boolean ok = false;
try {
File dir = new File(context.getFilesDir(),"oneui-depth");
config = new Config(dir); pack = new VideoMaskPack(new File(dir,"maskpack.zip"));
if(config.crop.right>pack.width || config.crop.bottom>pack.height) throw new IOException("Crop outside source");
staticPack = pack.unique==1;
ok = true;
} catch (Exception | LinkageError e) {
if(pack!=null) try {pack.close();}catch(IOException ignored){}
pack=null; config=null; Log.i(TAG,"VIDEO_LEGACY_PACK_UNAVAILABLE: "+e.getClass().getSimpleName());
}
final boolean available = ok;
MAIN.post(() -> {
loading=false; initialized=true;
try {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT);
context.registerReceiver(new BroadcastReceiver() {
@Override public void onReceive(Context c,Intent intent) {
if(Intent.ACTION_SCREEN_ON.equals(intent.getAction())) poke(150); else stop();
}
},filter,Context.RECEIVER_NOT_EXPORTED);
enabled=true;
try {
context.getContentResolver().registerContentObserver(VideoDepthBroker.URI,false,
new android.database.ContentObserver(MAIN) {
@Override public void onChange(boolean selfChange) { poke(0); }
});
} catch (RuntimeException error) { Log.i(TAG,"VIDEO_AUTO_OBSERVER_UNAVAILABLE"); }
poke(0);
if (available) Log.i(TAG,"VIDEO_DEPTH_PACK_READY");
Log.i(TAG,"VIDEO_AUTO_RUNTIME_READY");
} catch (RuntimeException e) { Log.w(TAG,"VIDEO_DEPTH_LIFECYCLE_UNAVAILABLE",e); }
});
});
}
/** Pure display check, safe to call from a draw hook. Keyguard verified by scheduler. */
static boolean drawable(View v) {
return displayEligible(v) && confirmedAt>0 && SystemClock.elapsedRealtime()-confirmedAt <= (staticPack?650:250);
}
private static boolean displayEligible(View v) {
Display d=v.getDisplay(); return enabled && v.isAttachedToWindow() && v.isShown()
&& d!=null && d.getState()==Display.STATE_ON && v.getWindowVisibility()==View.VISIBLE;
}
private static boolean anyEligible() {
if (!lockInteractive()) { status("VIDEO_WAIT_LOCK_INTERACTIVE"); return false; }
String reason = "VIDEO_WAIT_CLOCK_VISIBLE";
for (View v : CLOCKS) {
if (!displayEligible(v)) continue;
reason = compatibilityIssue(v);
if (reason == null) return true;
}
status(reason);
return false;
}
private static boolean compatible(View v) { return compatibilityIssue(v) == null; }
private static String compatibilityIssue(View v) {
try {
Display d = v.getDisplay();
if (d == null || d.getDisplayId() != Display.DEFAULT_DISPLAY)
return "VIDEO_WAIT_MAIN_DISPLAY";
// CurrentWindowMetrics can be a clock window rather than the wallpaper display.
Point real = new Point(); d.getRealSize(real);
if (real.x != displayWidth() || real.y != displayHeight())
return "VIDEO_DISPLAY_MISMATCH actual=" + real.x + "x" + real.y
+ " expected=" + displayWidth() + "x" + displayHeight();
for (Class<?> c = v.getClass(); c != null; c = c.getSuperclass())
if ("com.samsung.android.uniform.widget.clock.AbsClockView".equals(c.getName()))
return DepthBlurHooks.ready(c.getClassLoader()) ? null : "VIDEO_WAIT_NATIVE_BLUR";
} catch (Exception | LinkageError error) { return "VIDEO_CLOCK_CHECK_ERROR " + error.getClass().getSimpleName(); }
return "VIDEO_CLOCK_PROVIDER_UNSUPPORTED";
}
private static void schedule(long ms) {
if(!enabled || inFlight) return;
MAIN.removeCallbacks(TICK); MAIN.postDelayed(TICK,ms);
}
private static void clear() { confirmedAt=0; applied=false; for(View v:new ArrayList<>(CLOCKS)) DepthEffects.clearVideo(v); }
private static void stop() { generation++; retryUntil=0; MAIN.removeCallbacks(TICK); clear(); }
private static void tick() {
if(!anyEligible()) {clear(); retryIfWaiting(); return;}
VideoPlaybackBridge bridge=VideoPlaybackBridge.activeBridge();
if(bridge==null) {status("VIDEO_WAIT_BRIDGE"); clear(); schedule(500); return;}
inFlight=true; long token=generation;
bridge.request(MAIN, sample -> {
if(token!=generation || !anyEligible()) {done(token,null,500); return;}
if(sample==null) {status("VIDEO_WAIT_NATIVE_SAMPLE"); done(token,null,250); return;}
if(!sample.sourcePath().equals(lastSamplePath)) clear();
lastSamplePath=sample.sourcePath();
IO.execute(() -> {
DepthEffects.PreparedVideo result=null;
try {result=select(sample);} catch(Exception | LinkageError e) { workerStatus("VIDEO_SELECT_ERROR " + e.getClass().getSimpleName()); }
DepthEffects.PreparedVideo frame=result;
MAIN.post(() -> done(token,frame,frame==null?(autoPackLoaded?100:500):(staticPack?250:80)));
});
});
}
private static void done(long token,DepthEffects.PreparedVideo frame,long delay) {
inFlight=false;
if(token!=generation || !anyEligible()) {clear(); if(anyEligible()) schedule(0); else retryIfWaiting(); return;}
if(frame==null) clear();
else {
confirmedAt=SystemClock.elapsedRealtime();
try {
for(View v:new ArrayList<>(CLOCKS)) {
if(displayEligible(v) && compatible(v)) DepthEffects.applyVideo(v,frame); else DepthEffects.clearVideo(v);
}
if (!applied) status("VIDEO_DEPTH_APPLIED");
applied=true;
} catch (RuntimeException | LinkageError error) {
status("VIDEO_RENDER_ERROR " + error.getClass().getSimpleName());
clear();
}
}
schedule(delay);
}
private static DepthEffects.PreparedVideo select(VideoPlaybackBridge.Sample sample) throws Exception {
autoPackLoaded=false;
int mode=AUTO.mode(context);
if(mode==2){workerStatus("VIDEO_AUTO_DISABLED");return null;}
// Preserve the already validated manual pack for its exact source.
if(pack!=null&&config!=null) {
staticPack=pack.unique==1;
DepthEffects.PreparedVideo legacy=selectLegacy(sample);
if(legacy!=null)return legacy;
}
if(mode!=1)return null;
DepthEffects.PreparedVideo auto=AUTO.select(context,sample,displayWidth(),displayHeight());
staticPack=AUTO.isStatic();autoPackLoaded=AUTO.hasPack();
return auto;
}
private static DepthEffects.PreparedVideo selectLegacy(VideoPlaybackBridge.Sample sample) throws Exception {
if(sample.videoWidth()!=pack.width || sample.videoHeight()!=pack.height || !config.surface.equals(sample.visibleSurface())) {
workerStatus("VIDEO_SOURCE_GEOMETRY_MISMATCH source=" + sample.videoWidth() + "x" + sample.videoHeight() + " surface=" + sample.visibleSurface());
return null;
}
File media=new File(sample.sourcePath()); long length=media.length(), modified=media.lastModified();
if(!sample.sourcePath().equals(verifiedPath) || length!=verifiedLength || modified!=verifiedModified) {
identityValid=false; verifiedPath=sample.sourcePath(); verifiedLength=length; verifiedModified=modified; nextHashAttempt=0;
}
if(!identityValid && SystemClock.elapsedRealtime() >= nextHashAttempt) {
nextHashAttempt = SystemClock.elapsedRealtime() + 5000;
try {
String actual = VideoMaskPack.hash(media);
if (media.length()!=length || media.lastModified()!=modified) {
workerStatus("VIDEO_SOURCE_CHANGED"); return null;
}
identityValid=pack.sha256.equals(actual);
if (!identityValid) {
workerStatus("VIDEO_SOURCE_HASH_MISMATCH sha256=" + actual);
nextHashAttempt=Long.MAX_VALUE;
} else workerStatus("VIDEO_SOURCE_HASH_OK");
} catch (Exception error) {
workerStatus("VIDEO_SOURCE_UNREADABLE " + error.getClass().getSimpleName());
return null;
}
}
if(!identityValid) return null;
int id=pack.maskAt(sample.positionMs()); if(id<0) {workerStatus("VIDEO_FRAME_OUTSIDE_TIMELINE"); return null;}
if(id!=preparedId || prepared==null) {
DepthEffects.PreparedVideo next=DepthEffects.prepareVideo(pack.png(id),config.crop);
if(next==null) {workerStatus("VIDEO_MASK_PREPARE_FAILED"); return null;}
prepared=next; preparedId=id;
}
if(SystemClock.elapsedRealtime()-sample.sampledAtMs()>(staticPack?500:100)) {workerStatus("VIDEO_SAMPLE_STALE"); return null;}
workerStatus("VIDEO_MASK_SELECTED"); return prepared;
}
}