MIF_E31230910_MP-HRIS-MOBILE/lib/screens/presensi/camera_capture_screen.dart

508 lines
17 KiB
Dart

import 'dart:io';
import 'dart:ui';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';
import '../../core/theme.dart';
import '../../core/utils/camera_utils.dart';
import '../../widgets/atoms/custom_button.dart';
import '../../widgets/atoms/scanner_overlay.dart';
class CameraCaptureScreen extends StatefulWidget {
const CameraCaptureScreen({Key? key}) : super(key: key);
@override
State<CameraCaptureScreen> createState() => _CameraCaptureScreenState();
}
class _CameraCaptureScreenState extends State<CameraCaptureScreen>
with SingleTickerProviderStateMixin {
CameraController? _controller;
CameraDescription? _frontCamera;
bool _isCameraInitialized = false;
bool _isProcessingFrame = false;
// Quality gate
bool _isFaceDetected = false;
bool _isDistanceOk = false;
bool _isBrightnessOk = false;
double _faceRatio = 0.0;
double _brightness = 0.0;
// State rekam video
bool _isRecording = false;
bool _isRecordingDone = false;
XFile? _recordedVideo;
XFile? _capturedPhoto;
// Countdown
int _countdown = 1;
int _recordingSecondsLeft = 1;
late FaceDetector _faceDetector;
late AnimationController _pulseController;
bool get _allChecksValid =>
_isFaceDetected && _isDistanceOk && _isBrightnessOk;
String get _qualityMessage {
if (_isRecordingDone) return 'Video berhasil direkam ✓';
if (_isRecording) return 'Tetap hadap kamera... ($_recordingSecondsLeft detik)';
if (!_isFaceDetected) return 'Arahkan wajah ke dalam bingkai';
if (_faceRatio < 0.20) return 'Terlalu jauh, dekatkan wajah';
if (_faceRatio > 0.70) return 'Terlalu dekat, mundur sedikit';
if (!_isBrightnessOk) return 'Pencahayaan kurang terang';
return 'Siap — tekan tombol untuk merekam';
}
@override
void initState() {
super.initState();
_pulseController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800),
)..repeat(reverse: true);
_faceDetector = FaceDetector(
options: FaceDetectorOptions(
enableClassification: false,
enableLandmarks: false,
enableContours: false,
enableTracking: false,
performanceMode: FaceDetectorMode.fast,
),
);
_initializeCamera();
}
Future<void> _initializeCamera() async {
final cameras = await availableCameras();
_frontCamera = cameras.firstWhere(
(camera) => camera.lensDirection == CameraLensDirection.front,
orElse: () => cameras.first,
);
_controller = CameraController(
_frontCamera!,
ResolutionPreset.medium,
enableAudio: false,
imageFormatGroup: Platform.isAndroid
? ImageFormatGroup.nv21
: ImageFormatGroup.bgra8888,
);
await _controller!.initialize();
if (!mounted) return;
_controller!.startImageStream((CameraImage image) {
if (!mounted || _isRecording || _isRecordingDone) return;
_processFrame(image);
});
setState(() {
_isCameraInitialized = true;
});
}
void _processFrame(CameraImage image) async {
if (_isProcessingFrame) return;
_isProcessingFrame = true;
try {
_brightness = BrightnessUtils.calculateBrightness(image);
_isBrightnessOk = _brightness > 60;
final inputImage = CameraUtils.inputImageFromCameraImage(
image: image,
camera: _frontCamera!,
rotation: CameraUtils.rotationIntToImageRotation(
_frontCamera!.sensorOrientation),
);
final faces = await _faceDetector.processImage(inputImage);
if (faces.isNotEmpty) {
final face = faces.first;
final imageWidth = image.width.toDouble();
_faceRatio = face.boundingBox.width / imageWidth;
_isFaceDetected = true;
_isDistanceOk = _faceRatio >= 0.20 && _faceRatio <= 0.70;
} else {
_isFaceDetected = false;
_isDistanceOk = false;
_faceRatio = 0.0;
}
if (mounted) setState(() {});
} catch (e) {
debugPrint("Error processing frame: $e");
} finally {
_isProcessingFrame = false;
}
}
Future<void> _startRecording() async {
if (!_allChecksValid || _isRecording) return;
try {
await _controller!.stopImageStream();
} catch (_) {}
XFile? photo;
try {
photo = await _controller!.takePicture();
} catch (e) {
debugPrint("Gagal mengambil foto: $e");
}
setState(() {
_isRecording = true;
_recordingSecondsLeft = 1;
});
HapticFeedback.mediumImpact();
await _controller!.prepareForVideoRecording();
await _controller!.startVideoRecording();
// Countdown 1 detik
for (int i = 1; i >= 1; i--) {
if (!mounted) return;
setState(() => _recordingSecondsLeft = i);
await Future.delayed(const Duration(seconds: 1));
}
if (!mounted) return;
final video = await _controller!.stopVideoRecording();
HapticFeedback.heavyImpact();
setState(() {
_isRecording = false;
_isRecordingDone = true;
_recordedVideo = video;
_capturedPhoto = photo;
});
}
void _retake() {
setState(() {
_isRecording = false;
_isRecordingDone = false;
_recordedVideo = null;
_capturedPhoto = null;
_isFaceDetected = false;
_isDistanceOk = false;
_isBrightnessOk = false;
});
_controller!.startImageStream((CameraImage image) {
if (!mounted || _isRecording || _isRecordingDone) return;
_processFrame(image);
});
}
void _useVideo() {
if (_recordedVideo != null) {
Navigator.pop(context, {
'video': File(_recordedVideo!.path),
'photo': _capturedPhoto != null ? File(_capturedPhoto!.path) : null,
});
}
}
@override
void dispose() {
_pulseController.dispose();
_controller?.dispose();
_faceDetector.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
shape: BoxShape.circle,
),
child: const Icon(Icons.close, color: Colors.white, size: 16),
),
onPressed: () => Navigator.pop(context),
),
),
body: Stack(
children: [
// Preview kamera
if (_isCameraInitialized)
SizedBox.expand(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: _controller!.value.previewSize?.height ??
MediaQuery.of(context).size.width,
height: _controller!.value.previewSize?.width ??
MediaQuery.of(context).size.height,
child: CameraPreview(_controller!),
),
),
)
else
const Center(child: CircularProgressIndicator(color: Colors.white)),
// Overlay sambil recording: REC badge + countdown besar
if (_isRecording)
Positioned.fill(
child: Container(
color: Colors.black.withOpacity(0.15),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 80),
AnimatedBuilder(
animation: _pulseController,
builder: (context, child) => Container(
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.red.withOpacity(
0.7 + 0.3 * _pulseController.value),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 10,
height: 10,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
const Text('REC',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14)),
],
),
),
),
],
),
),
),
),
// Scanner overlay
ScannerOverlay(
borderColor: _isRecordingDone
? AppTheme.statusGreen
: _isRecording
? Colors.red
: _allChecksValid
? AppTheme.statusGreen
: _isFaceDetected
? AppTheme.statusYellow
: AppTheme.primaryBlue,
isScanning: !_isRecordingDone,
),
// Header info
Positioned(
top: MediaQuery.of(context).padding.top + kToolbarHeight + 20,
left: 20,
right: 20,
child: Column(
children: [
Text(
_isRecording
? 'Merekam Video...'
: _isRecordingDone
? 'Video Siap'
: 'Rekam Video Wajah',
style: AppTheme.heading3.copyWith(color: Colors.white),
),
const SizedBox(height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.15),
borderRadius: BorderRadius.circular(20),
border:
Border.all(color: Colors.white.withOpacity(0.3)),
),
child: Text(
_qualityMessage,
textAlign: TextAlign.center,
style: AppTheme.bodyLarge.copyWith(
color: _isRecordingDone
? AppTheme.statusGreen
: _isRecording
? Colors.red.shade200
: _allChecksValid
? AppTheme.statusGreen
: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
// Quality chips (sebelum rekam)
if (!_isRecording && !_isRecordingDone) ...[
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildChip(Icons.face, 'Wajah', _isFaceDetected),
const SizedBox(width: 6),
_buildChip(Icons.straighten, 'Jarak', _isDistanceOk),
const SizedBox(width: 6),
_buildChip(
Icons.wb_sunny_outlined, 'Cahaya', _isBrightnessOk),
],
),
],
// Countdown bundar besar saat merekam
if (_isRecording) ...[
const SizedBox(height: 20),
Container(
width: 72,
height: 72,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.red, width: 3),
color: Colors.black.withOpacity(0.4),
),
child: Center(
child: Text(
'$_recordingSecondsLeft',
style: const TextStyle(
color: Colors.white,
fontSize: 36,
fontWeight: FontWeight.bold,
),
),
),
),
],
],
),
),
// Tombol bawah
Positioned(
bottom: 40,
left: 20,
right: 20,
child: _isRecordingDone
? Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: CustomButton(
text: "Rekam Ulang",
type: ButtonType.secondary,
onPressed: _retake,
icon: Icons.refresh,
),
),
const SizedBox(width: 16),
Expanded(
child: CustomButton(
text: "Gunakan",
type: ButtonType.primary,
onPressed: _useVideo,
icon: Icons.check,
backgroundColor: AppTheme.statusGreen,
),
),
],
)
: _isRecording
? const SizedBox.shrink()
: Center(
child: GestureDetector(
onTap: _allChecksValid ? _startRecording : null,
child: Container(
width: 76,
height: 76,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: _allChecksValid
? Colors.white.withOpacity(0.8)
: Colors.white.withOpacity(0.3),
width: 6,
),
color: _allChecksValid
? Colors.red.withOpacity(0.8)
: Colors.white.withOpacity(0.05),
boxShadow: _allChecksValid
? [
BoxShadow(
color: Colors.red.withOpacity(0.4),
blurRadius: 16,
)
]
: null,
),
child: const Icon(
Icons.videocam,
color: Colors.white,
size: 30,
),
),
),
),
),
],
),
);
}
Widget _buildChip(IconData icon, String label, bool isOk) {
final color = isOk ? AppTheme.statusGreen : Colors.white.withOpacity(0.4);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.15),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: color.withOpacity(0.4)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(isOk ? Icons.check_circle : icon, color: color, size: 12),
const SizedBox(width: 4),
Text(label,
style: TextStyle(
color: color, fontSize: 10, fontWeight: FontWeight.w600)),
],
),
);
}
}