HTTP Live Streaming (HLS) is the most widely used protocol for delivering video content. This guide covers implementing HLS for adaptive streaming.
HLS Overview
HLS breaks video into small segments and delivers them via HTTP. Clients automatically adjust quality based on network conditions.
Video Encoding
FFmpeg Command
bash
ffmpeg -i input.mp4 \
-c:v h264 -profile:v baseline -level 3.0 \
-c:a aac -b:a 128k \
-f hls -hls_time 10 -hls_list_size 0 \
output.m3u8Backend Implementation
Express Server for HLS
typescript
import express from 'express';
import fs from 'fs';
const app = express();
app.get('/video/:filename', (req, res) => {
const file = `./videos/${req.params.filename}`;
const stat = fs.statSync(file);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = end - start + 1;
const stream = fs.createReadStream(file, { start, end });
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
});
stream.pipe(res);
}
});Frontend Player
Video.js Integration
typescript
import videojs from 'video.js';
export const VideoPlayer = ({ src }) => {
const videoRef = useRef<HTMLVideoElement>(null);
useEffect(() => {
const player = videojs(videoRef.current, {
controls: true,
sources: [{ src, type: 'application/x-mpegURL' }],
});
return () => player.dispose();
}, []);
return <div data-vjs-player><video ref={videoRef} className="video-js" /></div>;
};Conclusion
HLS provides reliable, adaptive video streaming. Use FFmpeg for encoding and Video.js for playback. Implement proper caching for optimal performance.