diff --git a/routes/api.js b/routes/api.js index fb9d973..987080c 100644 --- a/routes/api.js +++ b/routes/api.js @@ -7,6 +7,7 @@ const fs = require('fs'); const ffmpeg = require('../ffmpeg'); const fileUtils = require('../utils/fileUtils'); const serverError = require('../utils/serverError'); +const video = require('../utils/video'); /** * @swagger @@ -50,29 +51,14 @@ router.get('/projects', async (req, res) => { */ router.get('/projects/:id/create-video', async (req, res) => { const projectId = req.params.id; - const imageDir = `/storage/${projectId}`; - const outputVideo = `/storage/${projectId}/videos/output_video.mp4`; - const frameRate = 24; - const tempFile = `/storage/${projectId}/temp_file.txt`; - try { - const images = fs.readdirSync(imageDir).filter(file => file.endsWith('.jpg')); - if (images.length === 0) { - return res.status(404).json({ error: 'No images found for this project' }); - } - - const tempFileContent = images.map(img => `file '${path.join(imageDir, img)}'`).join('\n'); - fs.writeFileSync(tempFile, tempFileContent); - - const ffmpegCommand = `ffmpeg -r ${frameRate} -f concat -safe 0 -i ${tempFile} -vsync vfr -pix_fmt yuv420p ${outputVideo}`; - require('child_process').execSync(ffmpegCommand); - - fs.unlinkSync(tempFile); - res.status(200).json({ message: 'Video created successfully', videoPath: outputVideo }); + const videoPath = await video.createVideo(projectId); + res.json(videoPath); } catch (error) { serverError.sendError('Error creating video:', res, error); } -}); +} +); /** * @swagger diff --git a/utils/video.js b/utils/video.js new file mode 100644 index 0000000..ee81361 --- /dev/null +++ b/utils/video.js @@ -0,0 +1,31 @@ +const fs = require('fs'); +const path = require('path'); +const { execSync } = require('child_process'); +const serverError = require('../utils/serverError'); + +async function createVideo(projectId) { + const imageDir = `/storage/${projectId}`; + const outputVideo = `/storage/${projectId}/videos/output_video.mp4`; + const frameRate = 24; + const tempFile = `/storage/${projectId}/temp_file.txt`; + + try { + const images = fs.readdirSync(imageDir).filter(file => file.endsWith('.jpg')); + if (images.length === 0) { + throw new Error('No images found for this project'); + } + + const tempFileContent = images.map(img => `file '${path.join(imageDir, img)}'`).join('\n'); + fs.writeFileSync(tempFile, tempFileContent); + + const ffmpegCommand = `ffmpeg -r ${frameRate} -f concat -safe 0 -i ${tempFile} -vsync vfr -pix_fmt yuv420p ${outputVideo}`; + execSync(ffmpegCommand); + + fs.unlinkSync(tempFile); + return { message: 'Video created successfully', videoPath: outputVideo }; + } catch (error) { + throw new Error(`Error creating video: ${error.message}`); + } +} + +module.exports = { createVideo }; \ No newline at end of file