MPEG2 Presentation Time Stamps (PTS) calculation

Nabijon picture Nabijon · Nov 28, 2012 · Viewed 20.7k times · Source

I have an MPEG2 TS file and now I am interested in extracting PTS information from each picture frame. I know that PTS is described in 33 bits including 3 marker bits. But I don't know how this bitfield can be converted to more understandable form (seconds, milliseconds). Can anybody help me please

Answer

Alex I picture Alex I · Nov 30, 2012

The MPEG2 transport stream clocks (PCR, PTS, DTS) all have units of 1/90000 second. The PTS and DTS have three marker bits which you need to skip over. The pattern is always (from most to least significant bit) 3 bits, marker, 15 bits, marker, 15 bits, marker. The markers must be equal to 1. In C, removing the markers would work like this:

uint64_t v; // this is a 64bit integer, lowest 36 bits contain a timestamp with markers
uint64_t pts = 0;
pts |= (v >> 3) & (0x0007 << 30); // top 3 bits, shifted left by 3, other bits zeroed out
pts |= (v >> 2) & (0x7fff << 15); // middle 15 bits
pts |= (v >> 1) & (0x7fff <<  0); // bottom 15 bits
// pts now has correct timestamp without markers in lowest 33 bits 

They also have an extension field of 9bits, forming a 42bit integer in which the extension is the least significant bits. The units for the base+extension are 1/27000000 second. Many implementations leave the extension as all zeros.