import { useFocusEffect } from "@react-navigation/native"; import { useAudioPlayer } from "expo-audio"; import { CameraView, useCameraPermissions } from "expo-camera"; import React, { useCallback, useEffect, useRef, useState } from "react"; import { Platform, Text, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import Svg, { Circle } from "react-native-svg"; import GradientButton from "../../components/GradientButton"; import MusicLandHeader from "../../components/MusicLandHeader"; import { increment, projectsRef } from "../../config/firebase"; import { Routes } from "../../navigation"; import { goBack, navigate } from "../../navigation/NavigationService"; import { gutters, Palette } from "../../styles"; import { FONT_FAMILY } from "../../styles/Fonts"; import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader"; /** * RecordPlayback — refactor robuste du compteur * * Correction de l'auto-start : on garde un flag countdownActiveRef pour * empêcher l'effet de se déclencher tant que le timer n'a pas réellement démarré. * On affiche 5→1 puis on bascule (pas de 0 visible) pour éviter le "bloqué sur 1". */ const TIME_BEFORE_INCREMENT_MS = 20000; // 20s const RecordPlayback = ({ route }) => { const { top } = useSafeAreaInsets(); const { project } = route.params || {}; // Permissions const [cameraPermission, requestCameraPermission] = useCameraPermissions(); // Refs const cameraRef = useRef(null); const countdownTimerRef = useRef(null); const listenTimerRef = useRef(null); const checkSongEndRef = useRef(null); const stopRequestedRef = useRef(false); const startedRef = useRef(false); // empêche les doubles démarrages const countdownActiveRef = useRef(false); // évite le déclenchement avant 1er tick // Compteurs vues const listenedMsRef = useRef(0); const incrementDoneRef = useRef(false); // UI / state const [isPreparing, setIsPreparing] = useState(false); const [countdown, setCountdown] = useState(0); const [isRecording, setIsRecording] = useState(false); const [showProgress, setShowProgress] = useState(false); const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 }); // Musique const songUrl = project?.songUrl || null; const player = useAudioPlayer(songUrl ? { uri: songUrl } : undefined); useEffect(() => { listenedMsRef.current = 0; incrementDoneRef.current = false; }, [songUrl]); // Poll player -> progress ring useEffect(() => { if (!player) return; const id = setInterval(() => { try { const dur = (player?.duration || 0) * 1000; const pos = (player?.currentTime || 0) * 1000; setProgressInfo({ pos, dur }); } catch (_) {} }, 250); return () => clearInterval(id); }, [player]); // Permissions au mount + cleanup useEffect(() => { (async () => { try { if (!cameraPermission?.granted) await requestCameraPermission(); } catch (_) {} })(); return () => { try { if (countdownTimerRef.current) clearInterval(countdownTimerRef.current); if (listenTimerRef.current) clearInterval(listenTimerRef.current); if (checkSongEndRef.current) clearInterval(checkSongEndRef.current); countdownTimerRef.current = null; listenTimerRef.current = null; checkSongEndRef.current = null; } catch (_) {} }; }, []); // eslint-disable-line react-hooks/exhaustive-deps // Reset complet const resetSession = useCallback(async () => { try { if (countdownTimerRef.current) { clearInterval(countdownTimerRef.current); countdownTimerRef.current = null; } if (listenTimerRef.current) { clearInterval(listenTimerRef.current); listenTimerRef.current = null; } if (checkSongEndRef.current) { clearInterval(checkSongEndRef.current); checkSongEndRef.current = null; } startedRef.current = false; stopRequestedRef.current = false; countdownActiveRef.current = false; listenedMsRef.current = 0; incrementDoneRef.current = false; setIsPreparing(false); setIsRecording(false); setShowProgress(false); setCountdown(0); if (player) { try { if (player.playing) await player.pause?.(); await player.seekTo?.(0); } catch (_) {} } } catch (_) {} }, [player]); useFocusEffect( useCallback(() => { void resetSession(); return () => {}; }, [resetSession]) ); // Lancer le compte à rebours (le tick décrémente uniquement) const startCountdownThenRecord = async () => { if (!songUrl) return; await resetSession(); setIsPreparing(true); setShowProgress(false); setCountdown(5); // On démarre l'intervalle puis on active le flag if (countdownTimerRef.current) { clearInterval(countdownTimerRef.current); countdownTimerRef.current = null; } countdownTimerRef.current = setInterval(() => { setCountdown((c) => Math.max(0, c - 1)); }, 1000); countdownActiveRef.current = true; }; // Quand le compteur a réellement démarré ET atteint 0, on démarre useEffect(() => { if (!isPreparing) return; if (!countdownActiveRef.current) return; // évite l'auto-start if (countdown === 0 && !startedRef.current) { startedRef.current = true; if (countdownTimerRef.current) { clearInterval(countdownTimerRef.current); countdownTimerRef.current = null; } countdownActiveRef.current = false; // Bascule après rendu de la frame courante requestAnimationFrame(() => { setIsPreparing(false); setShowProgress(true); void startRecordingWithMusic(); }); } }, [countdown, isPreparing]); const startRecordingWithMusic = async () => { try { stopRequestedRef.current = false; listenedMsRef.current = 0; incrementDoneRef.current = false; setIsRecording(true); setShowProgress(true); const recordPromise = cameraRef.current?.recordAsync?.({ mute: true, maxDuration: 600, }); if (player && songUrl) { try { await player.seekTo?.(0); } catch (_) {} await player.play?.(); } // Incrément des vues if (!listenTimerRef.current && project?.id) { listenTimerRef.current = setInterval(async () => { try { if (player?.playing) { listenedMsRef.current += 500; if ( !incrementDoneRef.current && listenedMsRef.current >= TIME_BEFORE_INCREMENT_MS ) { incrementDoneRef.current = true; try { await projectsRef .doc(project.id) .set({ views: increment(1) }, { merge: true }); } catch (_) {} } } } catch (_) {} }, 500); } // Fin du morceau -> stop recording if (!checkSongEndRef.current) { checkSongEndRef.current = setInterval(() => { try { if (!player) return; const duration = (player?.duration || 0) * 1000; const currentTime = (player?.currentTime || 0) * 1000; if ( (!player.playing && !stopRequestedRef.current) || (duration > 0 && currentTime >= duration - 600) ) { stopRequestedRef.current = true; if (checkSongEndRef.current) { clearInterval(checkSongEndRef.current); checkSongEndRef.current = null; } try { cameraRef.current?.stopRecording?.(); } catch (_) {} } } catch (_) {} }, 500); } const video = await recordPromise; if (checkSongEndRef.current) { clearInterval(checkSongEndRef.current); checkSongEndRef.current = null; } try { if (player?.playing) await player.pause?.(); } catch (_) {} if (listenTimerRef.current) { clearInterval(listenTimerRef.current); listenTimerRef.current = null; } setIsRecording(false); setShowProgress(false); if (video?.uri) navigate(Routes.RecordedPlayback, { videoUri: video.uri, project }); else navigate(Routes.RecordedPlayback, { project }); } catch (e) { console.log("RecordPlayback error:", e); setIsRecording(false); setIsPreparing(false); setShowProgress(false); if (listenTimerRef.current) { clearInterval(listenTimerRef.current); listenTimerRef.current = null; } if (checkSongEndRef.current) { clearInterval(checkSongEndRef.current); checkSongEndRef.current = null; } } }; const permissionsGranted = !!cameraPermission?.granted; return ( L'enregistrement de ta vidéo commencera lorsque tu lanceras ta musique, et s'arrêtera à la fin du morceau. {/* Overlay de compte à rebours : on affiche 5→1 pour éviter l'effet visuel à 1 */} {isPreparing && countdown >= 1 && !showProgress && ( {countdown} )} {/* Permission prompt */} {!permissionsGranted && ( { try { if (!cameraPermission?.granted) await requestCameraPermission(); } catch (_) {} }} /> )} {/* Start button */} {permissionsGranted && !isPreparing && !isRecording && ( )} {/* Progress circulaire */} {permissionsGranted && (isRecording || showProgress) && ( )} ); }; // Progress ring SVG const ProgressRing = ({ size = 50, strokeWidth = 12, progress = 0 }) => { const r = size / 2 - strokeWidth / 2; const c = 2 * Math.PI * r; const clamped = Math.max(0, Math.min(1, progress || 0)); const offset = c * (1 - clamped); return ( ); }; export default RecordPlayback;