const express = require('express'); const cors = require('cors'); const dotenv = require('dotenv'); const fs = require('fs'); const path = require('path'); const ffmpeg = require('fluent-ffmpeg'); const { S3Client, ListObjectsV2Command, GetObjectCommand } = require('@aws-sdk/client-s3'); dotenv.config(); const app = express(); const PORT = process.env.PORT || 3000; const HOST = process.env.HOST || process.env.LISTEN_ADDRESS || '0.0.0.0'; app.use(cors()); app.use(express.json()); app.use(express.static('public')); // Configure AWS S3 Client const s3Client = new S3Client({ region: process.env.AWS_REGION || 'us-east-1', endpoint: process.env.S3_ENDPOINT, forcePathStyle: process.env.S3_FORCE_PATH_STYLE === 'true', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY } }); const BUCKET_NAME = process.env.S3_BUCKET_NAME; // Endpoint to list videos in the bucket app.get('/api/videos', async (req, res) => { try { if (!BUCKET_NAME) { return res.status(500).json({ error: 'S3_BUCKET_NAME not configured' }); } const command = new ListObjectsV2Command({ Bucket: BUCKET_NAME, }); const response = await s3Client.send(command); // Filter for a broader set of common video formats const videoExtensions = [ '.3gp', '.3g2', '.asf', '.avi', '.divx', '.flv', '.m2ts', '.m2v', '.m4v', '.mkv', '.mov', '.mp4', '.mpeg', '.mpg', '.mts', '.mxf', '.ogm', '.ogv', '.qt', '.rm', '.rmvb', '.ts', '.vob', '.vro', '.webm', '.wmv' ]; const videos = (response.Contents || []) .map(item => item.Key) .filter(key => { if (!key) return false; const lowerKey = key.toLowerCase(); return videoExtensions.some(ext => lowerKey.endsWith(ext)); }); res.json({ videos }); } catch (error) { console.error('Error fetching videos:', error); res.status(500).json({ error: 'Failed to fetch videos from S3', detail: error.message }); } }); // Endpoint to transcode S3 video streaming to HLS app.post('/api/transcode', async (req, res) => { const { key, codec, encoder } = req.body; if (!key) { return res.status(400).json({ error: 'Video key is required' }); } const safeCodec = codec === 'h265' ? 'h265' : 'h264'; const safeEncoder = ['nvidia', 'intel'].includes(encoder) ? encoder : 'software'; const codecMap = { software: { h264: 'libx264', h265: 'libx265' }, nvidia: { h264: 'h264_nvenc', h265: 'hevc_nvenc' }, intel: { h264: 'h264_qsv', h265: 'hevc_qsv' } }; const videoCodec = codecMap[safeEncoder][safeCodec]; try { const safeKeySegments = key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')); const outputDir = path.join(__dirname, 'public', 'hls', ...safeKeySegments); const m3u8Path = path.join(outputDir, 'index.m3u8'); const hlsUrl = `/hls/${safeKeySegments.join('/')}/index.m3u8`; // If it already exists, just return the URL if (fs.existsSync(m3u8Path)) { return res.json({ message: 'Already transcoded', hlsUrl }); } // Create output directory if it doesn't exist fs.mkdirSync(outputDir, { recursive: true }); // Get S3 stream const command = new GetObjectCommand({ Bucket: BUCKET_NAME, Key: key }); const response = await s3Client.send(command); const s3Stream = response.Body; // Triggers fluent-ffmpeg to transcode to HLS console.log(`Starting transcoding for ${key} with codec ${videoCodec}`); ffmpeg(s3Stream) .videoCodec(videoCodec) .audioCodec('aac') .outputOptions([ '-preset fast', '-crf 23', '-hls_time 6', '-hls_list_size 0', '-hls_allow_cache 1', '-hls_flags independent_segments', '-f hls' ]) .output(m3u8Path) .on('end', () => { console.log(`Finished transcoding ${key} to HLS`); }) .on('error', (err) => { console.error(`Error transcoding ${key}:`, err); }) .run(); // Return immediately so the client can start polling or waiting res.json({ message: 'Transcoding started', hlsUrl }); } catch (error) { console.error('Error in transcode:', error); res.status(500).json({ error: 'Failed to initiate transcoding', detail: error.message }); } }); // Status check for HLS playlist availability app.get('/api/status', (req, res) => { const { key } = req.query; if (!key) return res.status(400).json({ error: 'Key is required' }); const safeKeySegments = key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')); const m3u8Path = path.join(__dirname, 'public', 'hls', ...safeKeySegments, 'index.m3u8'); // Check if the playlist file exists if (fs.existsSync(m3u8Path)) { res.json({ ready: true, hlsUrl: `/hls/${safeKeySegments.join('/')}/index.m3u8` }); } else { res.json({ ready: false }); } }); app.listen(PORT, HOST, () => { console.log(`Server running on http://${HOST}:${PORT}`); });