pythonmpegtransport-stream

Using Python to check if first byte of MPEG transport stream is a sync byte


I am trying to use Python to look into a transport stream, and read the first byte. Once this is done, I will check if this byte is 0x47 to determine if the transport stream is a valid one.

Here's the code I have tried:

with open("my_ts_file.ts", "rb") as file_object:
    byte = file_object.read(1)
    if byte == 0x47:
        print("Found first sync byte")
        print(byte)
    else:
        print("Not a valid Transport Stream")
        print(byte)

So if the first byte is 0x47 or not, it should display that.

The issue I am having here is that the output of this code shows:

Not a valid Transport Stream
b'G'

And as @szatmary pointed out here: Using Python to extract the first 188-byte packet from MPEG Transport Stream but do not see the sync byte the letter G is actually the ASCII representation of 0x47 (Hex).

How can I effectively do a comparison between essentially the same value but are represented two different ways?


Solution

  • You need to convert 0x47 into string representing using chr():

    with open("my_ts_file.ts", "rb") as file_object:
        byte = file_object.read(1)
        if byte == chr(0x47):
            print("Found first sync byte")
            print(byte)
        else:
            print("Not a valid Transport Stream")
            print(byte)