Refactor la création de vidéos pour utiliser des promesses et améliorer la gestion des erreurs, avec une réponse immédiate au démarrage du rendu.

This commit is contained in:
2025-03-13 11:28:17 +01:00
parent 2e552be9db
commit c90ff42961
2 changed files with 102 additions and 79 deletions

View File

@@ -135,43 +135,41 @@ function serveFallbackVideo(res) {
router.post('/videos/render/:video_id', async (req, res) => { router.post('/videos/render/:video_id', async (req, res) => {
const videoId = req.params.video_id;
const query = 'SELECT measurement_ids, project_id, duration FROM public.videos WHERE id = $1';
db.query(query, [videoId], async (err, results) => {
if (err) {
return serverError.sendError('Error getting video:', res, err, 500);
}
if (results.rows.length === 0) {
return res.status(404).json({ error: 'Video not found' });
}
console.log('Video found:', results.rows[0]);
const duration = results.rows[0].duration;
console.log('Rendering video:', videoId);
const measurementIds = results.rows[0].measurement_ids;
const project_id = results.rows[0].project_id;
console.log('Measurement IDs:', measurementIds);
console.log('Project ID:', project_id);
try { try {
const pathList = await measureManager.getPathList(measurementIds, project_id); const videoId = req.params.video_id;
console.log('Path list:', pathList); const result = await db.query(
res.json({ message: 'Render process started' }); 'SELECT measurement_ids, project_id, duration FROM public.videos WHERE id = $1',
[videoId]
);
const videoFile = await videoManager.createVideoWithList(project_id, pathList, duration, videoId); if (result.rows.length === 0) {
console.log('Video file:', videoFile); return res.status(404).json({ error: 'Vidéo non trouvée' });
const update = await videoManager.updateVideoFile(videoId, videoFile);
console.log('Video rendering complete');
} catch (err) {
console.error('Error during video rendering:', err);
res.status(500).json({ error: 'Error during video rendering' });
} }
const { duration, measurement_ids, project_id } = result.rows[0];
const pathList = await measureManager.getPathList(measurement_ids, project_id);
// Démarrage du traitement en arrière-plan
videoManager.createVideoWithList(project_id, pathList, duration, videoId)
.then(videoFile => {
console.log('Rendu vidéo terminé:', videoFile);
return videoManager.updateVideoFile(videoId, videoFile);
})
.catch(error => {
console.error('Échec du rendu vidéo:', error);
}); });
// Réponse immédiate
res.json({
status: 'processing',
message: 'Le rendu a démarré',
check_url: `/videos/status/${videoId}`
});
} catch (error) {
console.error('Erreur initiale:', error);
res.status(500).json({ error: 'Échec de l\'initialisation du rendu' });
}
}); });
router.get('/videos/reset/:video_id', (req, res) => { router.get('/videos/reset/:video_id', (req, res) => {

View File

@@ -1,6 +1,9 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { execSync } = require('child_process'); const { execSync } = require('child_process');
const { exec } = require('child_process');
const util = require('util');
const execPromise = util.promisify(exec);
const serverError = require('../../utils/serverError'); const serverError = require('../../utils/serverError');
const db = require('../../db'); const db = require('../../db');
@@ -28,65 +31,87 @@ async function deleteVideoProject(videoId) {
} }
async function createVideoWithList(projectId, pathList, duration, videoId) { async function createVideoWithList(projectId, pathList, duration, videoId) {
//pathList étant la liste des chemins déjà triés
const tempFile = path.join('temp.txt'); const tempFile = path.join('temp.txt');
let ffmpegSuccess = false;
try { try {
// Trouver tous les fichiers image pour le projet donné
const workdir = path.join(PROJECTS_DIR, 'storage', `${projectId}`); const workdir = path.join(PROJECTS_DIR, 'storage', `${projectId}`);
const dir = path.join(PROJECTS_DIR, 'storage', `${projectId}`, 'images'); const dir = path.join(PROJECTS_DIR, 'storage', `${projectId}`, 'images');
console.log('dir:', dir);
const images = pathList;
console.log('images:', images);
// Trier les images numériquement // Vérification de l'existence du répertoire
const sortedImages = images.sort((a, b) => { if (!fs.existsSync(workdir)) {
fs.mkdirSync(workdir, { recursive: true });
}
// Triage des images
const sortedImages = pathList.sort((a, b) => {
const numA = parseInt(path.basename(a).match(/\d+/)[0], 10); const numA = parseInt(path.basename(a).match(/\d+/)[0], 10);
const numB = parseInt(path.basename(b).match(/\d+/)[0], 10); const numB = parseInt(path.basename(b).match(/\d+/)[0], 10);
return numA - numB; return numA - numB;
}); });
// En déduire l'id de la première et dernière image utilisée // Création du fichier temporaire
const firstImageId = parseInt(path.basename(sortedImages[0]).match(/\d+/)[0], 10);
const lastImageId = parseInt(path.basename(sortedImages[sortedImages.length - 1]).match(/\d+/)[0], 10);
console.log('firstImageId:', firstImageId);
console.log('lastImageId:', lastImageId);
// Créer un fichier temporaire pour la liste des images
fs.writeFileSync(tempFile, sortedImages.map(image => `file '${image}'`).join('\n')); fs.writeFileSync(tempFile, sortedImages.map(image => `file '${image}'`).join('\n'));
// Calcul du frame rate
const frameRate = Math.ceil(sortedImages.length / parseInt(duration)); const frameRate = Math.ceil(sortedImages.length / parseInt(duration));
// le fichier final prend cette forme : {projectId}_{firstImageId}_{lastImageId}-{timestamp}.mp4 // Génération du nom de fichier
const timestamp = new Date().getTime(); const timestamp = Date.now();
const outputVideo = path.join(workdir, `${projectId}_${firstImageId}_${lastImageId}-${timestamp}.mp4`); const outputVideo = path.join(
workdir,
`${projectId}_${path.basename(sortedImages[0], path.extname(sortedImages[0]))}_${path.basename(sortedImages[sortedImages.length - 1], path.extname(sortedImages[sortedImages.length - 1]))}-${timestamp}.mp4`
);
// Commande ffmpeg pour créer la vidéo // Commande FFmpeg
const ffmpegCommand = `ffmpeg -r ${frameRate} -f concat -safe 0 -i ${tempFile} -vsync vfr -pix_fmt yuv420p ${outputVideo}`; const ffmpegCommand = [
console.log('Running ffmpeg command:', ffmpegCommand); 'ffmpeg',
execSync(ffmpegCommand).then(() => { '-y', // Overwrite output file
console.log('Video created successfully:', outputVideo); '-r', frameRate,
'-f', 'concat',
'-safe', '0',
'-i', tempFile,
'-vsync', 'vfr',
'-pix_fmt', 'yuv420p',
outputVideo
].join(' ');
// Mettre à jour le statut de la vidéo à "completed" console.log(`Exécution de la commande FFmpeg: ${ffmpegCommand}`);
const updateStatusQuery = 'UPDATE public.videos SET status = $2 WHERE id = $1 RETURNING *'; const { stderr } = await execPromise(ffmpegCommand);
const updateStatusValues = [videoId, 1]; // 1 pour le statut "completed"
const updateStatusRes = db.query(updateStatusQuery, updateStatusValues); // Vérification des erreurs FFmpeg
console.log('Video status updated to completed:', updateStatusRes.rows[0]); if (stderr.includes('Error') || stderr.includes('failed')) {
throw new Error(`Erreur FFmpeg: ${stderr}`);
} }
).catch((error) => {
console.error('Error creating video:', error);
serverError.sendError('Error creating video', err=error);
});
ffmpegSuccess = true;
// Mise à jour de la base de données
const updateStatusRes = await db.query(
'UPDATE public.videos SET status = $1, file_path = $2 WHERE id = $3 RETURNING *',
[1, outputVideo, videoId]
);
console.log('Vidéo et statut mis à jour:', updateStatusRes.rows[0]);
return outputVideo; return outputVideo;
} catch (error) { } catch (error) {
console.error('Error creating video:', error); console.error('Erreur lors de la création vidéo:', error);
serverError.sendError('Error creating video', err=error);
// Mise à jour du statut en erreur
if (ffmpegSuccess) {
await db.query(
'UPDATE public.videos SET status = $1 WHERE id = $2',
[3, videoId] // 3 = statut erreur
);
}
throw error;
} finally { } finally {
// Supprimer le fichier temporaire // Nettoyage du fichier temporaire
if (fs.existsSync(tempFile)) { if (fs.existsSync(tempFile)) {
fs.unlinkSync(tempFile); fs.unlinkSync(tempFile);
console.log('Temporary file deleted:', tempFile);
} }
} }
} }