DEV Community

stupwark995
stupwark995

Posted on Originally published at m3u8play.net

Converting M3U8 (HLS) to MP4 with FFmpeg: Lossless Copy, Re-encode & Custom Headers

Renaming a .m3u8 file to .mp4 never works because .m3u8 is just a text index pointing to dozens or hundreds of .ts / .m4s segments. The cleanest way to merge an authorized HLS stream into a playable MP4 is locally with FFmpeg.

1. Fastest method: lossless stream copy

If the stream already uses H.264 + AAC, copy it without re-encoding (finishes in seconds):

ffmpeg -i "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8" \
  -c copy -bsf:a aac_adtstoasc output.mp4
Enter fullscreen mode Exit fullscreen mode

Why -bsf:a aac_adtstoasc? It fixes the common malformed AAC bitstream error when remuxing MPEG-TS segments into an MP4 container.

2. Safer fallback: re-encode to universal H.264 + AAC

If the copied file has no sound in QuickTime or stutters on mobile:

ffmpeg -i "https://example.com/hls/master.m3u8" \
  -c:v libx264 -preset medium -crf 20 \
  -c:a aac -b:a 128k -movflags +faststart output.mp4
Enter fullscreen mode Exit fullscreen mode

3. Fixing 403 Forbidden with Referer / User-Agent / Cookies

Most FFmpeg M3U8 failures are missing request headers rather than codec errors. Pass your authorized context before -i:

ffmpeg -user_agent "Mozilla/5.0" \
  -headers "Referer: https://your-site.example.com/\r\nCookie: session=your_token\r\n" \
  -i "https://your-cdn.example.com/hls/index.m3u8" \
  -c copy -bsf:a aac_adtstoasc output.mp4
Enter fullscreen mode Exit fullscreen mode

Skip typing flags manually

I put together a free M3U8 to MP4 FFmpeg Command Generator that builds copy/re-encode/header commands automatically — and you can sanity-check your manifest first in the online M3U8 player.

Top comments (0)