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

674 Views Asked by At

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?

3

There are 3 best solutions below

2
Maurice Meyer On BEST ANSWER

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)
1
SSA On

Use bitstring module from python.


enter image description here

0
AudioBubble On

I do this a lot.

SYNC_BYTE = 0x47

    def find_start(tsdata):
        while tsdata:
            one = tsdata.read(1)
            if not one:
                return False
            if one[0] == SYNC_BYTE:
                return True

if you slice bytes or convert them to a list, you get the integer value of each byte.

>>>> g = b'G'
>>>> list(g)
[71]

>>>> g = b'G'

>>>> g[0]
71
>>>> g == 0x47
False
>>>> g[0] == 0x47
True
>>>> g[0]
71
>>>> g
b'G'
>>>> 

>>>> 

>>>> stuff = b'Fonzie is the coolest'
>>>> list(stuff)
[70, 111, 110, 122, 105, 101, 32, 105, 115, 32, 116, 104, 101, 32, 99, 111, 111, 108, 101, 115, 116]