Created
September 10, 2024 16:59
-
-
Save Dhravya/939771a4f8997af44df7a0fce29a0afa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { type NextApiRequest, type NextApiResponse } from 'next'; | |
import Ffmpeg from 'fluent-ffmpeg'; | |
export default function handler(req: NextApiRequest, res: NextApiResponse) { | |
if (req.method === 'GET') { | |
// Set response headers | |
res.setHeader('Content-Type', 'video/mp4'); | |
res.setHeader('Connection', 'keep-alive'); | |
res.setHeader('Accept-Ranges', 'bytes'); | |
try { | |
const ffmpegCommand = Ffmpeg('rtsp://192.168.42.1/live') | |
.addOptions([ | |
'-rtsp_transport', 'tcp', // Use TCP instead of UDP | |
'-c:v', 'libx264', // Video codec | |
'-movflags', 'frag_keyframe+empty_moov', // MP4 streaming settings | |
'-bufsize', '512k', // Increase buffer size | |
]) | |
.format('mp4') // Explicitly specify the format | |
.on('end', () => { | |
console.log('Stream end'); | |
clearTimeout(timeout); | |
}) | |
.on('error', (err, stdout, stderr) => { | |
console.error('Error:', err); | |
console.error('ffmpeg stdout:', stdout); | |
console.error('ffmpeg stderr:', stderr); | |
res.status(500).send('Internal Server Error'); | |
clearTimeout(timeout); | |
}); | |
// Pipe the output to the response | |
ffmpegCommand.pipe(res); | |
// Timeout for stale requests | |
const timeoutDuration = 30000; // 30 seconds | |
const timeout = setTimeout(() => { | |
console.log('Request timed out. Stopping ffmpeg command.'); | |
ffmpegCommand.kill('SIGKILL'); | |
}, timeoutDuration); | |
// Clear timeout and stop ffmpeg if client closes connection | |
req.on('close', () => { | |
console.log('Client closed connection. Stopping ffmpeg command.'); | |
clearTimeout(timeout); | |
ffmpegCommand.kill('SIGKILL'); | |
}); | |
} catch (error) { | |
console.error('Streaming Error:', error); | |
res.status(500).send('Internal Server Error'); | |
} | |
} else { | |
res.status(405).send('Method Not Allowed'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment