Repository navigation
Expand file tree
/
Copy pathVideoDepthBroker.java
More file actions
274 lines (272 loc) · 17.1 KB
/
Copy pathVideoDepthBroker.java
File metadata and controls
274 lines (272 loc) · 17.1 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
package dev.denver.dressroomadvanced;
import android.content.*;
import android.content.pm.ApplicationInfo;
import android.database.Cursor;
import android.graphics.*;
import android.media.*;
import android.net.Uri;
import android.os.*;
import android.util.Log;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.zip.*;
/** Runs in :video_depth, never in the SystemUI process. Only Samsung's editor
* may change the user's setting; only SystemUI may submit its active video. */
public final class VideoDepthBroker extends ContentProvider {
static final Uri URI=Uri.parse("content://dev.denver.dressroomadvanced.video_depth");
static final String TAG="OneUIDepthMask";
static final int LIMIT=64*1024*1024, MAX_PACK=48*1024*1024;
private static final String EDITOR="com.samsung.android.app.dressroom";
private final ExecutorService work=Executors.newSingleThreadExecutor();
private Context storage;
private File directory;
private String running;
private volatile int completed,total,detections,reused;
private volatile String generationState="idle";
@Override public boolean onCreate() {
storage=getContext().createDeviceProtectedStorageContext();
directory=new File(storage.getFilesDir(),"video-depth-cache");
return true;
}
private void caller(String pkg) {
String[] names=getContext().getPackageManager().getPackagesForUid(Binder.getCallingUid());
if(names==null || !Arrays.asList(names).contains(pkg)) throw new SecurityException("Unsupported caller");
}
private android.content.SharedPreferences prefs() { return storage.getSharedPreferences("video_depth",0); }
private int mode() { return prefs().getInt("mode",0); } // 0 legacy, 1 auto, 2 disabled
static int readMode(Context c) {
Bundle b=c.getContentResolver().call(URI,"mode",null,null);
if(b==null) throw new IllegalStateException("Video depth service unavailable");
return b.getInt("mode",0);
}
static void setMode(Context c,int mode) {
Bundle b=new Bundle();b.putInt("mode",mode);
Bundle result=c.getContentResolver().call(URI,"setMode",null,b);
if(result==null || !result.getBoolean("ok")) throw new IllegalStateException("Cannot save video depth preference");
}
private static Bundle state(String status) {Bundle b=new Bundle();b.putString("status",status);return b;}
@Override public synchronized Bundle call(String method,String arg,Bundle extras) {
if("progress".equals(method)) {
caller(EDITOR);
String latest=prefs().getString("latest","");
String state=mode()==2?"disabled":mode()==0?"manual":generationState;
if(mode()==1&&running==null&&latest.matches("[0-9a-f]{64}")) {
if(new File(directory,latest+".zip").isFile())state="ready";
else if(new File(directory,latest+".attempt").isFile())state="failed";
else state="waiting";
}
Bundle b=state(state);
b.putInt("completed",completed);b.putInt("total",total);
b.putInt("detections",detections);b.putInt("reused",reused);
return b;
}
if("mode".equals(method)) {
String[] names=getContext().getPackageManager().getPackagesForUid(Binder.getCallingUid());
if(names==null || !(Arrays.asList(names).contains(EDITOR)||Arrays.asList(names).contains("com.android.systemui")))
throw new SecurityException("Unsupported caller");
Bundle b=new Bundle();b.putInt("mode",mode());return b;
}
if("setMode".equals(method)||"retry".equals(method)) {
caller(EDITOR);
if("setMode".equals(method)) {
int value=extras==null?-1:extras.getInt("mode",-1);
if(value<1||value>2)throw new IllegalArgumentException("Invalid mode");
if(!prefs().edit().putInt("mode",value).commit()) return Bundle.EMPTY;
} else if(running==null) {
generationState="waiting";completed=total=detections=reused=0;
File[] markers=directory.listFiles((d,n)->n.endsWith(".attempt"));
if(markers!=null)for(File marker:markers) marker.delete();
}
getContext().getContentResolver().notifyChange(URI,null);
Bundle b=new Bundle();b.putBoolean("ok",true);return b;
}
caller("com.android.systemui");
if(!"lookup".equals(method)&&!"submit".equals(method)) throw new IllegalArgumentException("Unknown method");
if(mode()!=1)return state("disabled");
if(arg==null||!arg.matches("[0-9a-f]{64}"))throw new IllegalArgumentException("Invalid source identity");
int w=extras==null?0:extras.getInt("width"), h=extras==null?0:extras.getInt("height");
if(w<1||h<1||w>4096||h>4096||(long)w*h>4_194_304L)return state("unsupported_geometry");
if(!directory.isDirectory()&&!directory.mkdirs())return state("storage_unavailable");
File target=new File(directory,arg+".zip"), attempt=new File(directory,arg+".attempt");
if(!arg.equals(prefs().getString("latest","")))prefs().edit().putString("latest",arg).apply();
if(target.isFile()) {
try {
Bundle b=state("ready");
b.putParcelable("pack",ParcelFileDescriptor.open(target,ParcelFileDescriptor.MODE_READ_ONLY));
target.setLastModified(System.currentTimeMillis());
return b;
} catch(IOException e) {return state("cache_unreadable");}
}
if(arg.equals(running))return state("generating");
if(attempt.isFile())return state("failed_retry_in_editor");
if(running!=null)return state("busy");
if("lookup".equals(method))return state("missing");
ParcelFileDescriptor fd=extras.getParcelable("media",ParcelFileDescriptor.class);
if(fd==null)return state("no_media");
try {
// Persist the attempt before JNI starts. A native crash cannot cause an endless restart loop.
if(!attempt.createNewFile()){fd.close();return state("failed_retry_in_editor");}
ParcelFileDescriptor copy;
try {copy=ParcelFileDescriptor.dup(fd.getFileDescriptor());}finally{fd.close();}
running=arg;completed=total=detections=reused=0;generationState="generating";
work.execute(()->generate(arg,w,h,copy,target,attempt));
return state("generating");
}catch(IOException|RuntimeException e){try{fd.close();}catch(IOException ignored){}return state("submit_failed");}
}
private void generate(String sha,int w,int h,ParcelFileDescriptor fd,File target,File attempt) {
File media=new File(directory,sha+".source"), temp=new File(directory,sha+".tmp");
try {
Log.i(TAG,"VIDEO_AUTO_GENERATING");
try(InputStream in=new ParcelFileDescriptor.AutoCloseInputStream(fd);OutputStream out=new FileOutputStream(media)) {
byte[] b=new byte[65536];int n;long size=0;
while((n=in.read(b))!=-1) {size+=n;if(size>LIMIT)throw new IOException("video too large");out.write(b,0,n);}
}
if(!sha.equals(VideoMaskPack.hash(media)))throw new IOException("video changed");
ApplicationInfo info=getContext().getPackageManager().getApplicationInfo(EDITOR,0);
if((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))==0)
throw new SecurityException("Samsung detector package is not a system app");
Context samsung=getContext().createPackageContext(EDITOR,Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);
if(!ObjectCaptureBackend.available(samsung.getClassLoader()))throw new IOException("Samsung subject detector unavailable in worker");
Boolean ok=ObjectCaptureBackend.detect(samsung,samsung.getClassLoader(),detector->{
writePack(media,temp,sha,w,h,detector);return Boolean.TRUE;
});
if(!Boolean.TRUE.equals(ok))throw new IOException("No detector");
try(VideoMaskPack check=new VideoMaskPack(temp)) {
if(!sha.equals(check.sha256)||check.width!=w||check.height!=h)throw new IOException("Pack validation failed");
for(int i=0;i<check.unique;i++)check.png(i);
}
if(temp.length()>MAX_PACK||!temp.renameTo(target))throw new IOException("Cache publish failed");
attempt.delete(); trim(target);
generationState="ready";
Log.i(TAG,"VIDEO_AUTO_READY detections="+detections+" reused="+reused);
} catch(Exception|LinkageError e) {
generationState="failed";
Log.w(TAG,"VIDEO_AUTO_FAILED "+e.getClass().getSimpleName()+": "+e.getMessage());
} finally {
media.delete();temp.delete();
synchronized(this){running=null;}
getContext().getContentResolver().notifyChange(URI,null);
}
}
private void trim(File keep) {
File[] files=directory.listFiles((d,n)->n.endsWith(".zip"));
if(files==null)return;
Arrays.sort(files,Comparator.comparingLong(File::lastModified).reversed());
long sum=0;int count=0;
for(File f:files) {
if(f.equals(keep)){sum+=f.length();count++;continue;}
if(count>=3||sum+f.length()>96L*1024*1024)f.delete();
else{sum+=f.length();count++;}
}
}
private void writePack(File video,File out,String sha,int w,int h,Object detector)throws Exception {
MediaMetadataRetriever reader=new MediaMetadataRetriever();
MediaExtractor extractor=new MediaExtractor();
try {
reader.setDataSource(video.getAbsolutePath());extractor.setDataSource(video.getAbsolutePath());
int durationMs=Integer.parseInt(reader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
String rotation=reader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
if(durationMs<1||durationMs>30000|| (rotation!=null&&!"0".equals(rotation)))throw new IOException("Unsupported duration or rotation");
int track=-1;
for(int i=0;i<extractor.getTrackCount();i++){
MediaFormat format=extractor.getTrackFormat(i);
String mime=format.getString(MediaFormat.KEY_MIME);
if(mime!=null&&mime.startsWith("video/")){track=i;break;}
}
if(track<0)throw new IOException("No video track");
extractor.selectTrack(track);
TreeSet<Long> points=new TreeSet<>();int samples=0;
do {
long t=extractor.getSampleTime();
if(t<0)break;
if(++samples>21600)throw new IOException("Too many video samples");
if(t<durationMs*1000L)points.add(t);
}while(extractor.advance());
if(points.isEmpty())throw new IOException("No timestamps");
ArrayList<Long> selected=VideoFramePolicy.select(points,250000);
if(selected.isEmpty()||selected.size()>121)throw new IOException("Unsupported timeline");
int metadataW=Integer.parseInt(reader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int metadataH=Integer.parseInt(reader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
if(metadataW!=w||metadataH!=h)throw new IOException("Decoder geometry differs");
float scale=Math.min(1f,720f/Math.max(w,h));
int iw=Math.max(1,Math.round(w*scale)),ih=Math.max(1,Math.round(h*scale));
completed=detections=reused=0;total=selected.size();
int[] reference=null;long referencePts=-1;int referenceIndex=-1;boolean referenceUseful=false;
StringBuilder timeline=new StringBuilder();Map<String,Integer> seen=new HashMap<>();
long bytes=0;int valid=0,frameIndex=0;
try(ZipOutputStream zip=new ZipOutputStream(new FileOutputStream(out))) {
for(long pts:selected) {
if(mode()!=1)throw new InterruptedIOException("Video depth disabled");
Bitmap frame=null,input=null,mask=null,full=null;
try {
frame=reader.getScaledFrameAtTime(pts,MediaMetadataRetriever.OPTION_CLOSEST,iw,ih);
if(frame==null||frame.getWidth()!=iw||frame.getHeight()!=ih) {
if(frame!=null)frame.recycle();
frame=reader.getFrameAtTime(pts,MediaMetadataRetriever.OPTION_CLOSEST);
if(frame==null||frame.getWidth()!=w||frame.getHeight()!=h)throw new IOException("Decoder geometry differs");
}
input=Bitmap.createScaledBitmap(frame,iw,ih,true);
if(input.getConfig()!=Bitmap.Config.ARGB_8888) {
Bitmap old=input;input=old.copy(Bitmap.Config.ARGB_8888,false);
if(old!=frame)old.recycle();
}
if(input==null)throw new IOException("Decoder bitmap unavailable");
int[] fingerprint=thumbnail(input);
if(referenceUseful&&referenceIndex>=0&&VideoFramePolicy.reuse(reference,fingerprint,pts-referencePts)) {
timeline.append(pts).append('\t').append(referenceIndex).append('\n');
reused++;valid++;completed=++frameIndex;
if(frameIndex%12==0)Log.i(TAG,"VIDEO_AUTO_PROGRESS "+frameIndex+"/"+selected.size());
continue;
}
detections++;
mask=MaskAlpha.detect(detector,input,"video frame");
boolean useful=mask!=null&&!MaskAlpha.bounds(mask).isEmpty();
full=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
full.setHasAlpha(true);
if(useful){
new Canvas(full).drawBitmap(mask,null,new Rect(0,0,w,h),new Paint(Paint.FILTER_BITMAP_FLAG));
// Reject nearly solid alpha masks instead of hiding the entire clock.
int covered=0,total=0;
for(int y=0;y<h;y+=8)for(int x=0;x<w;x+=8){total++;if((full.getPixel(x,y)>>>24)>127)covered++;}
if(covered<total*0.98&&covered>total*0.005)valid++;
else {full.eraseColor(Color.TRANSPARENT);useful=false;}
}
byte[] png=MaskAlpha.encode(full);
if(png.length<33||png.length>VideoMaskPack.MAX_PNG||png[25]!=6)throw new IOException("Invalid alpha PNG");
String digest=DepthStorage.hash(png);
Integer index=seen.get(digest);
if(index==null){index=seen.size();seen.put(digest,index);bytes+=png.length;if(bytes>MAX_PACK)throw new IOException("Mask budget exceeded");entry(zip,"masks/"+index+".png",png);}
timeline.append(pts).append('\t').append(index).append('\n');
reference=fingerprint;referencePts=pts;referenceIndex=index;referenceUseful=useful;
completed=++frameIndex;
if(frameIndex%12==0)Log.i(TAG,"VIDEO_AUTO_PROGRESS "+frameIndex+"/"+selected.size());
}finally {
if(full!=null)full.recycle();
if(mask!=null&&mask!=input&&mask!=frame)mask.recycle();
if(input!=null&&input!=frame)input.recycle();
if(frame!=null)frame.recycle();
}
}
if(valid==0)throw new IOException("No usable subject detected");
String manifest="schema=1\nsha256="+sha+"\nwidth="+w+"\nheight="+h+"\ndurationUs="+(durationMs*1000L)+"\ncount="+selected.size()+"\nunique="+seen.size()+"\n";
entry(zip,"manifest.properties",manifest.getBytes(java.nio.charset.StandardCharsets.UTF_8));
entry(zip,"timeline.tsv",timeline.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
}finally{extractor.release();reader.release();}
}
private static int[] thumbnail(Bitmap input) {
Bitmap small=Bitmap.createScaledBitmap(input,64,64,true);
try {
int[] pixels=new int[4096];small.getPixels(pixels,0,64,0,0,64,64);return pixels;
}finally{if(small!=input)small.recycle();}
}
private static void entry(ZipOutputStream z,String name,byte[] content)throws IOException {
z.putNextEntry(new ZipEntry(name));z.write(content);z.closeEntry();
}
@Override public Cursor query(Uri u,String[] p,String s,String[] a,String o){throw new UnsupportedOperationException();}
@Override public String getType(Uri u){return null;}
@Override public Uri insert(Uri u,ContentValues v){throw new UnsupportedOperationException();}
@Override public int delete(Uri u,String s,String[] a){throw new UnsupportedOperationException();}
@Override public int update(Uri u,ContentValues v,String s,String[] a){throw new UnsupportedOperationException();}
}