This commit is contained in:
Jan Pleterski
2026-11-13 09:15:17 +01:00
parent d3927aac8a
commit d4bc01f202
21 changed files with 294 additions and 1148 deletions
+46 -200
View File
@@ -1,15 +1,8 @@
import 'dart:async';
import 'package:flutter/foundation.dart' show compute, Uint8List;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:screenshot/screenshot.dart';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_mjpeg/flutter_mjpeg.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as img;
import 'yolo_detector.dart';
import 'preview_screen.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import '../utils/translations.dart';
import '../services/app_settings.dart';
@@ -18,17 +11,6 @@ import '../widgets/help_sheet.dart';
import '../widgets/image_settings.dart';
import '../services/wifi_binding.dart';
// Top-level: runs in background isolate via compute().
// Crops the capture to a square; filters are already baked into the screenshot.
Uint8List _processStreamImage(Uint8List bytes) {
final decoded = img.decodeImage(bytes)!;
final w = decoded.width, h = decoded.height;
final size = w < h ? w : h;
final cropped = img.copyCrop(decoded,
x: (w - size) ~/ 2, y: (h - size) ~/ 2, width: size, height: size);
return Uint8List.fromList(img.encodeJpg(cropped));
}
class CameraStreamScreen extends StatefulWidget {
final int cameraIndex; // shooting position 1–6
final String? ip; // chosen camera; falls back to the saved IP of the position
@@ -51,19 +33,12 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
with TickerProviderStateMixin {
String? _streamUrl;
bool _isError = false;
bool _isCapturing = false;
final ScreenshotController _screenshotController = ScreenshotController();
final TransformationController _transformationController =
TransformationController();
ImageAdjustments _image = const ImageAdjustments();
late YOLODetector _yoloDetector;
int _numberOfBullets = 5;
late AnimationController _zoomAnimController;
Animation<Matrix4>? _zoomAnimation;
Matrix4? _originalMatrix;
Color _bulletColor = Colors.blue;
String _selectedLanguage = 'English';
@@ -177,18 +152,11 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
_wifiReady = WifiBinding.acquire();
_loadAllPrefs();
YOLODetector.create().then((detector) => _yoloDetector = detector);
_setSystemBarStyle();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
_keepScreenAwake();
_zoomAnimController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
_shootProgressController = AnimationController(vsync: this);
_reloadProgressController = AnimationController(vsync: this);
_waitProgressController = AnimationController(vsync: this);
@@ -280,108 +248,6 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
});
}
Future<void> _captureAndPreviewImage() async {
if (_streamUrl == null || _isCapturing) return;
setState(() => _isCapturing = true);
_originalMatrix = _transformationController.value;
try {
final targetMatrix = Matrix4.identity()..scale(1.0);
final isZoomedIn = !_matrixEquals(_originalMatrix!, targetMatrix);
if (isZoomedIn) {
_zoomAnimController.reset();
_zoomAnimation = Matrix4Tween(
begin: _originalMatrix,
end: targetMatrix,
).animate(CurvedAnimation(
parent: _zoomAnimController,
curve: Curves.easeOut,
));
void updateZoom() {
_transformationController.value = _zoomAnimation!.value;
}
_zoomAnimController.addListener(updateZoom);
await _zoomAnimController.forward();
_zoomAnimController.removeListener(updateZoom);
}
await Future.delayed(const Duration(milliseconds: 100));
final imageBytes = await _screenshotController.capture();
if (imageBytes == null || imageBytes.isEmpty) return;
final dir = await getApplicationDocumentsDirectory();
final path = '${dir.path}/ip_capture_temp.jpg';
final processedBytes = await compute(_processStreamImage, imageBytes);
final file = File(path)..writeAsBytesSync(processedBytes);
// Detect objects in the image using YOLO
final detections = await _yoloDetector.detect(file);
if (!mounted) return;
// Navigate to the preview screen
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => PreviewScreen(
imagePath: file.path,
detections: detections,
bulletCount: _numberOfBullets,
),
),
);
} catch (e) {
debugPrint("❌ Capture error: $e");
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Capture failed: $e")),
);
}
} finally {
_zoomAnimController.reset();
_zoomAnimation = Matrix4Tween(
begin: _transformationController.value,
end: _originalMatrix!,
).animate(CurvedAnimation(
parent: _zoomAnimController,
curve: Curves.easeIn,
));
void restoreZoom() {
_transformationController.value = _zoomAnimation!.value;
}
_zoomAnimController.addListener(restoreZoom);
await _zoomAnimController.forward();
_zoomAnimController.removeListener(restoreZoom);
setState(() => _isCapturing = false);
}
}
img.Image invertImage(img.Image source) {
final result = img.Image.from(source);
for (int y = 0; y < result.height; y++) {
for (int x = 0; x < result.width; x++) {
final pixel = result.getPixel(x, y);
result.setPixelRgb(x, y, 255 - pixel.r, 255 - pixel.g, 255 - pixel.b);
}
}
return result;
}
bool _matrixEquals(Matrix4 a, Matrix4 b) {
for (int i = 0; i < 16; i++) {
if ((a.storage[i] - b.storage[i]).abs() > 0.001) return false;
}
return true;
}
void _showImageSettingsDialog() {
showImageSettingsSheet(
context,
@@ -462,8 +328,6 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
_reloadProgressController.dispose();
_waitProgressController.dispose();
_flashController.dispose();
_zoomAnimController.dispose();
_yoloDetector.close();
WifiBinding.release();
_restoreScreenSettings();
_setSystemBarStyle();
@@ -873,8 +737,9 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
// Manual counter dots — shown at top when timer not running
Widget _buildManualDotsOverlay() {
if (!_showManualCounter || _numberOfBullets <= 1)
if (!_showManualCounter || _numberOfBullets <= 1) {
return const SizedBox.shrink();
}
return Positioned(
top: 8,
left: 0,
@@ -1291,75 +1156,55 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
backgroundColor: Colors.black,
body: Stack(
children: [
Screenshot(
controller: _screenshotController,
child: LayoutBuilder(
builder: (context, constraints) {
return Center(
child: (_isError || _streamUrl == null)
? _buildErrorContent()
: InteractiveViewer(
clipBehavior: Clip.hardEdge,
constrained: false,
boundaryMargin: EdgeInsets.zero,
minScale: 1.0,
maxScale: 5.0,
transformationController: _transformationController,
child: SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
child: RepaintBoundary(
child: ColorFiltered(
colorFilter: _image.colorFilter,
child: RotatedBox(
quarterTurns: _image.quarterTurns,
child: Mjpeg(
key: ValueKey(_streamUrl),
stream: _streamUrl!,
isLive: true,
fit: BoxFit.contain,
error: (context, error, stackTrace) {
// Mark as error so we can display error placeholder outside filters
WidgetsBinding.instance
.addPostFrameCallback((_) {
if (mounted) {
setState(() {
_isError = true;
});
}
});
return SizedBox.expand(
child: Container(color: Colors.black),
);
},
),
LayoutBuilder(
builder: (context, constraints) {
return Center(
child: (_isError || _streamUrl == null)
? _buildErrorContent()
: InteractiveViewer(
clipBehavior: Clip.hardEdge,
constrained: false,
boundaryMargin: EdgeInsets.zero,
minScale: 1.0,
maxScale: 5.0,
transformationController: _transformationController,
child: SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
child: RepaintBoundary(
child: ColorFiltered(
colorFilter: _image.colorFilter,
child: RotatedBox(
quarterTurns: _image.quarterTurns,
child: Mjpeg(
key: ValueKey(_streamUrl),
stream: _streamUrl!,
isLive: true,
fit: BoxFit.contain,
error: (context, error, stackTrace) {
// Mark as error so we can display error placeholder outside filters
WidgetsBinding.instance
.addPostFrameCallback((_) {
if (mounted) {
setState(() {
_isError = true;
});
}
});
return SizedBox.expand(
child: Container(color: Colors.black),
);
},
),
),
),
),
),
);
},
),
),
);
},
),
if (_isCapturing)
Positioned.fill(
child: Container(
color: Colors.black.withValues(alpha: 0.4),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(color: Colors.white),
const SizedBox(height: 16),
Text(
_t("Processing image..."),
style: const TextStyle(color: Colors.white, fontSize: 16),
),
],
),
),
),
_buildManualDotsOverlay(),
_buildCountdownOverlay(),
// Phase-change flash overlay
@@ -1476,8 +1321,9 @@ class _CameraStreamScreenState extends State<CameraStreamScreen>
onTap: () async {
setState(() {
_manualCounterEnabled = !_manualCounterEnabled;
if (_manualCounterEnabled)
if (_manualCounterEnabled) {
_manualShotsLeft = _numberOfBullets;
}
});
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(