Repository navigation
Expand file tree
/
Copy pathDecoder.java
More file actions
executable file
·2300 lines (2125 loc) · 99.6 KB
/
Copy pathDecoder.java
File metadata and controls
executable file
·2300 lines (2125 loc) · 99.6 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) OpenIPC https://openipc.org Prosperity Public License 3.0.0
*
* Decoder.java — main activity for H.264/H.265 hardware video decoding
*
*/
package com.openipc.decoder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.PixelCopy;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class Decoder extends Activity
implements MenuManager.Listener {
private static final String TAG = "OpenIPCDecoder";
// --- Manager instances ---
AudioManager audioManager;
MediaCodecManager videoDecoder;
RtspClient rtspClient;
MenuManager menuManager;
// --- Shared state ---
final BlockingQueue<Frame> nalQueue = new ArrayBlockingQueue<>(32);
final FramePool framePool = new FramePool(50);
final NalAssembler nalAssembler = new NalAssembler(MediaCodecManager.MAX_NAL_SIZE, () -> {
closeDecoder();
nalQueue.clear();
}, framePool);
// --- UI components ---
// A SurfaceView, like the grid cells (#61), not a TextureView (#76): the decoder renders
// to a layer of its own, not through the app's window buffer, whose queueBuffer stalled
// for seconds and longer with every grid/single switch on Mali TV boxes
private SurfaceView mSurface;
/** The SurfaceView is hidden for a moment to get a new surface after MJPEG (#119). */
private boolean recreatingSurface;
/** Size of the video view without zoom (fitVideo()), 0 before the first frame. */
private int mFitWidth;
private int mFitHeight;
private Surface mVideoSurface;
private TextView statusText;
private float mDensity;
private View mClearOverlay;
// Quad mode
private boolean quadEnabled;
private QuadCell[] quadCells;
private LinearLayout quadContainer;
private final SurfaceView[] quadViews = new SurfaceView[CELL_COUNT];
// Quad audio (#12): the cell whose sound plays, -1 for none
private int quadAudio = -1;
private final TextView[] quadAudioBadges = new TextView[CELL_COUNT];
/** Small text in each cell's corner: stats while playing, otherwise the status (#80, #82). */
private final TextView[] quadStats = new TextView[CELL_COUNT];
/** Debug text in every cell (menu D), or in none (#92). */
private boolean showStats;
/** S (#108, #153): key frames only, in every view; saved as "slides". */
/** Read by the single view's decode thread too (Qodo on #155). */
private volatile boolean slides;
/** With the debug text on: where the debug page is (#96). */
private TextView debugUrls;
private volatile int quadAudioGen;
private ExecutorService quadAudioExecutor;
// Camera settings
/** Camera slots (#13). Multi-view shows 2x2, or 3x3 once a slot above 4 is in use. */
static final int CAM_COUNT = 8;
/** Index of the U cell (pushed UDP RTP, #87): the ninth cell of the 3x3 grid. */
static final int U_CELL = CAM_COUNT;
/** Multi-view cells: the slots and the U cell. */
static final int CELL_COUNT = CAM_COUNT + 1;
private static final String DEFAULT_URL = "rtsp://root:12345@192.168.1.10:554/stream=0";
private final String[] mHosts = new String[CAM_COUNT];
/** RTP transport per slot (#67): TCP, UDP or Auto (UDP with fallback to TCP). */
private final Transport.Mode[] mTransports = new Transport.Mode[CAM_COUNT];
private int mActive;
private volatile String mHost;
private String mVersion;
// Camera URLs (with passwords) are encrypted at rest (#16)
private CredentialStore credentials;
// Stored values that could not be decrypted: kept as they are until the slot is edited
private final String[] mUnreadable = new String[CAM_COUNT];
String mUserAgent = "User-Agent: OpenIPC-Decoder/1.0\r\n";
/** Short checks of the slots not on screen while the debug page is in use (#100). */
private StreamProbes streamProbes;
// Thread management
private volatile int listenerGen;
private ExecutorService executor;
// Pinch-to-zoom
private ScaleGestureDetector mScaleDetector;
private GestureDetector mGestureDetector;
private float mZoomScale = 1.0f;
private float mPanX;
private float mPanY;
private static final float ZOOM_MIN = 1.0f;
private static final float ZOOM_MAX = 5.0f;
// Screenshot
private boolean isTakingScreenshot;
// Stream size, for fitting the video view into the screen
private int mVideoWidth;
private int mVideoHeight;
// Codec/bitrate state for status overlay (pulled from RtspClient)
private volatile boolean codecH265;
private volatile String audioCodec = AudioConfig.NONE;
// Bitrate tracking (polled from RtspClient on "connected")
private long statusStreamBytes;
private long statusBitrateNs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.decoder);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
mVersion = getPackageManager()
.getPackageInfo(getPackageName(), PackageManager.PackageInfoFlags.of(0))
.versionName;
} else {
//noinspection deprecation
mVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
}
} catch (PackageManager.NameNotFoundException ignored) {}
mUserAgent = "User-Agent: OpenIPC-Decoder/" + mVersion + "\r\n";
streamProbes = new StreamProbes(mUserAgent);
mDensity = getResources().getDisplayMetrics().density;
credentials = CredentialStore.create();
// The decoder list for /stats.json, built off the UI thread (#88)
CodecInfo.warmUp();
// --- Create managers ---
videoDecoder = new MediaCodecManager(new MediaCodecManager.Listener() {
@Override public void onResolutionChanged(int w, int h) { updateResolution(w, h); }
@Override public void onDecoderStarted() { removeClearOverlay(); }
@Override public void onDecoderFailed() {}
});
audioManager = new AudioManager();
rtspClient = new RtspClient(framePool, nalAssembler, nalQueue);
rtspClient.setListener(new RtspClient.Listener() {
@Override public void onStatusChanged(String s) { updateStatus(s); }
@Override
public void onCodecChanged(boolean h265, AudioConfig audio) {
codecH265 = h265;
audioCodec = audio.codec;
boolean jpeg = rtspClient.isJpeg();
if (jpeg) {
// MJPEG has its own decoder or is drawn by the app (#119, #132): the
// video decoder must not hold the surface
closeDecoder();
} else {
jpegRenderer.release();
}
if (!jpeg && jpegRenderer.takeCanvasDrawn()) {
// A surface drawn with lockCanvas() cannot take a decoder any more: no
// decoder until the UI thread has put a new one in place (Qodo on #131)
surfacePending = true;
// Cleared once the new surface is there (surfaceCreated)
runOnUiThread(Decoder.this::recreateVideoSurface);
}
// RtspClient configures the AudioManager itself, on its own audio route
}
@Override public void onJitterSample(int avg) {
menuManager.updateQuality(avg);
menuManager.applyQualityToActive(quadEnabled, mActive);
}
@Override public void onDetail(String text) { showStatusDetail(text); }
});
rtspClient.setAudioManager(audioManager);
menuManager = new MenuManager(this, mDensity);
menuManager.setListener(this);
// --- UI setup ---
mSurface = findViewById(R.id.video_surface);
mSurface.setKeepScreenOn(true);
statusText = findViewById(R.id.status_text);
debugUrls = findViewById(R.id.debug_urls);
mSurface.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override public void surfaceCreated(SurfaceHolder holder) {
// The surface belongs to the SurfaceView: used, never released, here
replaceSurface(holder.getSurface());
// A new surface: nothing drawn into it with lockCanvas() yet (#132)
jpegRenderer.takeCanvasDrawn();
surfacePending = false;
recreatingSurface = false;
}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {}
@Override public void surfaceDestroyed(SurfaceHolder holder) {
// Nothing may render into the surface once this returns: close the decoder,
// the decode thread makes a new one when the next surface is there
replaceSurface(null);
closeDecoder();
if (recreatingSurface) {
// GONE has reached the surface: show the view again for a new one, unless
// the grid or the U view has taken the screen meanwhile (as in QuadCell)
recreatingSurface = false;
mSurface.post(() -> {
if (!quadEnabled && !udpViewShown) mSurface.setVisibility(View.VISIBLE);
});
}
}
});
// Pinch-to-zoom
mScaleDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override public boolean onScale(ScaleGestureDetector d) {
mZoomScale = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, mZoomScale * d.getScaleFactor()));
clampPan();
applyZoomTransform();
return true;
}
});
final View menuAnchor = findViewById(R.id.decoder);
// Rotation or a resized window: fit the video again (#31)
menuAnchor.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> {
if (r - l != or - ol || b - t != ob - ot) fitVideo();
});
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
if (mZoomScale > ZOOM_MIN) {
mPanX -= dx;
mPanY -= dy;
clampPan();
applyZoomTransform();
return true;
}
return false;
}
@Override public boolean onDoubleTap(MotionEvent e) { resetZoom(); return true; }
@Override public boolean onSingleTapConfirmed(MotionEvent e) {
menuManager.showMenu(menuAnchor, quadEnabled, mActive, mVersion,
BuildConfig.GIT_HASH, mHosts);
return true;
}
@Override public void onLongPress(MotionEvent e) { takeScreenshot(); }
});
mSurface.setOnTouchListener((v, event) -> {
// Pan moves the view itself (#76): the detectors get the touch in the parent's
// coordinates, which do not move with it, or each step would eat the next one
// (Qodo on #185)
MotionEvent inParent = MotionEvent.obtain(event);
inParent.offsetLocation(v.getLeft(), v.getTop());
mScaleDetector.onTouchEvent(inParent);
mGestureDetector.onTouchEvent(inParent);
inParent.recycle();
return true;
});
// Quad mode layout
quadContainer = new LinearLayout(this);
quadContainer.setOrientation(LinearLayout.VERTICAL);
quadContainer.setVisibility(View.GONE);
FrameLayout root = (FrameLayout) menuAnchor;
root.addView(quadContainer, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsetsController ctrl = getWindow().getInsetsController();
if (ctrl != null) {
ctrl.hide(WindowInsets.Type.navigationBars());
ctrl.setSystemBarsBehavior(
WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
}
} else {
//noinspection deprecation
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
updateStatus("disconnected");
DebugServer.get().setSource(debugSource);
}
// ====================== MenuManager.Listener ======================
@Override
public void onSwitchCamera(int slot) {
if (leaveUdpView()) {
// From the UDP view back to a slot: (re)start it even if it was the active one
mActive = slot;
saveSettings();
return;
}
if (slot == mActive && !quadEnabled) return;
if (quadEnabled) {
// Exit quad mode and switch to selected camera
stopQuad();
mActive = slot;
saveSettings();
return;
}
mActive = slot;
saveSettings();
}
@Override
public void onToggleQuad() {
// Q switches the view only; the playback mode is S's and stays as it is (#153)
if (leaveUdpView()) {
startQuad();
return;
}
boolean newState = !quadEnabled;
if (newState) {
startQuad();
} else {
stopQuad();
boolean configured = mHost != null && !mHost.isEmpty() && !mHost.equals(DEFAULT_URL);
if (configured) {
// A probe of this camera ends first: some take one client only (#100)
streamProbes.willShow(mHost);
rtspClient.configure(mHost, mUserAgent, mTransports[mActive]);
startListener();
rtspClient.start();
}
}
}
/**
* S (#108, #153): the playback mode only — every frame, or key frames only (the lowest
* decoder load) — in whatever view is shown: multi-view, U or a single camera. It never
* switches the view; Q does that.
*/
@Override
public void onToggleSlides() {
setSlides(!slides);
}
private void setSlides(boolean on) {
boolean changed = slides != on;
slides = on;
menuManager.setSlidesShown(on);
getSharedPreferences("settings", MODE_PRIVATE).edit().putBoolean("slides", on).apply();
if (!changed) return;
QuadCell[] cells = quadCells;
if (on && cells != null) {
for (QuadCell c : cells) if (c != null) c.setKeyFramesOnly(true);
}
// Back to adaptive: plan from scratch, cells are promoted again where they fit
// The decoders keep running: no warm-up (Qodo on #149)
if (!on && quadEnabled) decodePlanner = newPlanner(false);
// The single view: back to every frame from the next key frame on (#153)
if (!on) singleWaitKey = true;
Toast.makeText(this, on ? "Key frames only" : "Full stream", Toast.LENGTH_SHORT).show();
}
@Override
public void onToggleStats() {
showStats = !showStats;
getSharedPreferences("settings", MODE_PRIVATE).edit()
.putBoolean("show_stats", showStats).apply();
menuManager.setStatsShown(showStats);
updateDebugUrls();
// Apply at once instead of at the next second
QuadCell[] cells = quadCells;
for (int i = 0; i < quadStats.length; i++) {
QuadCell c = cells != null ? cells[i] : null;
if (quadStats[i] == null || c == null) continue;
quadStats[i].setVisibility(showStats ? View.VISIBLE : View.GONE);
}
Toast.makeText(this, showStats ? "Debug text on" : "Debug text off",
Toast.LENGTH_SHORT).show();
}
/** One line http://<address>:8085/ per device address while the debug text is on. */
private void updateDebugUrls() {
if (debugUrls == null) return;
if (!showStats) {
debugUrls.setVisibility(View.GONE);
return;
}
StringBuilder sb = new StringBuilder();
for (String ip : NetInfo.addresses()) {
if (sb.length() > 0) sb.append('\n');
sb.append("http://").append(ip).append(':').append(DebugServer.PORT).append('/');
}
if (sb.length() == 0) sb.append("Debug page: no network");
if (!sb.toString().contentEquals(debugUrls.getText())) debugUrls.setText(sb);
debugUrls.setVisibility(View.VISIBLE);
// Above the grid and its overlays, which are added later
ViewGroup parent = (ViewGroup) debugUrls.getParent();
if (parent.getChildAt(parent.getChildCount() - 1) != debugUrls) debugUrls.bringToFront();
}
@Override
public void onShowUdp() {
if (udpViewShown) return;
if (quadEnabled) {
stopQuad();
} else {
if (rtspClient != null) rtspClient.stop();
stopExecutor();
audioManager.closeAudio();
closeDecoder();
nalQueue.clear();
}
mSurface.setVisibility(View.GONE);
udpViewShown = true;
menuManager.setUdpShown(true);
startUdpGrid();
}
/** The U view (#87): a grid of one cell, the U cell, receiving on UDP_RTP_PORT. */
private void startUdpGrid() {
buildQuadGrid(1);
quadContainer.setVisibility(View.VISIBLE);
quadContainer.bringToFront();
ensureQuadLaidOut();
clearQuadViews();
createQuadCells();
}
/** Stops the cells of the grid, its audio and its stats; the views stay. */
private void stopQuadCells() {
quadContainer.removeCallbacks(quadStatsTick);
stopQuadAudio();
if (quadCells != null) {
for (QuadCell cell : quadCells) {
if (cell != null) cell.stop();
}
quadCells = null;
}
}
/** Hide the UDP view; true if it was shown. The caller starts what comes next. */
private boolean leaveUdpView() {
if (!udpViewShown) return false;
udpViewShown = false;
menuManager.setUdpShown(false);
stopQuadCells();
quadContainer.setVisibility(View.GONE);
resetDecoderStuck();
mSurface.setVisibility(View.VISIBLE);
return true;
}
@Override
public void onExit() { finishAndRemoveTask(); }
/**
* Reset (#171): stops every stream, deletes the stored settings, the key of the encrypted
* camera URLs and what WebUI kept (cookies, HTTP logins), then starts the app in a new
* process, so nothing kept in memory survives either.
*/
@Override
public void onReset() {
Log.i(TAG, "Reset: clearing all settings");
// commit(), not apply(): the process ends soon after. If the write fails, nothing
// else is touched and the app stays as it was, to try again (Qodo on #172)
if (!getSharedPreferences("settings", MODE_PRIVATE).edit().clear().commit()) {
Log.w(TAG, "Reset: the settings could not be cleared");
Toast.makeText(this, "Could not clear the settings, please try again",
Toast.LENGTH_LONG).show();
return;
}
if (quadEnabled) stopQuad();
if (rtspClient != null) rtspClient.stop();
closeDecoder();
closeAudio();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
KeystoreCipher.deleteKey();
} catch (Exception e) {
// The URLs it encrypted are gone already; the next save reuses the key
Log.w(TAG, "Reset: cannot delete the URL key: " + e.getMessage());
}
}
try {
android.webkit.WebViewDatabase.getInstance(this).clearHttpAuthUsernamePassword();
android.webkit.CookieManager cookies = android.webkit.CookieManager.getInstance();
// Restarted only once the cookies are really gone (Qodo on #172)
cookies.removeAllCookies(removed -> {
cookies.flush();
restartClean();
});
} catch (Exception e) {
// No WebView on this device (#15): nothing stored there either
restartClean();
}
}
/** Starts the app again in a new process after a reset (#171), through {@link Restart}. */
private void restartClean() {
Intent restart = new Intent(this, Restart.class);
restart.putExtra(Restart.EXTRA_PID, android.os.Process.myPid());
restart.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(restart);
}
@Override
public void onShowSettings() { menuManager.showUrlEditor(mActive, mHosts, mTransports); }
@Override
public void onWebUI() { menuManager.startBrowser(mHost); }
@Override
public void onSaveSettings() { saveSettings(); }
// ====================== Video lifecycle ======================
private void createDecoder() {
videoDecoder.setSurface(mVideoSurface);
videoDecoder.createDecoder(codecH265);
}
private void closeDecoder() { videoDecoder.closeDecoder(); }
// ====================== Audio lifecycle ======================
private void closeAudio() { audioManager.closeAudio(); }
// ====================== Settings ======================
@SuppressLint("AuthLeak")
private void loadSettings() {
SharedPreferences pref = getSharedPreferences("settings", MODE_PRIVATE);
if (pref.contains("host") && !pref.contains("host_0")) {
SharedPreferences.Editor edit = pref.edit();
edit.putString("host_0", credentials.seal(pref.getString("host", DEFAULT_URL)));
edit.putBoolean("type_0", pref.getBoolean("type", false));
edit.remove("host");
edit.remove("type");
edit.apply();
}
// Restore the last camera and mode (#22); both are saved but were never read back
mActive = clampSlot(pref.getInt("active", 0));
quadEnabled = pref.getBoolean("quad_enabled", false);
showStats = pref.getBoolean("show_stats", false);
slides = pref.getBoolean("slides", false);
if (menuManager != null) menuManager.setSlidesShown(slides);
if (menuManager != null) menuManager.setStatsShown(showStats);
SharedPreferences.Editor migrate = null;
for (int i = 0; i < CAM_COUNT; i++) {
String stored = pref.getString("host_" + i, null);
String url = credentials.open(stored);
mHosts[i] = url != null ? url : DEFAULT_URL;
mUnreadable[i] = url == null && stored != null ? stored : null;
// Auto for a slot that has never stored one (#112)
mTransports[i] = Transport.Mode.stored(pref.getString("transport_" + i, null));
// Plain URLs from older versions are re-saved encrypted right away
if (credentials.needsMigration(stored)) {
if (migrate == null) migrate = pref.edit();
migrate.putString("host_" + i, credentials.seal(stored));
}
}
if (migrate != null) migrate.apply();
Intent intent = getIntent();
String link = intent.getStringExtra(Intent.EXTRA_TEXT);
if (link != null) {
Log.d(TAG, "Link: " + Uri.parse(link).getHost());
mHosts[mActive] = sanitizeUrl(link);
// Optional, e.g. --es transport udp; a link without it keeps the slot's setting
String transport = intent.getStringExtra("transport");
if (transport != null) mTransports[mActive] = Transport.Mode.parse(transport);
// A shared link is meant to be watched: single view, and saved so that it is
// still there after the next pause/resume
quadEnabled = false;
pref.edit()
.putString("host_" + mActive, credentials.sealForSlot(
mHosts[mActive], mUnreadable[mActive], DEFAULT_URL))
.putBoolean("quad_enabled", false)
.putString("transport_" + mActive, mTransports[mActive].name())
.apply();
intent.removeExtra(Intent.EXTRA_TEXT);
}
applyActiveCamera();
}
static int clampSlot(int slot) {
return slot >= 0 && slot < CAM_COUNT ? slot : 0;
}
static String sanitizeUrl(String url) {
return url.replaceAll("[\r\n]", "");
}
private void applyActiveCamera() {
mHost = mHosts[mActive];
resetZoom();
if (mHost == null || mHost.isEmpty() || mHost.equals(DEFAULT_URL)) {
updateStatus("unconfigured");
} else {
updateStatus("connecting");
}
}
private void saveSettings() {
SharedPreferences pref = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("active", mActive);
for (int i = 0; i < CAM_COUNT; i++) {
edit.putString("host_" + i,
credentials.sealForSlot(mHosts[i], mUnreadable[i], DEFAULT_URL));
edit.putString("transport_" + i, mTransports[i].name());
}
edit.apply();
applyActiveCamera();
if (quadEnabled) return;
listenerGen++;
if (rtspClient != null) {
rtspClient.stop();
}
audioManager.closeAudio();
closeDecoder();
nalQueue.clear();
boolean configured = mHost != null && !mHost.isEmpty() && !mHost.equals(DEFAULT_URL);
if (!configured) {
clearVideo();
return;
}
// A probe of this camera ends first: some take one client only (#100)
streamProbes.willShow(mHost);
rtspClient.configure(mHost, mUserAgent, mTransports[mActive]);
startListener();
rtspClient.start();
}
// ====================== Status overlay ======================
// Delayed overlay updates after "connected"; cancelled on every status change
private final Runnable statusDetails = this::showConnectedDetails;
private final Runnable statusHide = () -> {
if (statusText != null) statusText.setVisibility(View.GONE);
};
private void showConnectedDetails() {
if (statusText == null || statusText.getVisibility() != View.VISIBLE) return;
String videoCodec = rtspClient != null && rtspClient.isJpeg() ? "MJPEG"
: codecH265 ? "H.265" : "H.264";
String aCodec;
switch (audioCodec) {
case AudioConfig.AAC: aCodec = " • AAC"; break;
case AudioConfig.OPUS: aCodec = " • Opus"; break;
case AudioConfig.PCMU:
case AudioConfig.PCMA: aCodec = " • G.711"; break;
case AudioConfig.PCM: aCodec = " • PCM"; break;
default: aCodec = ""; break;
}
long elapsedNs = System.nanoTime() - statusBitrateNs;
String bps = "";
long bytes = rtspClient != null ? rtspClient.getStreamBytes() : 0;
if (elapsedNs > 500_000_000 && bytes > 0) {
double mbps = (bytes * 8.0 / 1_000_000)
/ (elapsedNs / 1_000_000_000.0);
bps = String.format(Locale.US, " • %.1f Mbps", mbps);
}
// The transport the stream really uses, not the slot's setting (#115)
String inUse = rtspClient != null ? rtspClient.transportInUse() : null;
String transport = inUse != null
? Transport.label(inUse, mTransports[mActive]) + " • " : "";
statusText.setText("Connected • " + transport + videoCodec + aCodec + bps);
}
/**
* What a flowufo:// slot waits for (#187), in place of the plain status; posted after the
* status it belongs to, so it wins. Not shown once the stream plays.
*/
private void showStatusDetail(String text) {
runOnUiThread(() -> {
if (statusText == null || "connected".equals(singleState)) return;
statusText.setText(text);
statusText.setVisibility(View.VISIBLE);
});
}
private void updateStatus(String status) {
singleState = status;
runOnUiThread(() -> {
if (statusText == null) return;
// A stale timer from an earlier "connected" must not overwrite or hide this status
statusText.removeCallbacks(statusDetails);
statusText.removeCallbacks(statusHide);
switch (status) {
case "connecting":
statusText.setText(getString(R.string.status_connecting));
statusText.setVisibility(View.VISIBLE);
break;
case "connected":
statusText.setText(getString(R.string.status_connected));
statusText.setVisibility(View.VISIBLE);
statusStreamBytes = rtspClient != null ? rtspClient.getStreamBytes() : 0;
statusBitrateNs = rtspClient != null ? rtspClient.getBitrateMarkNs() : System.nanoTime();
// After 1 second, refresh with codec + bitrate info; hide after 5 seconds
statusText.postDelayed(statusDetails, 1000);
statusText.postDelayed(statusHide, 5000);
break;
case "disconnected":
statusText.setText(getString(R.string.status_disconnected));
statusText.setVisibility(View.VISIBLE);
break;
case "buffering":
statusText.setText(getString(R.string.status_buffering));
statusText.setVisibility(View.VISIBLE);
break;
case "unconfigured":
statusText.setText(getString(R.string.status_unconfigured));
statusText.setVisibility(View.VISIBLE);
break;
}
});
}
// ====================== Quad mode ======================
private void startQuad() {
// Every cell gets its own session: a probe would be a second client of its camera
streamProbes.stopAll();
if (rtspClient != null) {
rtspClient.stop();
}
closeDecoder();
closeAudio();
nalQueue.clear();
stopExecutor();
mSurface.setVisibility(View.GONE);
buildQuadGrid(quadGridSize(mHosts, DEFAULT_URL));
quadContainer.setVisibility(View.VISIBLE);
ensureQuadLaidOut();
removeClearOverlay();
createQuadCells();
quadEnabled = true;
getSharedPreferences("settings", MODE_PRIVATE).edit()
.putBoolean("quad_enabled", true).apply();
}
private void stopQuad() {
quadContainer.removeCallbacks(quadStatsTick);
stopQuadAudio();
quadEnabled = false;
getSharedPreferences("settings", MODE_PRIVATE).edit()
.putBoolean("quad_enabled", false).apply();
if (quadCells != null) {
for (QuadCell cell : quadCells) {
if (cell != null) cell.stop();
}
quadCells = null;
}
quadContainer.setVisibility(View.GONE);
resetDecoderStuck();
mSurface.setVisibility(View.VISIBLE);
}
/**
* Seen on an Android 10 TV box: after the window briefly lost visibility (a task brought
* to the front by another start), the Quad container stayed at 0x0 with no layout pass
* scheduled, so the cells never got a surface. Check once it should have been laid out
* and force a pass if not.
*/
private void ensureQuadLaidOut() {
quadContainer.postDelayed(() -> {
if (!(quadEnabled || udpViewShown) || quadContainer.getWidth() > 0) return;
Log.w(TAG, "Quad layout did not happen, forcing a layout pass");
View decor = getWindow().getDecorView();
for (View v = quadContainer; v != null && v != decor;
v = v.getParent() instanceof View ? (View) v.getParent() : null) {
v.forceLayout();
}
decor.requestLayout();
decor.invalidate();
}, 500);
}
/** Grid side for multi-view: 2 while only slots 1-4 are used, else 3 (#13). */
static int quadGridSize(String[] hosts, String defaultUrl) {
for (int i = 4; i < hosts.length; i++) {
String url = hosts[i];
if (url != null && !url.isEmpty() && !url.equals(defaultUrl)) return 3;
}
return 2;
}
/**
* (Re)build the multi-view grid; cells beyond it have no view. Side 3: the ninth cell is
* the U cell; side 1: the U cell alone (the U view).
*/
private void buildQuadGrid(int size) {
quadContainer.removeAllViews();
Arrays.fill(quadViews, null);
Arrays.fill(quadAudioBadges, null);
Arrays.fill(quadStats, null);
for (int row = 0; row < size; row++) {
LinearLayout lr = new LinearLayout(this);
lr.setOrientation(LinearLayout.HORIZONTAL);
quadContainer.addView(lr, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
for (int col = 0; col < size; col++) {
int idx = size == 1 ? U_CELL : row * size + col;
quadViews[idx] = new SurfaceView(this);
quadViews[idx].setOnClickListener(cv ->
menuManager.showMenu(findViewById(R.id.decoder), quadEnabled, mActive, mVersion,
BuildConfig.GIT_HASH, mHosts));
// Each cell is a FrameLayout so overlays can be stacked on the video
FrameLayout cell = new FrameLayout(this);
cell.addView(quadViews[idx], new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// Long press selects the cell whose audio plays (#12); the U cell has video only
if (idx != U_CELL) {
quadViews[idx].setOnLongClickListener(v -> {
toggleQuadAudio(idx);
return true;
});
}
TextView badge = new TextView(this);
badge.setText(R.string.quad_audio_badge);
badge.setTextColor(Color.WHITE);
badge.setTextSize(11);
badge.setBackgroundColor(0x99000000);
badge.setPadding(dp(6), dp(2), dp(6), dp(2));
badge.setVisibility(View.GONE);
FrameLayout.LayoutParams bp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.END);
bp.setMargins(dp(4), dp(4), dp(4), dp(4));
cell.addView(badge, bp);
quadAudioBadges[idx] = badge;
TextView stats = new TextView(this);
stats.setTextColor(Color.WHITE);
stats.setTextSize(10);
stats.setBackgroundColor(0x80000000);
stats.setPadding(dp(4), dp(1), dp(4), dp(1));
stats.setVisibility(View.GONE);
FrameLayout.LayoutParams sp = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.START);
sp.setMargins(dp(2), dp(2), dp(2), dp(2));
cell.addView(stats, sp);
quadStats[idx] = stats;
lr.addView(cell, new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.MATCH_PARENT, 1));
}
}
}
/** Port of the U cell (#68, #87); 5600 is the usual default for pushed RTP. */
static final int UDP_RTP_PORT = 5600;
/** What the U cell listens to: any sender, unicast, on UDP_RTP_PORT (#87). */
static final String UDP_CELL_URL = "udp://@:" + UDP_RTP_PORT;
/** The U cell full-screen (menu button U). */
private boolean udpViewShown;
/** Shown over the U cell until its first frame: where to send the stream. */
private TextView udpHintCell() {
TextView hint = new TextView(this);
hint.setText(udpHintText(NetInfo.addresses(), UDP_RTP_PORT));
hint.setTextColor(Color.GRAY);
hint.setTextSize(13);
hint.setGravity(Gravity.CENTER);
hint.setPadding(dp(12), dp(12), dp(12), dp(12));
hint.setBackgroundColor(Color.BLACK);
// Like the camera cells and the video view: a tap opens the menu
hint.setOnClickListener(v -> menuManager.showMenu(findViewById(R.id.decoder),
quadEnabled, mActive, mVersion, BuildConfig.GIT_HASH, mHosts));
return hint;
}
/** Keeps the addresses in the U cell's hint current (DHCP, cable, Wi-Fi), once a second. */
private void refreshUdpHint() {
SurfaceView v = quadViews[U_CELL];
if (v == null) return;
View overlay = ((View) v.getParent()).findViewWithTag("quad_overlay_" + U_CELL);
if (!(overlay instanceof TextView) || overlay.getVisibility() != View.VISIBLE) return;
String text = udpHintText(NetInfo.addresses(), UDP_RTP_PORT);
TextView hint = (TextView) overlay;
if (!text.contentEquals(hint.getText())) hint.setText(text);
}
/**
* Hint of the U cell: every usable IPv4 address of the device, one per line (#87). The
* addresses carry the port, so no separate port line.
*/
static String udpHintText(List<String> ips, int port) {
StringBuilder target = new StringBuilder();
for (String ip : ips) target.append('\n').append(ip).append(':').append(port);
if (target.length() == 0) target.append("\nthis device:").append(port);
return "Waiting for a stream\u2026\n\nSend the camera's RTP/UDP output to\n" + target;
}
private void createQuadCells() {
quadCells = new QuadCell[CELL_COUNT];
for (int i = 0; i < CELL_COUNT; i++) {
if (quadViews[i] == null) continue;
String url = i == U_CELL ? UDP_CELL_URL : mHosts[i];
if (url == null || url.isEmpty() || url.equals(DEFAULT_URL)) continue;
Transport.Mode mode = i == U_CELL ? Transport.Mode.UDP : mTransports[i];
quadCells[i] = new QuadCell(i, url, mode, quadViews[i], framePool, mUserAgent,
index -> runOnUiThread(() -> removeQuadOverlay(index)));
quadCells[i].start();
}
quadAudio = getSharedPreferences("settings", MODE_PRIVATE).getInt("quad_audio", -1);
startQuadAudio();
startStatsTick();
}
// ====================== Quad audio (#12) ======================
private void toggleQuadAudio(int index) {
quadAudio = quadAudio == index ? -1 : index;
getSharedPreferences("settings", MODE_PRIVATE).edit()
.putInt("quad_audio", quadAudio).apply();
applyQuadAudio();
Toast.makeText(this, quadAudio < 0 ? "Audio off"
: "Audio: camera " + (quadAudio + 1), Toast.LENGTH_SHORT).show();
}
/** Route audio of the selected cell to the AudioManager and update the badges. */
private void applyQuadAudio() {
// A new route: audio of a previously selected cell can no longer reach playback
int route = audioManager.newRoute();
QuadCell[] cells = quadCells;
for (int i = 0; i < CELL_COUNT; i++) {
QuadCell cell = cells != null ? cells[i] : null;
boolean on = i == quadAudio && cell != null;
if (cell != null) cell.setAudioSink(on ? audioManager : null, route);
if (on) audioManager.configure(cell.getAudioConfig(), route);
if (quadAudioBadges[i] != null) {
quadAudioBadges[i].setVisibility(on ? View.VISIBLE : View.GONE);
}
}
}