forked from ppy/osu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOsuGameAndroid.cs
More file actions
2711 lines (2434 loc) · 145 KB
/
Copy pathOsuGameAndroid.cs
File metadata and controls
2711 lines (2434 loc) · 145 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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using Debug = System.Diagnostics.Debug;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Numerics;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using osu.Android.Native;
using osu.Framework.Logging;
using osu.Framework;
using osu.Android.Input;
using ManagedBass;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Input.Handlers.Tablet;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Game;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Screens;
using osu.Game.Screens.Play;
using osu.Framework.Audio;
using osu.Framework.Audio.Mixing;
using osu.Framework.Threading;
using osu.Android.Performance;
using osu.Game.Utils;
using osu.Game.Updater;
using osu.Game.Performance;
namespace osu.Android
{
public partial class OsuGameAndroid : OsuGame
{
private readonly OsuGameActivity gameActivity;
private readonly Lock packageInfoLock = new Lock();
private PackageInfo? packageInfo;
private bool packageInfoChecked;
private PackageInfo? getPackageInfo()
{
lock (packageInfoLock)
{
if (packageInfoChecked) return packageInfo;
try
{
packageInfo = gameActivity.PackageManager?.GetPackageInfo(gameActivity.PackageName!, 0);
}
catch
{
// ignore errors.
}
finally
{
packageInfoChecked = true;
}
return packageInfo;
}
}
public override Vector2 ScalingContainerTargetDrawSize => DrawWidth > 0 && DrawHeight > 0
? new Vector2(1024, 1024 * DrawHeight / DrawWidth)
: new Vector2(1024, 768);
private readonly Bindable<bool> performanceMode = new Bindable<bool>();
private readonly Bindable<AndroidAudioOutput> audioOutput = new Bindable<AndroidAudioOutput>();
private readonly Bindable<bool> vulkanProbeEnabled = new Bindable<bool>();
private readonly BindableDouble audioOffset = new BindableDouble();
// Last UTC ms timestamp at which the AudioOffset diagnostic log line fired.
// Used to rate-limit the diagnostic so a slider drag (which can fire 30+
// change events per second) doesn't spam the runtime.log. See the
// BindValueChanged subscription in load() for the rate-limit policy.
private long lastLoggedAudioOffsetMs;
// Layer 2/3 startup-safety toggles. Held as fields so the BindValueChanged
// subscriptions installed in load() outlive the BDL frame and continue to
// mirror updates into the on-disk sentinel files for the next launch.
private readonly Bindable<bool> cleanupStaleRealmFifos = new Bindable<bool>();
private readonly Bindable<bool> deferStartupNativeInit = new Bindable<bool>();
private readonly Bindable<bool> startupFrameSyncMigrationEnabled = new Bindable<bool>();
private readonly Bindable<bool> verboseLogging = new Bindable<bool>();
private readonly Bindable<bool> stylusAsTouch = new Bindable<bool>();
private readonly Bindable<bool> stylusDisableClick = new Bindable<bool>();
private readonly BindableFloat stylusPressureThreshold = new BindableFloat();
[Cached(typeof(IHighPerformanceSessionManager))]
private readonly IHighPerformanceSessionManager highPerformanceSessionManager = new AndroidHighPerformanceSessionManager();
private OboeAudioRedirector? audioRedirector;
private IDisposable? highPerformanceSession;
private IDisposable? dexPerformanceSession;
private Delegate? activeMixersHandler;
private object? activeMixersList;
// Cold-start safety nets that MUST keep firing even if the Update thread
// stalls on a Veldrid glslang shader-compile burst. Held as fields so the
// .NET threadpool kernel timer keeps the underlying ManagedTimerHolder
// alive (a System.Threading.Timer with no live root is eligible for GC).
// See LoadComplete for the rationale (Scheduler.AddDelayed runs on the
// Update thread and therefore cannot be relied on to fire the very
// safety nets that exist to unblock that thread).
private System.Threading.Timer? coldStartTamingTimer;
private System.Threading.Timer? clearStartupSentinelTimer;
// Set true the FIRST time the Draw thread executes a scheduled lambda
// after LoadComplete. The same heartbeat lambda also queues
// AndroidStartupSafeMode.ClearStartupInProgress onto a threadpool
// worker, so the IN_PROGRESS sentinel clears within ~1 s of LoadComplete
// on a healthy renderer (instead of being gated on the 25 s watchdog
// below). This prevents a perpetual safe-mode loop in which a user
// who restarts the app within 25 s of LoadComplete (e.g. immediately
// after switching Settings → Renderer → Vulkan) is permanently locked
// to OpenGL because LogManagement.ForceOpenGLRendererIfSafeMode
// rewrites their choice on every subsequent boot.
//
// The 25 s threadpool timer below remains as a fast-fail watchdog: if
// the heartbeat NEVER fires (Draw thread genuinely wedged inside the
// Veldrid Vulkan present queue — the cross-driver Adreno failure mode
// reproduced on multiple phones), we deliberately leave the
// IN_PROGRESS sentinel armed so the NEXT launch enters safe-mode
// (which forces Renderer = OpenGL via
// LogManagement.ForceOpenGLRendererIfSafeMode) and KillProcess so
// the user gets an automatic restart-into-safe-mode in 1-2 s instead
// of staring at a black screen.
//
// Deadline raised from 10 s → 25 s alongside the ppy.osu.Framework
// 2026.427.4 bump (which pulled in winnerspiros/veldrid b314005:
// VkSurfaceKHR loss recovery + bounded vkAcquireNextImageKHR). The
// framework now self-heals from a transient surface loss in 1-3 s on a
// good day, but a recovery that lands DURING the cold-start Toolbar
// texture-upload burst (600+ items) plus full swapchain+VkSurface
// rebuild can legitimately consume 8-12 s on Adreno. 25 s leaves clear
// headroom for that worst-case while still firing on a genuinely
// wedged renderer.
private volatile bool drawThreadEverPresented;
// Set true by the deferred SelectHighestRefreshRate call in LoadComplete; gates
// any earlier OnConfigurationChanged-driven SelectHighestRefreshRate() invocations
// out of the cold-start swapchain bring-up window. See SelectHighestRefreshRate.
private bool initialRefreshRateApplied;
private object? nativeBridges;
/// <summary>
/// Last value passed to <see cref="global::Android.App.Activity.RequestedOrientation"/> by
/// <see cref="updateOrientation"/>. Cached locally so we can short-circuit
/// redundant updates without round-tripping through the activity getter, which
/// itself performs a binder IPC on modern Android.
/// </summary>
private global::Android.Content.PM.ScreenOrientation? lastRequestedOrientation;
private int currentRefreshRate;
// One-shot System.Threading.Timer that runs a burst of background-thread taming passes
// when the user transitions into active gameplay. Cancelled and replaced on each new
// gameplay entry so repeated pause/resume cycles don't stack timers.
private System.Threading.Timer? gameplayThreadTamingTimer;
// Surface.setFrameRate() compatibility constants from android.view.Surface.
// Hard-coded because the Xamarin/.NET-for-Android bindings do not always expose
// these as named fields across binding versions.
// https://developer.android.com/reference/android/view/Surface#FRAME_RATE_COMPATIBILITY_FIXED_SOURCE
private const int FRAME_RATE_COMPATIBILITY_FIXED_SOURCE = 1;
// https://developer.android.com/reference/android/view/Surface#CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
private const int CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS = 0;
// android.app.GameState.MODE_* constants (API 33).
// Xamarin bindings expose these as ints rather than a dedicated enum;
// hard-coding the values avoids a binding version sensitivity and keeps
// them in line with the Surface constants pattern already established above.
// https://developer.android.com/reference/android/app/GameState#MODE_NONE
private const int GAME_STATE_MODE_NONE = 0;
// https://developer.android.com/reference/android/app/GameState#MODE_GAMEPLAY_UNINTERRUPTIBLE
private const int GAME_STATE_MODE_GAMEPLAY_UNINTERRUPTIBLE = 2;
// android.content.Context.GAME_STATE_SERVICE (API 33) — the service-name string
// used to obtain a GameStateManager instance via Context.getSystemService.
// Expressed as a string literal for the same binding-version-robustness reason
// as the Surface constants above.
private const string GAME_STATE_SERVICE = "game_state";
public OsuGameAndroid(OsuGameActivity activity)
: base(null)
{
gameActivity = activity;
}
public override string Version
{
get
{
if (!IsDeployedBuild)
return @"local " + (osu.Framework.Development.DebugUtils.IsDebugBuild ? @"debug" : @"release");
return getPackageInfo()?.VersionName ?? @"unknown";
}
}
public override Version AssemblyVersion
{
get
{
try
{
string? versionName = getPackageInfo()?.VersionName;
if (!string.IsNullOrEmpty(versionName))
return new Version(versionName.Split('-').First());
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Failed to parse assembly version: {e.Message}");
}
return new Version(@"0.0.0");
}
}
private AndroidStylusHandler? stylusHandler;
private AndroidMouseHandler? mouseHandler;
private AndroidKeyboardHandler? keyboardHandler;
/// <summary>
/// Background-loaded entry point. <paramref name="frameworkConfig"/> is injected
/// to drive <see cref="applyAndroidFrameSyncMigrationOnce"/>, the one-shot Android
/// FrameSync default migration; everything else here is unrelated init wiring.
/// </summary>
/// <remarks>
/// We must NOT take <see cref="OsuConfigManager"/> as a BDL parameter here. The
/// dependency activator resolves BDL parameters from the parent dependency
/// container, but <c>OsuGameBase.load</c> caches <c>LocalConfig</c> into
/// the child container (the one returned from <c>CreateChildDependencies</c>).
/// Resolving <c>OsuConfigManager</c> as a parameter therefore throws
/// <c>DependencyNotRegisteredException</c> before this method body even runs.
/// Use the inherited <see cref="OsuGameBase.LocalConfig"/> field instead — it is
/// guaranteed to be non-null because <c>SetHost</c> creates it before any BDL.
/// </remarks>
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager frameworkConfig)
{
LocalConfig.BindWith(OsuSetting.AndroidPerformanceMode, performanceMode);
LocalConfig.BindWith(OsuSetting.AndroidAudioOutput, audioOutput);
LocalConfig.BindWith(OsuSetting.AndroidVulkanProbe, vulkanProbeEnabled);
LocalConfig.BindWith(OsuSetting.AudioOffset, audioOffset);
// Diagnostic: log audio-offset changes so the next runtime.log conclusively
// shows whether the user's slider value reaches the global bindable. Field
// reports of "moving audio offset doesn't sync hitsounds" are ambiguous
// without this: either (a) the slider isn't writing to the bound setting
// (in which case we'd see no log line on slider drag), (b) it is writing
// but FramedBeatmapClock isn't re-reading (would still see lines here), or
// (c) the offset is shifting the gameplay clock correctly but Oboe pipeline
// introduces a constant-latency confounder that makes the audible shift
// smaller than expected.
//
// Rate-limited to avoid log spam while the user is actively dragging the
// slider (which can fire 30+ changes/sec): emit only when the delta exceeds
// 0.5ms OR ≥2s have elapsed since the last log. The first fire (initial
// bind, OldValue==NewValue) is also always emitted so the persisted value
// is captured at startup.
audioOffset.BindValueChanged(e =>
{
double delta = Math.Abs(e.NewValue - e.OldValue);
long nowMs = System.Environment.TickCount64;
bool firstFire = lastLoggedAudioOffsetMs == 0;
bool deltaSignificant = delta >= 0.5;
bool elapsedSignificant = (nowMs - lastLoggedAudioOffsetMs) >= 2_000;
if (firstFire || deltaSignificant || elapsedSignificant)
{
Logger.Log($"[osu!] AudioOffset changed: {e.OldValue:F1}ms → {e.NewValue:F1}ms", LoggingTarget.Performance);
lastLoggedAudioOffsetMs = nowMs;
}
}, true);
// Bind the three Android startup-safety toggles. The BindWith call
// wires each persistent OsuConfigManager setting to a long-lived
// field bindable, then a value-changed handler mirrors the current
// value into a tiny on-disk sentinel under FilesDir.
// OsuGameActivity.OnCreate runs LONG before the OsuConfigManager
// exists, so for any setting that gates pre-SetHost behaviour we
// need a config-manager-independent way to signal the user's
// preference into the next launch. The sentinel is read by
// AndroidStartupFlags in the activity.
try
{
LocalConfig.BindWith(OsuSetting.AndroidCleanupStaleRealmFifos, cleanupStaleRealmFifos);
LocalConfig.BindWith(OsuSetting.AndroidDeferStartupNativeInit, deferStartupNativeInit);
LocalConfig.BindWith(OsuSetting.AndroidStartupFrameSyncMigrationEnabled, startupFrameSyncMigrationEnabled);
LocalConfig.BindWith(OsuSetting.AndroidVerboseLogging, verboseLogging);
LocalConfig.BindWith(OsuSetting.AndroidStylusAsTouch, stylusAsTouch);
LocalConfig.BindWith(OsuSetting.AndroidStylusDisableClick, stylusDisableClick);
LocalConfig.BindWith(OsuSetting.AndroidStylusPressureThreshold, stylusPressureThreshold);
// Mirror the stylus-as-touch toggle into the volatile flag the OS-thread
// dispatch hot path reads on AndroidStylusHandler. Subscribed (not just
// set once) so toggling at runtime takes effect on the very next motion
// event. The handler instance may not yet exist at this point — the
// value is also re-applied at the bottom of registerInputHandlers() once
// the handler is constructed, so the initial value is never lost.
stylusAsTouch.BindValueChanged(e =>
{
if (stylusHandler != null)
stylusHandler.TreatAsTouch = e.NewValue;
}, true);
stylusDisableClick.BindValueChanged(e =>
{
if (stylusHandler != null)
stylusHandler.DisableClick = e.NewValue;
}, true);
// sentinelOnDisable=true → presence ⇒ "feature disabled". The
// safety nets default to ON, so the sentinel is created only
// when the user explicitly disables them.
mirrorStartupFlag(cleanupStaleRealmFifos, AndroidStartupFlags.FLAG_CLEANUP_REALM_FIFOS_DISABLED, sentinelOnDisable: true);
mirrorStartupFlag(deferStartupNativeInit, AndroidStartupFlags.FLAG_DEFER_NATIVE_INIT_DISABLED, sentinelOnDisable: true);
// sentinelOnDisable=false → presence ⇒ "feature enabled". The
// FrameSync migration and verbose-logging toggles both default
// to OFF, so the sentinel is created only when the user
// explicitly opts in.
mirrorStartupFlag(startupFrameSyncMigrationEnabled, AndroidStartupFlags.FLAG_FRAME_SYNC_MIGRATION_ENABLED, sentinelOnDisable: false);
mirrorStartupFlag(verboseLogging, AndroidStartupFlags.FLAG_VERBOSE_LOGGING_ENABLED, sentinelOnDisable: false);
// Mirror AndroidAudioOutput into the FLAG_BASS_AAUDIO_ENABLED sentinel.
// OsuGameActivity.OnCreate reads this before Bass.Init() and calls
// Bass.AndroidAAudio = true only when the flag is present (= AAudio selected).
// Oboe and AudioTrack do not need a startup-time sentinel (Oboe init is deferred
// post-game-load; AudioTrack is the BASS default when no flag is set).
void applyAudioOutputFlag(AndroidAudioOutput v)
=> AndroidStartupFlags.Set(AndroidStartupFlags.FLAG_BASS_AAUDIO_ENABLED, v == AndroidAudioOutput.AAudio);
applyAudioOutputFlag(audioOutput.Value);
audioOutput.BindValueChanged(e => applyAudioOutputFlag(e.NewValue));
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Startup-flag sentinel binding failed: {e.Message}");
}
// Layer 3a — only run the silent first-launch FrameSync migration
// if the user has explicitly opted back in via the new toggle.
// Default is OFF: the migration was added to fix a 120Hz Adreno
// present-queue starvation, but on a freshly-installed APK that
// hangs at startup we must not silently mutate framework defaults
// before we know the cold-start path is healthy.
//
// Additionally, if the previous launch died during startup
// (AndroidStartupSafeMode.IsActive) we ALWAYS skip the migration
// for this launch even if the user has enabled it — the goal is
// to recover the user back to a working game first.
if (startupFrameSyncMigrationEnabled.Value && !AndroidStartupSafeMode.IsActive)
applyAndroidFrameSyncMigrationOnce(frameworkConfig);
else if (startupFrameSyncMigrationEnabled.Value)
Debug.WriteLine("[osu!] FrameSync migration skipped this launch (safe-mode active)");
// NOTE: the three Android input handlers (stylus / mouse / keyboard) used to
// be created here and registered via `Host.AvailableInputHandlers.Add(...)`.
// That call is silently a no-op: `GameHost.AvailableInputHandlers` is an
// `ImmutableArray<InputHandler>` (see GameHost.cs in osu-framework), so
// `.Add(...)` returns a brand-new array and the result is discarded — the
// host's actual handler list is never updated, the input thread never polls
// our handlers, and S Pen / mouse / keyboard input that we intercepted in
// `OsuGameActivity.Dispatch*Event` was enqueued into a `PendingInputs`
// queue that no consumer ever drained. Registration now happens in
// `SetHost()` (synchronously, on the GameHost thread) via reflective
// replacement of the immutable array — see `registerAndroidInputHandlers`.
audioRedirector = new OboeAudioRedirector(Audio);
// The previous implementation watched AudioManager.activeMixers via reflection
// and called `audioRedirector.RefreshMixers(0)` whenever a per-store user
// mixer was added — necessary because the old redirector held a snapshot
// of mixer handles and had to re-attach new ones manually.
//
// The current OboeAudioRedirector goes through the framework's official
// `AudioManager.GlobalMixerHandle` hook, so any subsequently-created
// BassAudioMixer auto-attaches itself to our master mixer inside its own
// `createMixer` call (see osu.Framework BassAudioMixer.cs). The watch is
// no longer needed and would in fact be harmful: each invocation would
// tear down + recreate the master mixer + force every framework mixer to
// recreate, producing audible audio glitches every time a sample store was
// added. Field declarations are kept (null) so the existing dispose-time
// unbind code stays a no-op without further conditionals.
activeMixersList = null;
activeMixersHandler = null;
}
private void onActiveMixersChanged(object? sender, NotifyCollectionChangedEventArgs args)
{
// Intentionally a no-op — see comment in the constructor body where the
// active-mixers watch was previously bound.
}
protected override void LoadComplete()
{
// Crash-loop safe-mode: bypass CPU big-core affinity pinning entirely.
//
// Pinning Update + Draw + Input to a 5-core subset (mask 0xF8 on SD8G2) is the
// ONLY unconditional Android-specific synchronous mutation we still perform
// during the cold-start window — every other customisation (RequestUnbufferedDispatch,
// refresh-rate selection, Oboe / Vulkan-probe init,
// performance-mode GC-latency flip) is already deferred behind the
// refreshRateDelayMs scheduler below. Field logs.zip on v2026.423.176 show both
// a normal launch and a safe-mode launch dying silently mid-Toolbar load
// (~3 s after SetHost) before any deferred work has a chance to run, with no
// native_crash entry, no managed exception, and the 10 s native watchdog never
// firing — the fingerprint of an external SIGKILL (input-ANR or LMK). With
// every other mutation already deferred, affinity pinning is the last
// candidate. Pinning to a fixed CPU subset while Mono GC / finalizer / JIT
// threads run on default affinity (all cores) creates contention on the same
// big-cluster cores during the texture-upload burst; combined with the kernel
// load-balancer pulling the unpinned Android Main UI thread off the LITTLE
// cluster (because the big cluster looks "active" but is actually saturated),
// touch-event ACK can miss the 5 s input-dispatch deadline. Skipping the
// pinning in safe-mode gives the next launch a true vanilla cold-start path:
// if it survives, we have isolated the cause; if it does not, we have ruled
// out CPU pinning and the next iteration can target the next suspect with
// the heartbeat data captured below.
//
// Vulkan background-worker affinity note: the LITTLE-core affinity pin
// of background workers is still skipped for Vulkan (littleMask = 0
// below). The Adreno / Mali / Xclipse driver spawns internal worker
// threads whose comm names are not in our keep-alone list; if we push
// all unknown workers to the LITTLE subset those driver threads end up
// on slow cores and stall vkQueuePresentKHR. Renice-to-zero only is the
// correct policy for background workers on Vulkan.
//
// Draw + Input threads CAN now be pinned to big cores, for two reasons:
// 1. The workers are NOT pushed to little cores (littleMask = 0), so
// Adreno driver threads remain free to run on any core. The original
// stall was specifically the combination of Draw-on-big + workers-
// on-little; with only the Draw pin active the driver workers are
// unaffected.
// 2. Veldrid now has a 100 ms bounded vkAcquireNextImageKHR timeout
// (since ppy.osu.Framework 2026.503.1). Any residual contention
// is capped to one 100 ms stall rather than an indefinite hang.
// Pinning Draw to big cores significantly improves GPU command-recording
// throughput and texture-upload burst performance — the primary cause of
// the 35-40 fps observed in steady-state Vulkan gameplay.
bool vulkanConfigured = false;
try { vulkanConfigured = LogManagement.IsVulkanConfigured(); }
catch (Exception e) { Debug.WriteLine($"[osu!] IsVulkanConfigured probe failed: {e.Message}"); }
if (vulkanConfigured)
Logger.Log("[osu!] Vulkan renderer detected from framework.ini — pinning Draw/Input to big cores (worker LITTLE-core pin still skipped to keep Adreno/Mali driver workers schedulable).", LoggingTarget.Performance);
int affinityMask;
if (AndroidStartupSafeMode.IsActive)
{
affinityMask = 0;
CrashDiagnostics.WriteAliveMarker("LoadComplete: skipping CPU affinity pinning (safe-mode)");
Logger.Log("[osu!] CPU affinity pinning skipped (safe-mode active)", LoggingTarget.Performance);
}
else
{
// Use sysfs-based CPU topology for accurate big-core detection across all SoC vendors.
// Falls back to generic upper-half heuristic if native library unavailable.
affinityMask = AndroidNativeBridgeManager.GetBigCoreMask();
if (affinityMask == 0)
{
int coreCount = System.Environment.ProcessorCount;
int bigCoreStart = Math.Max(coreCount / 2, 1);
for (int i = bigCoreStart; i < Math.Min(coreCount, 32); i++)
affinityMask |= 1 << i;
if (affinityMask == 0)
affinityMask = (1 << Math.Min(coreCount, 31)) - 1;
}
}
try
{
if (affinityMask != 0 && OboeAudioBridge.nSetThreadAffinity(affinityMask) != 0)
Logger.Log($"[osu!] Update thread pinned to big cores (mask=0x{affinityMask:X})", LoggingTarget.Performance);
// Intentionally NOT calling Process.SetThreadPriority(UrgentDisplay) here.
//
// UrgentDisplay (-8 nice) is Android's display-compositor priority, intended for
// short, latency-critical UI bursts. Applying it continuously to Update + Draw +
// Input threads — all already pinned to a 5-core big-cluster subset (mask 0xF8 on
// SD8G2) — creates priority inversion against Mono's GC coordinator / finalizer /
// JIT threads, which run at default priority on the same cores. During cold-start
// bursts (texture upload queue draining, shader compile, beatmap import) the
// game-loop threads then preempt the GC coordinator indefinitely, the STW request
// never completes, every managed thread (incl. the SDLActivity main UI thread)
// stays parked in sigsuspend, and Android tears the process down with a 10s
// MotionEvent ANR — the "splash → black screen → ANR" fingerprint reported in
// logs.zip across multiple launches. CPU pinning alone is harmless; the priority
// elevation is what causes the inversion. Default SDL-set priorities are
// sufficient and match upstream osu! / osu-framework behaviour.
// Pin Draw + Input to big cores on all renderers.
// For Vulkan, see the comment above: workers are NOT pushed to little
// cores, so Adreno driver threads remain schedulable on any core.
int mask = affinityMask;
if (mask != 0)
{
Scheduler.Add(() =>
{
try
{
Host?.DrawThread?.Scheduler.Add(() =>
{
try
{
if (OboeAudioBridge.nSetThreadAffinity(mask) != 0) Logger.Log("[osu!] Render thread pinned to big cores", LoggingTarget.Performance);
}
catch { }
});
Host?.InputThread?.Scheduler.Add(() =>
{
try
{
if (OboeAudioBridge.nSetThreadAffinity(mask) != 0) Logger.Log("[osu!] Input thread pinned to big cores", LoggingTarget.Performance);
}
catch { }
});
}
catch (Exception e)
{
// The enclosing try/catch only covers the Scheduler.Add call — not the
// lambda body, which runs later on the update thread. Guard here so an
// NRE from Host.DrawThread/Host.InputThread being null (or a Host
// teardown race during startup) can't escape as an unhandled update-
// thread exception and kill the framework.
Debug.WriteLine($"[osu!] Failed to enqueue thread-affinity pinning for render/input threads: {e.Message}");
}
});
}
}
catch (Exception e)
{
Logger.Log($"[osu!] Failed to pin threads: {e.Message}", LoggingTarget.Performance);
}
// Tame background worker threads (Mono threadpool / shader-compile /
// OkHttp / Okio / unnamed "Thread-N" workers) out of the nice=-10
// display-compositor priority class Mono maps ThreadPriority.Highest
// to. Field tombstones from v177 show a Mono threadpool worker stuck
// in Veldrid's glslang::SetupBuiltinSymbolTable at nice=-10 on a big
// core while the Draw thread drains a 300+-item texture-upload queue
// — together starving the Android main UI thread past the 10s input-
// dispatch deadline and producing a MotionEvent ANR.
//
// The native helper walks /proc/self/task, identifies non-game
// workers by kernel comm, and drops them to nice=0. If we detected a
// big-core mask above, it ALSO pins those workers to the LITTLE-core
// subset (inverse of the big-core mask, masked against the real CPU
// count) so that shader-compile / network / finalizer work cannot
// preempt the Draw thread or the Android main UI thread.
//
// We apply this unconditionally — i.e. also during safe-mode — because
// the two latest safe-mode launches in logs.zip demonstrated that
// skipping CPU affinity pinning alone does NOT avoid the hang;
// background-thread priority elevation is the other half of the
// starvation equation and must be addressed independently.
//
// VULKAN OVERRIDE: pass mask=0 so the helper only does the renice-to-0
// pass and skips sched_setaffinity. See the top-of-LoadComplete
// rationale comment — pinning unidentified driver workers to the
// LITTLE subset is what stalls vkQueuePresentKHR.
//
// First apply runs synchronously here so any already-created workers
// are tamed immediately; additional apply passes are scheduled inside
// the refreshRateDelayMs block below to catch workers that are spawned
// later (Veldrid typically creates its shader-compile worker on first
// use, i.e. right when the Toolbar starts loading).
try
{
int coreCount = System.Environment.ProcessorCount;
int totalMask = coreCount >= 32 ? -1 : (1 << Math.Min(coreCount, 31)) - 1;
int littleMask = vulkanConfigured ? 0 : (~affinityMask) & totalMask;
if (!vulkanConfigured && littleMask == 0)
littleMask = totalMask; // fall back to "any core" if topology unknown.
int demoted = AndroidNativeBridgeManager.TameBackgroundThreads(littleMask);
if (demoted > 0)
Logger.Log($"[osu!] Tamed {demoted} background worker thread(s) to nice=0 (little-core mask=0x{littleMask:X}{(vulkanConfigured ? " — affinity skipped for Vulkan" : "")})", LoggingTarget.Performance);
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] TameBackgroundThreads (initial) failed: {e.Message}");
}
// Window.SetSustainedPerformanceMode is intentionally NOT called anywhere.
//
// On Samsung One UI / Adreno devices, calling SetSustainedPerformanceMode(true)
// triggers a non-seamless display-mode transition (even when deferred behind the
// texture-upload burst). The transition momentarily destroys the SurfaceView,
// which resets the surface pixel format back to the Android default (RGB565 on
// high-density Samsung panels). Our SurfaceChanged reactive guard then calls
// SurfaceHolder.SetFormat(RGBA8888), causing a second surface-destroy/recreate
// cycle. During this second cycle the ANativeWindow transiently reports the
// display's scaled (dp) dimensions — 1029×480 on a 3088×1440 3×-density panel —
// instead of the physical pixel dimensions. Veldrid reads those dimensions from
// vkGetPhysicalDeviceSurfaceCapabilitiesKHR during its VkSurfaceKHR-loss
// recovery, creates a permanent swapchain at 1029×480, and SurfaceFlinger tiles
// that sub-screen image 3×3 to fill the display. The result is the "9 screens"
// artifact, blurry/flashing textures, and a sustained FPS drop observed on
// Galaxy S24 Ultra (Adreno 740, One UI 7, Android 15) with Vulkan enabled.
//
// Removing the call eliminates the mid-session surface teardown. ADPF performance
// hinting is already provided by Oboe's setPerformanceHintEnabled(true) (set
// during stream open in oboe_bridge.cpp), and GC low-latency is handled by
// AndroidHighPerformanceSessionManager (SustainedLowLatency GCSettings) which
// covers the same thermal/responsiveness goals without touching the Surface.
base.LoadComplete();
// Always select the highest refresh rate on startup, regardless of performance mode.
// This ensures 120Hz+ displays are used at their native rate.
//
// Deferred by 5 s after LoadComplete so the initial Surface.setFrameRate call
// runs AFTER the Vulkan swapchain has stabilised and the first burst of texture
// uploads (Toolbar et al.) has drained off the Draw thread.
//
// Note: applyDisplayMode no longer writes window.Attributes.PreferredDisplayModeId
// (see that method's comment). Previously that write was the main reason for the
// cold-start ANR (non-seamless SurfaceView destruction mid-swapchain); the delay
// is retained as a safety margin for Surface.setFrameRate even though its
// ONLY_IF_SEAMLESS flag makes surface destruction unlikely.
//
// Under crash-loop safe-mode (previous launch died during startup) the delay
// is extended to 15 s so a slow-loading device that needed >5 s to drain
// the texture-upload backpressure last time gets a wider safety margin.
int refreshRateDelayMs = AndroidStartupSafeMode.IsActive ? 15_000 : 5_000;
// Repeat passes of background-thread taming during the Toolbar cold-start
// texture-upload burst. Veldrid spawns its shader-compile worker lazily
// on the first CompileGlslToSpirv call, which happens mid-Toolbar-load
// (i.e. after the synchronous taming pass above has already run). Without
// these follow-up passes, the newly-spawned worker inherits nice=-10
// from its parent and reproduces the starvation pattern.
//
// CRITICAL: these passes MUST run on the .NET threadpool (System.Threading.Timer),
// NOT on Scheduler.AddDelayed. Scheduler runs on the Update thread, which is
// exactly what we're trying to unblock — if the glslang worker has already
// started monopolising a big core at nice=-10 by the time the first deferred
// Scheduler tick is due, the Update thread is already starved and the tick
// never fires. Field tombstones (PIDs 27798/29226/499) confirm this: the +0
// and +500ms taming passes logged, but +1500/+3500ms never did, while a
// glslang worker remained at nice=-10 producing the 10s MotionEvent ANR.
// A kernel-managed Timer fires from the threadpool regardless of game-thread
// health, so the just-spawned worker is reliably caught and demoted within
// one tick (250 ms) of being created.
try
{
int coreCount = System.Environment.ProcessorCount;
int totalMask = coreCount >= 32 ? -1 : (1 << Math.Min(coreCount, 31)) - 1;
int deferredLittleMask;
if (AndroidStartupSafeMode.IsActive)
deferredLittleMask = totalMask; // safe-mode: affinity disabled, use full mask.
else if (vulkanConfigured)
deferredLittleMask = 0; // Vulkan: skip affinity pinning entirely (renice-only).
else
{
int bigMask = AndroidNativeBridgeManager.GetBigCoreMask();
deferredLittleMask = (~bigMask) & totalMask;
if (deferredLittleMask == 0) deferredLittleMask = totalMask;
}
int capturedMask = deferredLittleMask;
int tickCount = 0;
// Tick every 250 ms, give up after ~8 s — long enough to cover the entire
// observed Toolbar shader-compile burst window (mid-load through drain).
const int tick_period_ms = 250;
const int max_ticks = 32;
coldStartTamingTimer = new System.Threading.Timer(_ =>
{
try
{
int demoted = AndroidNativeBridgeManager.TameBackgroundThreads(capturedMask);
if (demoted > 0)
Logger.Log($"[osu!] Tamed {demoted} background worker thread(s) (timer tick {tickCount + 1})", LoggingTarget.Performance);
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Deferred TameBackgroundThreads (timer) failed: {e.Message}");
}
if (System.Threading.Interlocked.Increment(ref tickCount) >= max_ticks)
{
var t = System.Threading.Interlocked.Exchange(ref coldStartTamingTimer, null);
try { t?.Dispose(); }
catch { /* ignore */ }
}
}, state: null, dueTime: tick_period_ms, period: tick_period_ms);
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Failed to schedule deferred TameBackgroundThreads timer: {e.Message}");
}
Scheduler.AddDelayed(() =>
{
// Flip the gate FIRST, then run the actual query. Any subsequent
// OnConfigurationChanged-driven calls (DeX connect/disconnect, rotation)
// arriving after this point must be allowed to proceed normally; only
// the cold-start window (before this deferred call fires) is suppressed
// by initialRefreshRateApplied below.
initialRefreshRateApplied = true;
try { selectHighestRefreshRateCore(); }
catch (Exception ex)
{
Debug.WriteLine($"[osu!] Deferred SelectHighestRefreshRate failed: {ex.Message}");
}
// Deferred initial application of the user's performance-mode setting.
// The BindValueChanged registration below is WITHOUT the immediate-fire
// flag, so the very first apply (which may flip GCSettings.LatencyMode
// to SustainedLowLatency via AndroidHighPerformanceSessionManager) is
// done here, after the Toolbar texture-upload burst has drained. Running
// it synchronously during LoadComplete suppresses gen-2 GCs while the
// Draw thread is churning through hundreds of queued texture uploads,
// causing the managed heap to balloon, the kernel to start paging
// (VmSwap ~22 MB / RSS ~695 MB / memory-pressure avg10=1.34 observed in
// the ANR dump), the Draw thread to stall on a page-fault burst, and
// the main thread to miss its input-channel ACK deadline — another
// contributor to the MotionEvent ANR fingerprint.
try
{
applyPerformanceOptimizations(performanceMode.Value);
}
catch (Exception ex)
{
Debug.WriteLine($"[osu!] Deferred initial performance-mode apply failed: {ex.Message}");
}
// Deferred UI-thread RequestUnbufferedDispatch(sources). Moved here from
// the bottom of LoadComplete so the DecorView attribute mutation no
// longer races the cold-start Toolbar texture-upload burst. OnCreate
// already requested unbuffered dispatch once (with a dummy MotionEvent),
// and every per-pointer DispatchTouchEvent / DispatchGenericMotionEvent
// re-requests it as needed, so this global set-sources call is only a
// latency polish for the first few real touches after the burst — it
// brings no benefit during the black-screen window but does take a
// binder IPC round-trip through ViewRootImpl, which we do not want
// competing with swapchain settle work.
try
{
gameActivity.RunOnUiThread(() =>
{
try
{
int sources = (int)(InputSourceType.Touchscreen | InputSourceType.Stylus | InputSourceType.Mouse | InputSourceType.Touchpad);
gameActivity.Window?.DecorView?.RequestUnbufferedDispatch(sources);
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Failed to request unbuffered touch dispatch: {e.Message}");
}
});
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Failed to dispatch unbuffered-dispatch request to UI thread: {e.Message}");
}
}, refreshRateDelayMs);
// Clear the "startup in progress" sentinel once the current launch has
// survived ~25 s past LoadComplete. The sentinel governs the NEXT launch's
// safe-mode decision, not the current one (AndroidStartupSafeMode.IsActive
// is latched at OnCreate time and never changes mid-process). Window size
// is chosen to be longer than typical post-LoadComplete texture-upload
// bursts plus a worst-case Veldrid surface-lost recovery cycle (~8-12 s on
// Adreno) so we don't prematurely declare a recoverable transient failure
// a permanent one, but short enough that any genuinely surviving launch
// clears the sentinel before the user could reasonably trigger a manual
// restart. If the process dies before this fires (ANR, native crash, OOM
// kill), the sentinel persists and the next launch enters safe-mode.
//
// Fired from a kernel-managed System.Threading.Timer rather than
// Scheduler.AddDelayed: the same Update-thread stall that caused the
// Toolbar shader-compile ANR also prevents Scheduler.AddDelayed from
// firing the sentinel-clear, leaving safe-mode latched forever and
// every relaunch hitting the identical wall (confirmed by all three
// field tombstones — 27798 / 29226 / 499 — starting with "CPU affinity
// pinning skipped (safe-mode active)"). The threadpool tick is immune
// to game-thread starvation, so the sentinel reliably clears whenever
// the activity-main thread (and therefore the process) survives the
// deadline, breaking the perpetual-safe-mode loop.
// Schedule a one-shot lambda on the Draw thread that flips the
// drawThreadEverPresented flag. This runs AS SOON AS the Draw
// thread next dequeues a scheduled action, which in practice
// happens once it has presented at least one frame (Veldrid pumps
// the framework scheduler at the start of each Draw iteration).
// If the Draw thread is stuck in vkAcquireNextImageKHR /
// vkQueuePresentKHR (the failure mode reproduced across Adreno
// GPUs in this fork's Vulkan path), the lambda never runs and
// the gate below leaves IN_PROGRESS sentinel armed for next launch.
try
{
Host?.DrawThread?.Scheduler.Add(() =>
{
drawThreadEverPresented = true;
// Clear the IN_PROGRESS sentinel as soon as the Draw thread
// has demonstrably presented (i.e. successfully dequeued and
// executed a scheduled lambda). This is the actual signal of
// renderer health — once it fires we know the Vulkan/OpenGL
// path is up, so there is no reason to wait the full 25 s
// watchdog window before letting the next launch boot in
// normal mode.
//
// Why this matters: the previous design only cleared the
// sentinel from the 25 s threadpool timer below, which meant
// any user who restarted the app within 25 s of LoadComplete
// (e.g. immediately after flipping Settings → Renderer →
// Vulkan and being prompted to restart) was permanently
// trapped in safe-mode. Safe-mode rewrites their Vulkan
// choice back to OpenGL via LogManagement
// .ForceOpenGLRendererIfSafeMode on every subsequent boot,
// making it impossible to escape OpenGL.
//
// Clearing here closes that window: a healthy renderer
// surfaces the clear within ~1 s of LoadComplete, so any
// realistic user-initiated restart afterwards boots in
// normal mode and respects the user's renderer choice.
//
// File I/O is hopped to a threadpool worker so the Draw
// thread never blocks on disk. ClearStartupInProgress is
// idempotent (Interlocked.Exchange guard), so the 25 s
// timer's else-branch remains safe as a belt-and-braces
// fallback for the (vanishingly unlikely) case where the
// threadpool hop is dropped.
try
{
System.Threading.ThreadPool.QueueUserWorkItem(static _ =>
{
try
{
AndroidStartupSafeMode.ClearStartupInProgress();
}
catch (Exception clearEx)
{
Debug.WriteLine($"[osu!] ClearStartupInProgress (Draw-thread heartbeat) failed: {clearEx.Message}");
}
});
}
catch (Exception queueEx)
{
Debug.WriteLine($"[osu!] Could not queue ClearStartupInProgress from Draw-thread heartbeat: {queueEx.Message}");
}
});
}
catch (Exception ex)
{
Debug.WriteLine($"[osu!] Could not schedule Draw-thread first-frame heartbeat: {ex.Message}");
// Failsafe: if we can't even schedule the heartbeat, treat
// it as presented so we don't latch safe-mode forever on a
// pathologically small framework change.
drawThreadEverPresented = true;
}
try
{
clearStartupSentinelTimer = new System.Threading.Timer(_ =>
{
try
{
// Vulkan-stall gate: if the Draw thread never executed
// its first scheduled lambda within 25 s of LoadComplete,
// we assume the renderer is hung. Leave the IN_PROGRESS
// sentinel armed so the next launch will enter safe-mode
// (which rewrites Renderer = OpenGL via
// LogManagement.ForceOpenGLRendererIfSafeMode) and
// append a diagnostic block flagging the cause so the
// next-session log clearly identifies it.
if (!drawThreadEverPresented)
{
try
{
// Capture a /proc/self/task snapshot of every thread BEFORE
// KillProcess. Each row carries the kernel `wchan` (name of the
// kernel function the thread is sleeping in) and `syscall`
// (active syscall number + user-space PC), which together
// pinpoint exactly where the Draw thread is stuck — typically
// a futex inside the GPU driver's vkQueuePresentKHR /
// vkAcquireNextImageKHR, an Adreno binder wait, etc.
//
// Without this we have no visibility into Vulkan stalls beyond
// "Draw thread didn't tick", which makes every report opaque.
// The same snapshot logic is used by HangWatchdog for in-flight
// hangs; here we reuse it in the fatal-stall path.
string snapshot;
try { snapshot = HangWatchdog.CaptureProcTaskSnapshot(); }
catch (Exception snapEx) { snapshot = $" (snapshot failed: {snapEx.Message})\n"; }
CrashDiagnostics.AppendDiagnosticBlock(
"\n=========================================================\n"
+ "=== DRAW_THREAD_NEVER_PRESENTED ===\n"
+ $" utc_time = {DateTime.UtcNow:O}\n"
+ " reason = Draw thread did not execute a scheduled lambda within 25s of LoadComplete\n"
+ " effect = leaving FLAG_STARTUP_IN_PROGRESS set; killing process so next launch enters safe-mode\n"
+ " (which forces Renderer = OpenGL via LogManagement.ForceOpenGLRendererIfSafeMode)\n"
+ " suspect = Vulkan present-queue deadlock that survives Veldrid's bounded vkAcquireNextImageKHR\n"
+ " + VkSurfaceKHR-loss recovery (i.e. a genuinely broken Vulkan stack on this device,\n"
+ " not a transient surface loss). The framework's recovery cycle should fit comfortably\n"
+ " inside 25 s — if we tripped this gate, the device is reproducibly stuck.\n"
+ " hint = grep the snapshot below for `comm=Draw` / `comm=Audio` / `comm=Update` rows;\n"
+ " `wchan` names the kernel function the thread is sleeping in (e.g. `futex_wait_queue`,\n"
+ " `pipe_wait`), `syscall` carries the active syscall number + user-space PC. If the\n"
+ " Draw thread shows wchan=futex_* and syscall=98 (futex), the call originates from\n"
+ " vulkan.adreno.so; if it shows wchan=binder_*, the WSI is blocked on a SurfaceFlinger\n"
+ " round-trip; if it shows wchan=`do_epoll_wait`, the driver is parked between presents\n"
+ " (i.e. the freeze is upstream — likely a missed scheduler tick).\n"
+ "\n--- /proc/self/task snapshot ---\n"
+ snapshot
+ "=== END DRAW_THREAD_NEVER_PRESENTED ===\n\n");
}
catch (Exception ex)
{
Debug.WriteLine($"[osu!] DRAW_THREAD_NEVER_PRESENTED diagnostic block failed: {ex.Message}");
}
// IMPORTANT: do NOT call ClearStartupInProgress here. Leaving the
// sentinel set is the whole point of the gate.
// Active fast-fail: kill the process so the user gets an automatic
// restart-into-safe-mode in ~1-2 s instead of staring at a black
// screen until the OS ANR-kills (~30 s) or they manually force-quit.
// The IN_PROGRESS sentinel is already armed from
// AndroidStartupSafeMode.ApplyIfPreviousLaunchFailed in OnCreate, so
// the next launch is guaranteed to boot in OpenGL via
// LogManagement.ForceOpenGLRendererIfSafeMode. KillProcess is
// async-signal-safe and works from any thread (including this
// threadpool worker — we deliberately do NOT round-trip through
// the Activity UI thread because that thread is itself frequently
// stuck waiting on the Vulkan present-queue deadlock).
//
// PerformPlatformExit() goes through RunOnUiThread which would
// never fire if the UI thread is blocked, defeating the whole
// point of the fast-fail. Direct KillProcess gives a deterministic
// 1-2 s restart cycle (Activity.onDestroy + Application restart by
// the launcher) instead of an indefinite hang.
try
{
Logger.Log("[osu!] Vulkan stall detected — restarting in OpenGL via safe-mode latch", LoggingTarget.Performance, LogLevel.Important);
}
catch { /* logger may itself be stalled if the framework took a draw lock */ }
try { global::Android.OS.Process.KillProcess(global::Android.OS.Process.MyPid()); }
catch (Exception ex) { Debug.WriteLine($"[osu!] Vulkan-stall fast-fail KillProcess failed: {ex.Message}"); }
}
else
{
AndroidStartupSafeMode.ClearStartupInProgress();
}
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] ClearStartupInProgress (timer) failed: {e.Message}");
}
var ct = System.Threading.Interlocked.Exchange(ref clearStartupSentinelTimer, null);
try { ct?.Dispose(); }
catch { /* ignore */ }
}, state: null, dueTime: 25_000, period: System.Threading.Timeout.Infinite);
}
catch (Exception e)
{
Debug.WriteLine($"[osu!] Failed to schedule ClearStartupInProgress timer: {e.Message}");
}
// Cold-start heartbeat instrumentation. For the first 30 s after LoadComplete
// we emit per-second ALIVE markers from BOTH the Update thread and the Draw
// thread into native_crash.log, tagged with the originating thread name.
// This closes the diagnostic gap between the last "SetHost returning" marker
// (~22 s mark in field logs) and the 25 s ClearStartupInProgress marker that
// has so far never fired because the process is killed before it does. With
// per-second per-thread heartbeats, the next post-mortem can
// see exactly which thread (Update, Draw, both, or neither) was still alive