How to Multiplex Multiple Programs into MPEG-TS with FFmpeg

Multiplexing multiple programs into a single Multi-Program Transport Stream (MPTS) is a standard requirement for digital broadcasting, IPTV, and cable television distribution. This guide explains how to use FFmpeg to combine multiple video and audio inputs into a single MPEG-TS output stream, utilizing the -program option to define distinct virtual channels with their own program numbers and PIDs.

Understanding MPTS in FFmpeg

In a standard Single Program Transport Stream (SPTS), there is only one television program. An MPTS contains multiple programs, each mapped with a unique Service ID (program number) and its associated audio and video streams.

FFmpeg achieves this by using the -map option to order the input streams, and the -program option to group those mapped streams into distinct program blocks.

The Basic Command Structure

To multiplex two separate input files into a single MPTS containing two distinct programs, use the following FFmpeg command:

ffmpeg -i input1.mp4 -i input2.mp4 \
-map 0:v -map 0:a \
-map 1:v -map 1:a \
-c:v libx264 -c:a aac \
-program title="Program 1":program_num=101:st=0:st=1 \
-program title="Program 2":program_num=102:st=2:st=3 \
-f mpegts output.ts

Command Breakdown

Customizing PIDs (Packet Identifiers)

In professional broadcasting, you often need to define specific Packet Identifiers (PIDs) for video, audio, and Program Map Tables (PMT). You can assign custom PIDs using the -streamid option, which maps output stream indexes to specific PID numbers:

ffmpeg -i input1.mp4 -i input2.mp4 \
-map 0:v -map 0:a -map 1:v -map 1:a \
-c:v copy -c:a copy \
-streamid 0:1001 -streamid 1:1002 \
-streamid 2:2001 -streamid 3:2002 \
-program title="Channel 1":program_num=101:st=0:st=1 \
-program title="Channel 2":program_num=102:st=2:st=3 \
-f mpegts output.ts

In this command: * 0:1001 sets the video PID for Program 1 to 1001. * 1:1002 sets the audio PID for Program 1 to 1002. * 2:2001 sets the video PID for Program 2 to 2001. * 3:2002 sets the audio PID for Program 2 to 2002. * -c:v copy -c:a copy is used to stream-copy the codecs without re-encoding, saving CPU resources if the inputs are already in a compatible format.