-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathafme_vk_layer.cpp
More file actions
3300 lines (2961 loc) · 152 KB
/
Copy pathafme_vk_layer.cpp
File metadata and controls
3300 lines (2961 loc) · 152 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* AFME Vulkan Layer — Adreno Frame Motion Engine
*
* Copyright (C) 2025-2026 IRedDragonICY
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* HW-accelerated frame generation using Adreno glExtrapolateTex2DQCOM
* via EGL/GLES interop with AHardwareBuffer shared images.
* Supports 2x, 3x, 4x frame multiplier via persist.sys.afme.multiplier
*/
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>
#include <vulkan/vk_layer.h>
#include <string.h>
#include <unistd.h>
#include <unordered_map>
#include <mutex>
#include <atomic>
#include <vector>
#include <string>
// EGL/GLES for AFME HW interop
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <GLES3/gl31.h> // Compute shaders, image load/store, memory barriers
#include <GLES3/gl32.h> // glCopyImageSubData
#include <GLES3/gl3ext.h>
#include <GLES2/gl2ext.h>
// AHardwareBuffer
#include <android/hardware_buffer.h>
#include <android/log.h>
#include <cutils/properties.h>
#include "afme_core.h"
#include "afme_filter.h"
// ─── Constants ──────────────────────────────────────────────────────────────
#define LOG_TAG "AFME"
#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
static const char kLayerName[] = "VK_LAYER_AFME_frame_gen";
static const char kLayerDescription[] = "AFME Frame Generation Layer (IRedDragonICY)";
static const uint32_t kLayerImplVersion = 5;
static const uint32_t kLayerSpecVersion = VK_MAKE_API_VERSION(0, 1, 3, 0);
// Maximum pre-allocated semaphores for frame generation (per swapchain)
// Each synth frame needs 2 sems (acquire + signal); deferred drain means up to
// 2 frames of sems may be in-flight simultaneously. 4x * 4 = 16 covers worst case.
static constexpr int kMaxSemaphorePool = afme::kMaxMultiplier * 4;
// Pre-allocated command buffer ring (avoid hot-path alloc/free)
static constexpr int kCmdRingSize = afme::kMaxMultiplier * 2 + 2; // +2 for copy steps
typedef void (GL_APIENTRYP PFNGLEXTRAPOLATETEX2DQCOMPROC)(GLuint, GLuint, GLuint, float);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)(GLenum, void*);
typedef void* (EGLAPIENTRYP PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC)(const struct AHardwareBuffer*);
typedef void* (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC)(EGLDisplay, EGLContext, EGLenum,
EGLClientBuffer, const EGLint*);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC)(EGLDisplay, void*);
// QCOM motion estimation + depth estimation HW accelerators
typedef void (GL_APIENTRYP PFNGLTEXESTIMATEMOTIONQCOMPROC)(GLuint, GLuint, GLuint);
typedef void (GL_APIENTRYP PFNGLTEXGENERATEDISPARITYQCOMPROC)(GLuint, GLuint);
typedef void (GL_APIENTRYP PFNGLSHADINGRATEQCOMPROC)(GLenum);
// QCOM motion estimation search block size query tokens
#define GL_MOTION_ESTIMATION_SEARCH_BLOCK_X_QCOM 0x8C90
#define GL_MOTION_ESTIMATION_SEARCH_BLOCK_Y_QCOM 0x8C91
// GL_QCOM_shading_rate — ABI values match ANGLE's include/GLES2/gl2ext.h
#ifndef GL_SHADING_RATE_1X1_PIXELS_QCOM
#define GL_SHADING_RATE_1X1_PIXELS_QCOM 0x96A6
#endif
#ifndef GL_SHADING_RATE_2X2_PIXELS_QCOM
#define GL_SHADING_RATE_2X2_PIXELS_QCOM 0x96A9
#endif
// ─── Global next-layer function pointers ────────────────────────────────────
namespace {
PFN_vkGetInstanceProcAddr next_vkGetInstanceProcAddr{};
PFN_vkGetDeviceProcAddr next_vkGetDeviceProcAddr{};
PFN_vkCreateInstance next_vkCreateInstance{};
PFN_vkDestroyInstance next_vkDestroyInstance{};
PFN_vkCreateDevice next_vkCreateDevice{};
PFN_vkDestroyDevice next_vkDestroyDevice{};
PFN_vkQueuePresentKHR next_vkQueuePresentKHR{};
PFN_vkQueueSubmit next_vkQueueSubmit{};
PFN_vkQueueWaitIdle next_vkQueueWaitIdle{};
PFN_vkGetDeviceQueue next_vkGetDeviceQueue{};
PFN_vkCreateSwapchainKHR next_vkCreateSwapchainKHR{};
PFN_vkDestroySwapchainKHR next_vkDestroySwapchainKHR{};
PFN_vkGetSwapchainImagesKHR next_vkGetSwapchainImagesKHR{};
PFN_vkAcquireNextImageKHR next_vkAcquireNextImageKHR{};
PFN_vkCreateCommandPool next_vkCreateCommandPool{};
PFN_vkDestroyCommandPool next_vkDestroyCommandPool{};
PFN_vkAllocateCommandBuffers next_vkAllocateCommandBuffers{};
PFN_vkFreeCommandBuffers next_vkFreeCommandBuffers{};
PFN_vkResetCommandBuffer next_vkResetCommandBuffer{};
PFN_vkBeginCommandBuffer next_vkBeginCommandBuffer{};
PFN_vkEndCommandBuffer next_vkEndCommandBuffer{};
PFN_vkCmdPipelineBarrier next_vkCmdPipelineBarrier{};
PFN_vkCmdBlitImage next_vkCmdBlitImage{};
PFN_vkCreateImage next_vkCreateImage{};
PFN_vkDestroyImage next_vkDestroyImage{};
PFN_vkGetImageMemoryRequirements next_vkGetImageMemoryRequirements{};
PFN_vkAllocateMemory next_vkAllocateMemory{};
PFN_vkFreeMemory next_vkFreeMemory{};
PFN_vkBindImageMemory next_vkBindImageMemory{};
PFN_vkCreateFence next_vkCreateFence{};
PFN_vkDestroyFence next_vkDestroyFence{};
PFN_vkWaitForFences next_vkWaitForFences{};
PFN_vkResetFences next_vkResetFences{};
PFN_vkCreateSemaphore next_vkCreateSemaphore{};
PFN_vkDestroySemaphore next_vkDestroySemaphore{};
PFN_vkGetAndroidHardwareBufferPropertiesANDROID next_vkGetAndroidHardwareBufferProperties{};
PFN_vkGetPhysicalDeviceMemoryProperties next_vkGetPhysicalDeviceMemoryProperties{};
PFN_vkGetPhysicalDeviceProperties next_vkGetPhysicalDeviceProperties{};
PFN_vkGetPhysicalDeviceFeatures next_vkGetPhysicalDeviceFeatures{};
PFN_vkCreateSampler next_vkCreateSampler{};
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR next_vkGetPhysicalDeviceSurfaceCapabilities{};
PFN_vkEnumerateDeviceExtensionProperties next_vkEnumerateDeviceExtensionProperties{};
PFN_vkGetFenceFdKHR next_vkGetFenceFdKHR{};
PFN_vkImportSemaphoreFdKHR next_vkImportSemaphoreFdKHR{};
PFN_vkGetRefreshCycleDurationGOOGLE next_vkGetRefreshCycleDurationGOOGLE{};
// ─── Global State ───────────────────────────────────────────────────────────
std::mutex gLock;
// ─── SGSR1 Shader Sources (Qualcomm BSD-3) ──────────────────────────────────
// Fullscreen triangle vertex shader — no VBO needed, 3 vertices cover viewport
static const char* kSGSR1VertSrc = R"(
#version 300 es
out highp vec4 in_TEXCOORD0;
void main() {
float x = float((gl_VertexID & 1) << 1);
float y = float((gl_VertexID >> 1) & 1) * 2.0;
gl_Position = vec4(x * 2.0 - 1.0, y * 2.0 - 1.0, 0.0, 1.0);
in_TEXCOORD0 = vec4(x, y, 0.0, 0.0);
}
)";
// SGSR1 fragment shader — 12-tap Lanczos-like upscaling + adaptive sharpening
// Source: snapdragon-gsr/sgsr/v1/include/glsl/sgsr1_shader_mobile.frag
static const char* kSGSR1FragSrc = R"(
#version 300 es
precision mediump float;
precision highp int;
#define OperationMode 1
#define EdgeThreshold 8.0/255.0
#define EdgeSharpness 2.0
uniform highp vec4 ViewportInfo[1];
uniform mediump sampler2D ps0;
layout(location=0) in highp vec4 in_TEXCOORD0;
layout(location=0) out vec4 out_Target0;
float fastLanczos2(float x) {
float wA = x - 4.0;
float wB = x * wA - wA;
wA *= wA;
return wB * wA;
}
vec2 weightY(float dx, float dy, float c, float std) {
float x = ((dx*dx)+(dy*dy))*0.55 + clamp(abs(c)*std, 0.0, 1.0);
float w = fastLanczos2(x);
return vec2(w, w * c);
}
void main() {
int mode = OperationMode;
float edgeThreshold = EdgeThreshold;
float edgeSharpness = EdgeSharpness;
vec4 color;
if(mode == 1)
color.xyz = textureLod(ps0, in_TEXCOORD0.xy, 0.0).xyz;
else
color.xyzw = textureLod(ps0, in_TEXCOORD0.xy, 0.0).xyzw;
if (mode != 4) {
highp vec2 imgCoord = ((in_TEXCOORD0.xy*ViewportInfo[0].zw)+vec2(-0.5,0.5));
highp vec2 imgCoordPixel = floor(imgCoord);
highp vec2 coord = (imgCoordPixel*ViewportInfo[0].xy);
vec2 pl = (imgCoord+(-imgCoordPixel));
vec4 left = textureGather(ps0, coord, mode);
float edgeVote = abs(left.z - left.y) + abs(color[mode] - left.y) + abs(color[mode] - left.z);
if(edgeVote > edgeThreshold) {
coord.x += ViewportInfo[0].x;
vec4 right = textureGather(ps0, coord + highp vec2(ViewportInfo[0].x, 0.0), mode);
vec4 upDown;
upDown.xy = textureGather(ps0, coord + highp vec2(0.0, -ViewportInfo[0].y), mode).wz;
upDown.zw = textureGather(ps0, coord + highp vec2(0.0, ViewportInfo[0].y), mode).yx;
float mean = (left.y+left.z+right.x+right.w)*0.25;
left = left - vec4(mean);
right = right - vec4(mean);
upDown = upDown - vec4(mean);
color.w = color[mode] - mean;
float sum = (((((abs(left.x)+abs(left.y))+abs(left.z))+abs(left.w))+(((abs(right.x)+abs(right.y))+abs(right.z))+abs(right.w)))+(((abs(upDown.x)+abs(upDown.y))+abs(upDown.z))+abs(upDown.w)));
float std = 2.181818/sum;
vec2 aWY = weightY(pl.x, pl.y+1.0, upDown.x, std);
aWY += weightY(pl.x-1.0, pl.y+1.0, upDown.y, std);
aWY += weightY(pl.x-1.0, pl.y-2.0, upDown.z, std);
aWY += weightY(pl.x, pl.y-2.0, upDown.w, std);
aWY += weightY(pl.x+1.0, pl.y-1.0, left.x, std);
aWY += weightY(pl.x, pl.y-1.0, left.y, std);
aWY += weightY(pl.x, pl.y, left.z, std);
aWY += weightY(pl.x+1.0, pl.y, left.w, std);
aWY += weightY(pl.x-1.0, pl.y-1.0, right.x, std);
aWY += weightY(pl.x-2.0, pl.y-1.0, right.y, std);
aWY += weightY(pl.x-2.0, pl.y, right.z, std);
aWY += weightY(pl.x-1.0, pl.y, right.w, std);
float finalY = aWY.y/aWY.x;
float maxY = max(max(left.y,left.z),max(right.x,right.w));
float minY = min(min(left.y,left.z),min(right.x,right.w));
finalY = clamp(edgeSharpness*finalY, minY, maxY);
float deltaY = finalY - color.w;
deltaY = clamp(deltaY, -23.0/255.0, 23.0/255.0);
color.x = clamp((color.x+deltaY), 0.0, 1.0);
color.y = clamp((color.y+deltaY), 0.0, 1.0);
color.z = clamp((color.z+deltaY), 0.0, 1.0);
}
}
color.w = 1.0;
out_Target0 = color;
}
)";
// ─── Helpers ────────────────────────────────────────────────────────────────
template<typename T>
bool initInstanceFunc(VkInstance instance, const char* name, T* func) {
*func = reinterpret_cast<T>(next_vkGetInstanceProcAddr(instance, name));
if (!*func) { ALOGW("AFME: No func: %s", name); return false; }
return true;
}
template<typename T>
bool initDeviceFunc(VkDevice device, const char* name, T* func) {
*func = reinterpret_cast<T>(next_vkGetDeviceProcAddr(device, name));
if (!*func) { ALOGW("AFME: No func: %s", name); return false; }
return true;
}
// The filter runs on this layer's private GLES context, so the entry points are
// simply the ones we link. (The GLES layer fills the same struct from
// eglGetProcAddress — see afme_filter.h for why it is a struct at all.)
static afme::FilterGL gFilterGl;
static std::once_flag gFilterGlOnce;
static void initFilterGl() {
std::call_once(gFilterGlOnce, [] {
gFilterGl.CreateShader = glCreateShader;
gFilterGl.ShaderSource = glShaderSource;
gFilterGl.CompileShader = glCompileShader;
gFilterGl.GetShaderiv = glGetShaderiv;
gFilterGl.GetShaderInfoLog = glGetShaderInfoLog;
gFilterGl.DeleteShader = glDeleteShader;
gFilterGl.CreateProgram = glCreateProgram;
gFilterGl.AttachShader = glAttachShader;
gFilterGl.LinkProgram = glLinkProgram;
gFilterGl.GetProgramiv = glGetProgramiv;
gFilterGl.GetProgramInfoLog = glGetProgramInfoLog;
gFilterGl.DeleteProgram = glDeleteProgram;
gFilterGl.UseProgram = glUseProgram;
gFilterGl.GetUniformLocation = glGetUniformLocation;
gFilterGl.Uniform1i = glUniform1i;
gFilterGl.Uniform4f = glUniform4f;
gFilterGl.Uniform1f = glUniform1f;
gFilterGl.GenFramebuffers = glGenFramebuffers;
gFilterGl.DeleteFramebuffers = glDeleteFramebuffers;
gFilterGl.BindFramebuffer = glBindFramebuffer;
gFilterGl.FramebufferTexture2D = glFramebufferTexture2D;
gFilterGl.GenVertexArrays = glGenVertexArrays;
gFilterGl.DeleteVertexArrays = glDeleteVertexArrays;
gFilterGl.BindVertexArray = glBindVertexArray;
gFilterGl.GenTextures = glGenTextures;
gFilterGl.DeleteTextures = glDeleteTextures;
gFilterGl.TexStorage2D = glTexStorage2D;
gFilterGl.GenerateMipmap = glGenerateMipmap;
gFilterGl.ActiveTexture = glActiveTexture;
gFilterGl.BindTexture = glBindTexture;
gFilterGl.TexParameteri = glTexParameteri;
gFilterGl.Viewport = glViewport;
gFilterGl.DrawArrays = glDrawArrays;
gFilterGl.Disable = glDisable;
});
}
// The AHB staging buffer is allocated AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM, so
// a 10-bit or FP16 swapchain would round-trip the REAL frame through 8 bits.
// That is invisible while we only read the frame for generation, but the filter
// copies its result back — so refuse rather than quietly degrade the game.
static bool is8BitSwapchain(VkFormat f) {
switch (f) {
case VK_FORMAT_R8G8B8A8_UNORM:
case VK_FORMAT_R8G8B8A8_SRGB:
case VK_FORMAT_B8G8R8A8_UNORM:
case VK_FORMAT_B8G8R8A8_SRGB:
return true;
default:
return false;
}
}
static uint32_t findMemoryType(const VkPhysicalDeviceMemoryProperties& memProps,
uint32_t typeFilter, VkMemoryPropertyFlags flags) {
for (uint32_t i = 0; i < memProps.memoryTypeCount; i++) {
if ((typeFilter & (1 << i)) &&
(memProps.memoryTypes[i].propertyFlags & flags) == flags) {
return i;
}
}
// Fallback: any compatible type
for (uint32_t i = 0; i < memProps.memoryTypeCount; i++) {
if (typeFilter & (1 << i)) return i;
}
return 0;
}
// ─── AHB Image: shared between Vulkan and GLES ─────────────────────────────
struct AHBImage {
AHardwareBuffer* ahb = nullptr;
VkImage vkImage = VK_NULL_HANDLE;
VkDeviceMemory vkMemory = VK_NULL_HANDLE;
EGLImageKHR eglImage = EGL_NO_IMAGE_KHR;
GLuint glTex = 0;
bool valid = false;
};
// ─── AFME Context: one per swapchain ────────────────────────────────────────
struct AFMEContext {
VkDevice device = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
VkExtent2D extent = {0, 0};
VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
std::vector<VkImage> swapchainImages;
uint32_t queueFamilyIndex = 0;
// Vulkan resources
VkCommandPool cmdPool = VK_NULL_HANDLE;
VkFence copyFence = VK_NULL_HANDLE; // Fence for copy-to-AHB step
VkPhysicalDeviceMemoryProperties memProps = {};
// Pre-allocated semaphore pool (avoid per-frame create/destroy)
VkSemaphore semPool[kMaxSemaphorePool] = {};
uint32_t semPoolSize = 0;
uint32_t semPoolCursor = 0;
// Pre-allocated command buffer ring (avoid hot-path alloc/free)
VkCommandBuffer cmdRing[kCmdRingSize] = {};
uint32_t cmdRingSize = 0;
uint32_t cmdRingCursor = 0;
// SGSR1 GLES resources
GLuint sgsrProgram = 0;
GLuint sgsrFbo = 0;
GLuint sgsrVao = 0;
GLint sgsrViewportInfoLoc = -1;
GLint sgsrPs0Loc = -1;
bool sgsrInitialized = false;
AHBImage sharpenedFrame; // Output of SGSR1 sharpening
// Fence signaled by the LAST synth copy submit of a frame; waited at the
// start of the next frame instead of vkQueueWaitIdle (which also waited
// for the game's freshly submitted rendering and destroyed pipelining).
VkFence drainFence = VK_NULL_HANDLE;
bool drainPending = false;
// Cadence control law, statistics and the game-loop discriminator. Shared
// with the GLES layer — see afme_core.h. Per context, never file-scope:
// games recreate swapchains (ZZZ makes several at startup) and a static
// baseline from the old one underflows against the new context's small
// counters (observed: "real=2147483647 total=-2" for one window).
afme::Pacer pacer;
afme::Stats stats;
afme::EngagementGate gate;
// Color filter. stageFrame holds the untouched present image; the filter
// grades it INTO currFrame, so generation and the real frame both see the
// graded result and the grade costs one pass per real frame at any
// multiplier. Allocated lazily — a session that never enables the filter
// pays nothing.
AHBImage stageFrame;
// Stage B output. Only allocated when a screen-space effect is actually
// set, because it is a full extra frame of memory.
AHBImage presentFrame;
// Generation scratch: with stage B on, synthesis writes here and stage B
// copies out to the synth AHB, since a pass cannot read and write one
// texture. Without stage B, synthesis writes the AHB directly as before.
GLuint genScratchTex = 0;
afme::Filter filter;
bool filterUnsupported = false; // non-8-bit swapchain: refuse, do not degrade
// MobFGSR is built at swapchain creation, but the method property can flip
// mid-session; this lets us build it on first use without retrying forever.
bool mobfgsrAttempted = false;
// VK_GOOGLE_display_timing pacing for synthetic frames
bool hasDisplayTiming = false;
uint32_t presentId = 0;
// Measured panel refresh cycle (vkGetRefreshCycleDurationGOOGLE); 0 = use
// the afme::config().displayHz prop instead. Vsync grid
// calibration: the panel CAN differ from the staged prop (e.g. Battery
// Saver votes 60Hz over the GameStateDispatcher force), and tier/limiter
// math against the wrong grid produced exactly the invisible-generation
// cadence seen on device.
uint64_t refreshCycleNs = 0;
PFNGLSHADINGRATEQCOMPROC glShadingRate = nullptr;
// Native-fence (sync_fd) VK↔GLES interop — replaces vkWaitForFences and
// glFinish on the game's render thread with GPU-side waits.
bool hasNativeFenceSync = false;
bool copyFencePending = false; // copyFence submitted, not yet CPU-waited
VkSemaphore genDoneSem = VK_NULL_HANDLE; // GLES gen complete → VK copy
PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR_ = nullptr;
PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR_ = nullptr;
PFNEGLWAITSYNCKHRPROC eglWaitSyncKHR_ = nullptr;
PFNEGLDUPNATIVEFENCEFDANDROIDPROC eglDupNativeFenceFD_ = nullptr;
// AHB frames for AFME
AHBImage prevFrame;
AHBImage currFrame;
AHBImage synthFrames[afme::kMaxMultiplier - 1]; // up to 3 for 4x
// EGL/GLES context (owned by this swapchain context)
EGLDisplay eglDpy = EGL_NO_DISPLAY;
EGLContext eglCtx = EGL_NO_CONTEXT;
EGLSurface eglSurf = EGL_NO_SURFACE;
// GLES extension pointers
PFNGLEXTRAPOLATETEX2DQCOMPROC glExtrapolateTex2D = nullptr;
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2D = nullptr;
PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC eglGetNativeClientBuffer = nullptr;
PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR = nullptr;
PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR = nullptr;
// QCOM HW motion estimation + depth estimation
PFNGLTEXESTIMATEMOTIONQCOMPROC glTexEstimateMotion = nullptr;
PFNGLTEXGENERATEDISPARITYQCOMPROC glTexGenerateDisparity = nullptr;
int motionBlockX = 16; // queried at runtime
int motionBlockY = 16;
// ─── MobFGSR resources ───────────────────────────────────
bool mobfgsrInitialized = false;
GLuint lumaConvertProg = 0; // RGB→R8 luminance (render pass, not compute)
GLuint lumaFbo = 0; // render target for the luminance pass
GLuint lumaVao = 0; // empty VAO for the fullscreen triangle
GLint lumaSrcLoc = -1;
GLuint mvUpsampleProg = 0; // Block-level MV → per-pixel MV
GLuint dilateProg = 0; // Nearest-depth dilation
GLuint clearProg = 0; // Clear reprojection buffer
GLuint reprojectProg = 0; // Scatter reproject with atomicMin
GLuint fillProg = 0; // Fill reprojection holes
GLuint warpProg = 0; // Warp + blend final output
GLuint mobfgsrUBO = 0; // Uniform buffer (binding=10)
// MobFGSR GLES textures (NOT AHB — pure GLES on our private context)
GLuint prevLumaTex = 0; // R8 luminance, render res
GLuint currLumaTex = 0; // R8 luminance, render res
GLuint motionVecBlockTex = 0; // RGBA16F, W/blockX × H/blockY
GLuint motionVecTex = 0; // RG16F, per-pixel (upsampled)
GLuint prevMotionVecTex = 0; // RG16F, previous frame
GLuint depthTex = 0; // R32F, estimated depth
GLuint prevDepthTex = 0; // R32F, previous depth
GLuint dilatedDepthTex = 0; // R32F, dilated current
GLuint dilatedMVTex = 0; // RG16F, dilated current
GLuint prevDilatedDepthTex = 0; // R32F, dilated previous
GLuint prevDilatedMVTex = 0; // RG16F, dilated previous
GLuint reprojectionTex = 0; // R32UI, reproject scatter buf
GLuint filledReprojTex = 0; // R32UI, filled reprojection
GLuint fgResultTex = 0; // RGBA8, frame gen result
// ── HUD ghost protection ────────────────────────────────────────────
// Per-block (motion-grid) accumulation of screen-STATIC content
// (minimap, HP bars, buttons, subtitles). Moving world pixels fail the
// "static" test, so the warp keeps blending them normally; HUD pixels
// are locked to the current real frame instead of the warped/interpolated
// value — which is what stops the classic FG "shadow trail" on UI.
GLuint hudMaskProg = 0; // block-grid static accumulation
GLuint hudMaskTex = 0; // R32F, W/blockX × H/blockY (write side)
GLuint prevHudMaskTex = 0; // R32F, read side (baseline, swapped)
bool initialized = false;
bool afmeHWAvailable = false;
bool hasPrevFrame = false;
int allocatedMult = 2; // Multiplier at init time (# synth frames = allocatedMult-1)
uint64_t frameIdx = 0;
uint64_t genFrames = 0;
uint64_t skippedFrames = 0; // Frames skipped due to scene change
// Semaphore pool helpers — cursor resets each frame to ensure drain
VkSemaphore acquireSem() {
if (semPoolSize == 0) return VK_NULL_HANDLE;
VkSemaphore s = semPool[semPoolCursor % semPoolSize];
semPoolCursor++;
return s;
}
// Command buffer ring — cursor resets each frame
VkCommandBuffer acquireCmd() {
if (cmdRingSize == 0) return VK_NULL_HANDLE;
VkCommandBuffer cb = cmdRing[cmdRingCursor % cmdRingSize];
cmdRingCursor++;
return cb;
}
};
// Effective panel rate: prefer the measured refresh cycle (display_timing)
// over the staged prop — the two can disagree (Battery Saver 60Hz vote,
// 90Hz override sessions, future panels), and running the tier/limiter math
// on the wrong grid is how generation becomes invisible.
static inline int effectiveHz(const AFMEContext& ctx) {
if (ctx.refreshCycleNs >= 2000000 && ctx.refreshCycleNs <= 100000000) { // 10..500 Hz
int hz = (int)(1000000000.0 / (double)ctx.refreshCycleNs + 0.5);
if (hz >= 10 && hz <= 500) return hz;
}
return afme::config().displayHz.load(std::memory_order_relaxed);
}
// Set fragment shading rate for our passes when the driver supports it.
static inline void setFgShadingRate(const AFMEContext& ctx, GLenum rate) {
if (ctx.glShadingRate && afme::config().vrsFg.load(std::memory_order_relaxed)) {
ctx.glShadingRate(rate);
}
}
// Swapchain → context mapping
std::unordered_map<VkSwapchainKHR, AFMEContext> gSwapchainContexts;
// Device → state mapping
std::unordered_map<VkDevice, VkPhysicalDevice> gDeviceToPhysical;
// Device → memProps mapping
std::unordered_map<VkDevice, VkPhysicalDeviceMemoryProperties> gDeviceMemProps;
// Device → VK_GOOGLE_display_timing enabled (for synth-frame pacing)
std::unordered_map<VkDevice, bool> gDeviceHasGoogleTiming;
// Device → VK_KHR_external_fence_fd + VK_KHR_external_semaphore_fd enabled
// (for GPU-side VK↔GLES sync without blocking the game thread)
std::unordered_map<VkDevice, bool> gDeviceHasNativeFence;
// ─── EGL Context Setup ─────────────────────────────────────────────────────
static bool initEGLContext(AFMEContext& ctx) {
ctx.eglDpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (ctx.eglDpy == EGL_NO_DISPLAY) {
ALOGE("AFME: eglGetDisplay failed");
return false;
}
EGLint major, minor;
if (!eglInitialize(ctx.eglDpy, &major, &minor)) {
ALOGE("AFME: eglInitialize failed: 0x%x", eglGetError());
return false;
}
EGLint configAttribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8,
EGL_NONE
};
EGLConfig config;
EGLint numConfigs;
if (!eglChooseConfig(ctx.eglDpy, configAttribs, &config, 1, &numConfigs) || numConfigs == 0) {
ALOGE("AFME: eglChooseConfig failed");
return false;
}
EGLint surfAttribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
ctx.eglSurf = eglCreatePbufferSurface(ctx.eglDpy, config, surfAttribs);
EGLint ctxAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
ctx.eglCtx = eglCreateContext(ctx.eglDpy, config, EGL_NO_CONTEXT, ctxAttribs);
if (ctx.eglCtx == EGL_NO_CONTEXT) {
ALOGE("AFME: eglCreateContext failed: 0x%x", eglGetError());
return false;
}
// Resolve extension functions (don't make current yet — we save/restore)
ctx.glExtrapolateTex2D = (PFNGLEXTRAPOLATETEX2DQCOMPROC)
eglGetProcAddress("glExtrapolateTex2DQCOM");
ctx.glEGLImageTargetTexture2D = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)
eglGetProcAddress("glEGLImageTargetTexture2DOES");
ctx.eglGetNativeClientBuffer = (PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC)
eglGetProcAddress("eglGetNativeClientBufferANDROID");
ctx.eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC)
eglGetProcAddress("eglCreateImageKHR");
ctx.eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC)
eglGetProcAddress("eglDestroyImageKHR");
ctx.afmeHWAvailable = ctx.glExtrapolateTex2D
&& ctx.glEGLImageTargetTexture2D
&& ctx.eglGetNativeClientBuffer
&& ctx.eglCreateImageKHR;
ALOGI("AFME: EGL init — HW %s (glExtrapolateTex2DQCOM=%p)",
ctx.afmeHWAvailable ? "AVAILABLE" : "UNAVAILABLE", ctx.glExtrapolateTex2D);
// Resolve QCOM motion estimation. RE of libGLESv2_adreno.so confirms
// glTexEstimateMotionQCOM is impl(ctx, uint prev, uint curr, uint outMV)
// — exactly our 3-arg typedef, and GL_QCOM_motion_estimation is an
// advertised extension. Safe to call.
ctx.glTexEstimateMotion = (PFNGLTEXESTIMATEMOTIONQCOMPROC)
eglGetProcAddress("glTexEstimateMotionQCOM");
// VRS for our own fragment passes (generation cost drops ~4x on the
// shaded passes)
ctx.glShadingRate = (PFNGLSHADINGRATEQCOMPROC)
eglGetProcAddress("glShadingRateQCOM");
// glTexGenerateDisparityQCOM is deliberately NOT resolved. RE of the
// driver export shows its real ABI is
// (uint,uint,uint,uint,uint,uint,uint,uint, float,float) — 8 uint + 2f
// not the (uint,uint) this layer previously assumed. It is also NOT in
// the driver's advertised GL_QCOM_* extension list (it's a hidden stereo
// disparity primitive, not a monocular depth estimator). Calling it with
// 2 args passed undefined register values as the other 8 params →
// UB/corrupt output. MobFGSR runs its clean degraded path instead
// (depthTex stays 0 → occlusion handling off, interpolation still valid).
ctx.glTexGenerateDisparity = nullptr;
// EGL_ANDROID_native_fence_sync + EGL_KHR_wait_sync for GPU-side VK↔GLES
// synchronization (no game-thread blocking)
ctx.eglCreateSyncKHR_ = (PFNEGLCREATESYNCKHRPROC)
eglGetProcAddress("eglCreateSyncKHR");
ctx.eglDestroySyncKHR_ = (PFNEGLDESTROYSYNCKHRPROC)
eglGetProcAddress("eglDestroySyncKHR");
ctx.eglWaitSyncKHR_ = (PFNEGLWAITSYNCKHRPROC)
eglGetProcAddress("eglWaitSyncKHR");
ctx.eglDupNativeFenceFD_ = (PFNEGLDUPNATIVEFENCEFDANDROIDPROC)
eglGetProcAddress("eglDupNativeFenceFDANDROID");
ALOGI("AFME: HW MotionEstimation=%p DepthEstimation=%p",
ctx.glTexEstimateMotion, ctx.glTexGenerateDisparity);
return true;
}
// ─── SGSR1 Shader Initialization ────────────────────────────────────────────
static GLuint compileShader(GLenum type, const char* src) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
GLint ok = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[512];
glGetShaderInfoLog(shader, sizeof(log), nullptr, log);
ALOGE("AFME: SGSR1 shader compile error: %s", log);
glDeleteShader(shader);
return 0;
}
return shader;
}
static bool initSGSR(AFMEContext& ctx) {
// Must be called with AFME's EGL context current
GLuint vs = compileShader(GL_VERTEX_SHADER, kSGSR1VertSrc);
GLuint fs = compileShader(GL_FRAGMENT_SHADER, kSGSR1FragSrc);
if (!vs || !fs) {
ALOGE("AFME: SGSR1 shader compilation failed");
if (vs) glDeleteShader(vs);
if (fs) glDeleteShader(fs);
return false;
}
ctx.sgsrProgram = glCreateProgram();
glAttachShader(ctx.sgsrProgram, vs);
glAttachShader(ctx.sgsrProgram, fs);
glLinkProgram(ctx.sgsrProgram);
GLint linked = 0;
glGetProgramiv(ctx.sgsrProgram, GL_LINK_STATUS, &linked);
if (!linked) {
char log[512];
glGetProgramInfoLog(ctx.sgsrProgram, sizeof(log), nullptr, log);
ALOGE("AFME: SGSR1 program link error: %s", log);
glDeleteProgram(ctx.sgsrProgram);
ctx.sgsrProgram = 0;
glDeleteShader(vs);
glDeleteShader(fs);
return false;
}
glDeleteShader(vs); // Safe to delete after linking
glDeleteShader(fs);
ctx.sgsrViewportInfoLoc = glGetUniformLocation(ctx.sgsrProgram, "ViewportInfo");
ctx.sgsrPs0Loc = glGetUniformLocation(ctx.sgsrProgram, "ps0");
glGenFramebuffers(1, &ctx.sgsrFbo);
glGenVertexArrays(1, &ctx.sgsrVao);
ctx.sgsrInitialized = true;
ALOGI("AFME: SGSR1 shader initialized (program=%u, viewportInfo=%d, ps0=%d)",
ctx.sgsrProgram, ctx.sgsrViewportInfoLoc, ctx.sgsrPs0Loc);
return true;
}
// Apply SGSR1 sharpening: inputTex → outputTex (same resolution)
// Must be called with AFME's EGL context current
static void applySGSR1(AFMEContext& ctx, GLuint inputTex, GLuint outputTex,
uint32_t w, uint32_t h) {
glUseProgram(ctx.sgsrProgram);
// ViewportInfo = {1/w, 1/h, w, h}
float viewportInfo[4] = {1.0f/(float)w, 1.0f/(float)h, (float)w, (float)h};
glUniform4fv(ctx.sgsrViewportInfoLoc, 1, viewportInfo);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, inputTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glUniform1i(ctx.sgsrPs0Loc, 0);
glBindFramebuffer(GL_FRAMEBUFFER, ctx.sgsrFbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, outputTex, 0);
glViewport(0, 0, w, h);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
setFgShadingRate(ctx, GL_SHADING_RATE_2X2_PIXELS_QCOM);
glBindVertexArray(ctx.sgsrVao);
glDrawArrays(GL_TRIANGLES, 0, 3);
setFgShadingRate(ctx, GL_SHADING_RATE_1X1_PIXELS_QCOM);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
glUseProgram(0);
}
// ─── MobFGSR Compute Shaders (ported to GLES 310 es) ───────────────────────
//
// Pipeline: HW motion estimation → dilate → clear → reproject → fill → warp
// Based on MobFGSR (BSD-3 license) adapted for Adreno 840 HW primitives.
// RGB → R8 luminance for motion estimation input.
//
// Done as a render-to-texture pass, not a compute imageStore: `r8` is not a
// required image format in GLSL ES 3.1/3.2, and this Adreno build does not
// expose GL_NV_image_formats, so `layout(r8, ...)` fails to compile with
// "not a legal layout qualifier id". R8 *is* colour-renderable though, so a
// plain fragment shader writing into an FBO works and keeps the single-channel
// format glTexEstimateMotionQCOM expects for its inputs.
static const char* kLumaVertSrc = R"(#version 300 es
out vec2 vUV;
void main() {
// ids 0,1,2 -> (-1,-1), (3,-1), (-1,3): one triangle covering the viewport
vec2 p = vec2((gl_VertexID == 1) ? 3.0 : -1.0,
(gl_VertexID == 2) ? 3.0 : -1.0);
vUV = (p + 1.0) * 0.5;
gl_Position = vec4(p, 0.0, 1.0);
})";
static const char* kLumaFragSrc = R"(#version 300 es
precision mediump float;
uniform mediump sampler2D uSrc;
in vec2 vUV;
out vec4 outColor;
void main() {
vec3 c = texture(uSrc, vUV).rgb;
outColor = vec4(0.299 * c.r + 0.587 * c.g + 0.114 * c.b, 0.0, 0.0, 1.0);
})";
// Compute shader: Bilinear upsample block-level MVs → per-pixel MVs
// glTexEstimateMotionQCOM outputs pixel displacements at block granularity.
// MobFGSR expects UV-space (normalized) motion vectors at per-pixel resolution.
static const char* kMVUpsampleSrc = R"(#version 310 es
layout(local_size_x=8,local_size_y=8) in;
uniform mediump sampler2D blockMV;
layout(rgba16f, binding=0) writeonly uniform mediump image2D perPixelMV;
uniform ivec2 renderSize;
uniform ivec2 blockSize;
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(p, renderSize))) return;
// Map pixel position to UV in [0,1] — bilinear sampling handles block boundaries
vec2 uv = (vec2(p) + 0.5) / vec2(renderSize);
// Sample block-level MV texture (bilinear interpolation upsamples automatically)
vec2 mvPixels = textureLod(blockMV, uv, 0.0).xy;
// Convert from pixel displacement to UV-space for MobFGSR shaders
vec2 mvUV = mvPixels / vec2(renderSize);
imageStore(perPixelMV, p, vec4(mvUV, 0.0, 0.0));
})";
// Compute shader: Nearest-depth dilation (from MobFGSR Dilate.comp)
static const char* kDilateSrc = R"(#version 310 es
layout(local_size_x=8,local_size_y=8) in;
layout(binding=0) uniform mediump sampler2D r_depth;
layout(binding=1) uniform mediump sampler2D r_mv;
layout(r32f, binding=0) writeonly uniform highp image2D rw_dilated_depth;
layout(rgba16f, binding=1) writeonly uniform mediump image2D rw_dilated_mv;
uniform ivec2 renderSize;
void main() {
ivec2 pos = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(pos, renderSize))) return;
const ivec2 offsets[8] = ivec2[8](
ivec2(-1,-1),ivec2(-1,0),ivec2(-1,1),ivec2(0,-1),
ivec2(0,1),ivec2(1,-1),ivec2(1,0),ivec2(1,1));
ivec2 nearestPos = pos;
float nearestDepth = texelFetch(r_depth, pos, 0).x;
for (int i=0; i<8; i++) {
ivec2 sp = clamp(pos + offsets[i], ivec2(0), renderSize - ivec2(1));
float d = texelFetch(r_depth, sp, 0).x;
if (d < nearestDepth) { nearestPos = sp; nearestDepth = d; }
}
vec2 mv = texelFetch(r_mv, nearestPos, 0).xy;
imageStore(rw_dilated_depth, pos, vec4(nearestDepth));
imageStore(rw_dilated_mv, pos, vec4(mv, 0.0, 0.0));
})";
// Compute shader: Clear reprojection buffer
static const char* kClearSrc = R"(#version 310 es
layout(local_size_x=8,local_size_y=8) in;
layout(r32ui, binding=0) writeonly uniform highp uimage2D rw_reproj;
void main() {
imageStore(rw_reproj, ivec2(gl_GlobalInvocationID.xy), uvec4(0xFFFFFFFFu));
})";
// Compute shader: Reproject with atomicMin (from MobFGSR Reproject_I.comp)
static const char* kReprojectSrc = R"(#version 310 es
// imageAtomicMin is not core until ES 3.2; on 3.1 it must be asked for by name.
// Adreno 840 advertises GL_OES_shader_image_atomic, so this compiles here —
// without it the shader failed with "requires extension ... to be enabled" and
// took the whole MobFGSR pipeline down with it.
#extension GL_OES_shader_image_atomic : require
layout(local_size_x=8,local_size_y=8) in;
layout(binding=0) uniform mediump sampler2D r_depth;
layout(binding=1) uniform mediump sampler2D r_cur_mv;
layout(binding=2) uniform mediump sampler2D r_prev_mv;
layout(r32ui, binding=0) coherent uniform highp uimage2D rw_reproj;
uniform ivec2 renderSize;
uniform float delta;
const uint depthBits = 11u;
const uint xBits = 11u;
const uint yBits = 10u;
const uint maxDepth = (1u << depthBits) - 1u;
const int minX = -(1 << (int(xBits)-1));
const int minY = -(1 << (int(yBits)-1));
const int maxX = (1 << (int(xBits)-1)) - 1;
const int maxY_ = (1 << (int(yBits)-1)) - 1;
void main() {
ivec2 pos = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(pos, renderSize))) return;
vec2 rsInv = 1.0 / vec2(renderSize);
vec2 uv = (vec2(pos) + 0.5) * rsInv;
vec2 mv_t1 = texelFetch(r_cur_mv, pos, 0).xy;
ivec2 pos_t0 = ivec2((uv - mv_t1) * vec2(renderSize));
vec2 mv_t0 = texelFetch(r_prev_mv, clamp(pos_t0,ivec2(0),renderSize-ivec2(1)), 0).xy;
float d2 = delta * 0.5;
float dw = delta * delta * 0.5;
vec2 uvDelta = uv + (-1.0+d2+dw)*mv_t1 + (d2-dw)*mv_t0;
if (all(greaterThanEqual(uvDelta, vec2(0.0))) && all(lessThanEqual(uvDelta, vec2(1.0)))) {
ivec2 posDelta = ivec2(uvDelta * vec2(renderSize));
float depth = texelFetch(r_depth, pos, 0).x;
uint uD = uint(float(maxDepth) * depth);
ivec2 rel = clamp(posDelta - pos, ivec2(minX,minY), ivec2(maxX,maxY_));
uvec2 uRel = uvec2(rel - ivec2(minX,minY));
uint data = (uD << (32u-depthBits)) | (uRel.x << yBits) | uRel.y;
imageAtomicMin(rw_reproj, posDelta, data);
}
})";
// Compute shader: Fill holes in reprojection (from MobFGSR Fill.comp)
static const char* kFillSrc = R"(#version 310 es
layout(local_size_x=8,local_size_y=8) in;
layout(binding=0) uniform highp usampler2D r_reproj;
layout(r32ui, binding=0) writeonly uniform highp uimage2D rw_filled;
uniform ivec2 renderSize;
const uint INV = 0xFFFFFFFFu;
const uint depthBits = 11u;
float unpackDepth(uint d) { return float(d >> (32u-depthBits)) / float((1u<<depthBits)-1u); }
void main() {
ivec2 pos = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(pos, renderSize))) return;
uint center = texelFetch(r_reproj, pos, 0).x;
float cDepth = unpackDepth(center);
float nearest = 1.0;
uint selected = INV;
uint mask = 1u << 4u;
const ivec2 off[9] = ivec2[9](
ivec2(-1,-1),ivec2(-1,0),ivec2(-1,1),
ivec2(0,-1),ivec2(0,0),ivec2(0,1),
ivec2(1,-1),ivec2(1,0),ivec2(1,1));
for (int i=0; i<9; i++) {
if (i==4) continue;
ivec2 np = clamp(pos+off[i], ivec2(0), renderSize-ivec2(1));
uint nd = texelFetch(r_reproj, np, 0).x;
float nDepth = unpackDepth(nd);
float diff = cDepth - nDepth;
if (nd != INV && diff > 0.0005) {
if (nDepth < nearest) { nearest = nDepth; selected = nd; }
} else { mask |= (1u << uint(i)); }
}
const uint rej[4] = uint[4](
(1u<<0u)|(1u<<1u)|(1u<<3u)|(1u<<4u),
(1u<<1u)|(1u<<2u)|(1u<<4u)|(1u<<5u),
(1u<<3u)|(1u<<4u)|(1u<<6u)|(1u<<7u),
(1u<<4u)|(1u<<5u)|(1u<<7u)|(1u<<8u));
bool reject = ((mask&rej[0])==rej[0])||((mask&rej[1])==rej[1])||
((mask&rej[2])==rej[2])||((mask&rej[3])==rej[3]);
uint result;
if (reject) { result = (center != INV) ? center : INV; }
else { result = selected; }
imageStore(rw_filled, pos, uvec4(result));
})";
// Compute shader: HUD mask — per-BLOCK accumulation of screen-static content
// (minimap frames, HP bars, buttons, prompts). Runs on the motion-estimation
// block grid (8x8 px on Adreno 840), so one texel per ME block; the warp
// shader bilinearly upsamples it for free.
//
// Two tests, both required — luma alone is fooled by static sky/ground, MV
// alone is fooled by small-magnitude real motion:
// 1. 9-tap mean |Δluma| at the block centre ≈ 0 (content isn't changing)
// 2. the block's motion vector length < threshold (ME agrees it isn't moving)
// A static block accumulates toward 1 (+0.10/frame ≈ 10 frames to lock), a
// moved block releases fast (−0.50/frame ≈ 2 frames) so it can never smear.
// Note this is SAFE for static WORLD content too: static world pixels are
// identical in curr and prev, so pinning them to curr is exact, not a guess.
static const char* kHudMaskSrc = R"(#version 310 es
layout(local_size_x=8,local_size_y=8) in;
layout(binding=0) uniform mediump sampler2D r_curr_luma;
layout(binding=1) uniform mediump sampler2D r_prev_luma;
layout(binding=2) uniform highp sampler2D r_block_mv;
layout(binding=3) uniform mediump sampler2D r_prev_mask;
// r32f, NOT r8: ESSL 3.10 only guarantees rgba32f/rgba16f/r32f/rgba8/
// rgba8_snorm/rgba*ui/r32ui/rgba*i/r32i as image formats. The Adreno compiler
// rejects r8, which failed the whole of initMobFGSR and silently downgraded
// method=motion to extrapolation.
layout(r32f, binding=0) writeonly uniform highp image2D rw_mask;
uniform ivec2 lumaSize;
uniform ivec2 blockSize;
uniform float lumaThr;
uniform float mvThr;
uniform float upRate;
uniform float downRate;
uniform float worldThr;
uniform float structThr;
float gradAt(mediump sampler2D t, ivec2 p, ivec2 lim) {
float l = texelFetch(t, clamp(p + ivec2(-1, 0), ivec2(0), lim), 0).x;
float r = texelFetch(t, clamp(p + ivec2( 1, 0), ivec2(0), lim), 0).x;
float u = texelFetch(t, clamp(p + ivec2( 0,-1), ivec2(0), lim), 0).x;
float d = texelFetch(t, clamp(p + ivec2( 0, 1), ivec2(0), lim), 0).x;
return abs(r - l) + abs(d - u);
}
void main() {
ivec2 blk = ivec2(gl_GlobalInvocationID.xy);
ivec2 maskSize = imageSize(rw_mask);
if (any(greaterThanEqual(blk, maskSize))) return;
ivec2 lim = lumaSize - ivec2(1);