Fix race condition gphoto2 : verrou camera sur preview et capture

This commit is contained in:
2026-04-09 01:49:48 +02:00
parent 076e6d0030
commit 4273caf1ee

View File

@@ -1,6 +1,7 @@
import io import io
import logging import logging
import subprocess import subprocess
import threading
import time import time
from datetime import datetime from datetime import datetime
@@ -66,6 +67,7 @@ class Camera:
self.webcam = None self.webcam = None
self.webcam_index = -1 self.webcam_index = -1
self.preview_dslr_ok = True # True si le dernier preview DSLR a reussi self.preview_dslr_ok = True # True si le dernier preview DSLR a reussi
self._lock = threading.Lock() # Verrou pour eviter acces gphoto2 concurrent
def connecter(self, source=None) -> bool: def connecter(self, source=None) -> bool:
"""Connecte la camera. source: 'gphoto2', 'webcam:0', 'webcam:2', etc.""" """Connecte la camera. source: 'gphoto2', 'webcam:0', 'webcam:2', etc."""
@@ -145,34 +147,33 @@ class Camera:
def _capture_gphoto2(self, chemin_dest: Path) -> Path | None: def _capture_gphoto2(self, chemin_dest: Path) -> Path | None:
from PIL import Image as PILImage from PIL import Image as PILImage
for attempt in range(3): with self._lock:
try: for attempt in range(3):
chemin_camera = self.camera.capture(gp.GP_CAPTURE_IMAGE) try:
fichier_camera = gp.CameraFile() chemin_camera = self.camera.capture(gp.GP_CAPTURE_IMAGE)
self.camera.file_get( fichier_camera = gp.CameraFile()
chemin_camera.folder, chemin_camera.name, gp.GP_FILE_TYPE_NORMAL, fichier_camera self.camera.file_get(
) chemin_camera.folder, chemin_camera.name, gp.GP_FILE_TYPE_NORMAL, fichier_camera
# Sauvegarder le fichier brut temporairement )
tmp_path = str(chemin_dest) + ".tmp" tmp_path = str(chemin_dest) + ".tmp"
fichier_camera.save(tmp_path) fichier_camera.save(tmp_path)
# Redimensionner (max 4000px de large, JPEG 92%) img = PILImage.open(tmp_path)
img = PILImage.open(tmp_path) if img.width > 4000:
if img.width > 4000: ratio = 4000 / img.width
ratio = 4000 / img.width img = img.resize((4000, int(img.height * ratio)), PILImage.LANCZOS)
img = img.resize((4000, int(img.height * ratio)), PILImage.LANCZOS) img.save(str(chemin_dest), "JPEG", quality=92)
img.save(str(chemin_dest), "JPEG", quality=92) Path(tmp_path).unlink(missing_ok=True)
Path(tmp_path).unlink(missing_ok=True)
log.info(f"Photo capturee (DSLR) : {chemin_dest} ({img.width}x{img.height})") log.info(f"Photo capturee (DSLR) : {chemin_dest} ({img.width}x{img.height})")
return chemin_dest return chemin_dest
except gp.GPhoto2Error as e: except gp.GPhoto2Error as e:
if "I/O in progress" in str(e) and attempt < 2: if "I/O in progress" in str(e) and attempt < 2:
log.warning(f"DSLR occupe, retry {attempt + 1}/3...") log.warning(f"DSLR occupe, retry {attempt + 1}/3...")
time.sleep(0.5) time.sleep(0.5)
continue continue
log.error(f"Erreur capture DSLR : {e}") log.error(f"Erreur capture DSLR : {e}")
return None return None
def _capture_webcam(self, chemin_dest: Path) -> Path | None: def _capture_webcam(self, chemin_dest: Path) -> Path | None:
if not self.webcam or not self.webcam.isOpened(): if not self.webcam or not self.webcam.isOpened():
@@ -203,47 +204,46 @@ class Camera:
"""Active le LiveView sur les Canon (nécessaire avant capture_preview).""" """Active le LiveView sur les Canon (nécessaire avant capture_preview)."""
if self.mode != "gphoto2" or not self.connectee: if self.mode != "gphoto2" or not self.connectee:
return return
try: with self._lock:
cfg = self.camera.get_config() try:
vf = cfg.get_child_by_name("viewfinder") cfg = self.camera.get_config()
vf.set_value(1) vf = cfg.get_child_by_name("viewfinder")
self.camera.set_config(cfg) vf.set_value(1)
log.info("Viewfinder activé") self.camera.set_config(cfg)
except Exception as e: log.info("Viewfinder activé")
log.warning(f"Viewfinder non supporté : {e}") except Exception as e:
log.warning(f"Viewfinder non supporté : {e}")
def desactiver_viewfinder(self): def desactiver_viewfinder(self):
"""Désactive le LiveView.""" """Désactive le LiveView."""
if self.mode != "gphoto2" or not self.connectee: if self.mode != "gphoto2" or not self.connectee:
return return
try: with self._lock:
cfg = self.camera.get_config() try:
vf = cfg.get_child_by_name("viewfinder") cfg = self.camera.get_config()
vf.set_value(0) vf = cfg.get_child_by_name("viewfinder")
self.camera.set_config(cfg) vf.set_value(0)
log.info("Viewfinder désactivé") self.camera.set_config(cfg)
except Exception as e: log.info("Viewfinder désactivé")
log.warning(f"Viewfinder non supporté : {e}") except Exception as e:
log.warning(f"Viewfinder non supporté : {e}")
def _preview_gphoto2(self) -> bytes | None: def _preview_gphoto2(self) -> bytes | None:
try: with self._lock:
fichier = self.camera.capture_preview() try:
donnees = bytes(fichier.get_data_and_size()) fichier = self.camera.capture_preview()
# Redimensionner pour alléger le WebSocket donnees = bytes(fichier.get_data_and_size())
img = cv2.imdecode( img = cv2.imdecode(np.frombuffer(donnees, dtype=np.uint8), cv2.IMREAD_COLOR)
np.frombuffer(donnees, dtype=np.uint8), if img is not None:
cv2.IMREAD_COLOR, h, w = img.shape[:2]
) if w > 960:
if img is not None: img = cv2.resize(img, (960, int(h * 960 / w)), interpolation=cv2.INTER_LINEAR)
h, w = img.shape[:2] _, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 75])
if w > 960: return buf.tobytes()
img = cv2.resize(img, (960, int(h * 960 / w)), interpolation=cv2.INTER_LINEAR) return donnees
_, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 75]) except gp.GPhoto2Error as e:
return buf.tobytes() log.error(f"Erreur preview DSLR : {e}")
return donnees return None
except gp.GPhoto2Error as e:
log.error(f"Erreur preview DSLR : {e}")
return None
def _preview_webcam(self) -> bytes | None: def _preview_webcam(self) -> bytes | None:
if not self.webcam or not self.webcam.isOpened(): if not self.webcam or not self.webcam.isOpened():