#!/usr/bin/env python3

# ========================================================
#    This code is for study only.
#    This code is not optimized.
#    This code is over simplified.
#    This code doesn't respect rules of good coding.
#    This code has duplicate codes: 
#        to understanding without complexity.
#    Some values -useless on code- will not be converted.
# ========================================================

import sys
import io

# Conversion en int
def to_int(length : bytes = b'') -> int:
    return int.from_bytes(length, byteorder='big')

if len(sys.argv) < 2:
    print("Usage: %s <mxf>" % sys.argv[0])
    sys.exit(1)

mxf_file = sys.argv[1]

with open(mxf_file, "rb") as file:

    while True:

        # Key : Universal Label
        key = file.read(16)

        # End of file
        if not key: 
            break

        # Length (BER format)
        length = to_int(file.read(4)[1:])  # BER format - read last 3 bytes

        # Value
        value = file.read(length)

        # Filter by KLV : RGBA Essence Descriptor
        if key.hex() != "060e2b34025301010d01010101012900":
           continue

        # Show each KLV
        print("{key} - {length:>6d} bytes - {value}...".format(
            key    = key.hex(),
            length = length,
            value  = value[0:16].hex()
        ))

        # read each item
        data = io.BytesIO(value)

        # "item" is a baby KLV:
        #  localtag (key)  :  2 bytes
        #  item length     :  2 bytes (no BER format)
        #  item value      :  variable bytes

        while True:

            # get local tag (2 bytes)
            localtag = data.read(2)

            if not localtag:
                break

            # get item length (2 bytes, directly int, NOT Ber format)
            item_length = to_int(data.read(2))

            # get item value
            item_value = data.read(item_length)

            # Show each item
            print("{localtag} : {item_length:>2d} : {item_value}".format(
                localtag    = localtag.hex(),
                item_length = item_length,
                item_value  = item_value.hex()
            ))
