コード例 #1
0
ファイル: Gyro.py プロジェクト: Umair-Anwar/ADXRS810
 def Pid(self):
     self.spi1.spi_xfer(self.h,self.Read_Pid)
     (count,st)=self.spi1.spi_xfer(self.h,self.Read_Pid)
     f2 = BitStream(bytes = st)
     f2.pos= 11
     a=f2.read(16).bin
     return a
コード例 #2
0
ファイル: Gyro.py プロジェクト: Umair-Anwar/ADXRS810
 def Sensor_Data(self):
     self.spi1.spi_xfer(self.h,self.Sensor_data_CHK_de_asrRead_Rate)
     (count,st)=self.spi1.spi_xfer(self.h,self.Sensor_data_CHK_de_asrRead_Rate)
     f2 = BitStream(bytes = st )
     f2.pos= 6
     a=f2.read(16).int
     return a
コード例 #3
0
ファイル: Gyro.py プロジェクト: Umair-Anwar/ADXRS810
 def Rate(self):
     self.spi1.spi_xfer(self.h,self.Read_Rate)
     (count,st)=self.spi1.spi_xfer(self.h,self.Read_Rate)
     f2 = BitStream(bytes = st )
     f2.pos= 11
     a=f2.read(16).int
     a=a/80
     return a
コード例 #4
0
ファイル: static.py プロジェクト: marknach/swarfarm
def decrypt_images(**kwargs):
    path = kwargs.pop('path', 'herders/static/herders/images')
    for im_path in iglob(f'{path}/**/*.png', recursive=True):
        encrypted = BitStream(filename=im_path)

        # Check if it is 'encrypted'. 8th byte is 0x0B instead of the correct signature 0x0A
        encrypted.pos = 0x07 * 8
        signature = encrypted.peek('uint:8')
        if signature == 0x0B:
            print(f'Decrypting {im_path}')
            # Correct the PNG signature
            encrypted.overwrite('0x0A', encrypted.pos)

            # Replace bits with magic decrypted values
            try:
                while True:
                    pos = encrypted.pos
                    val = encrypted.peek('uint:8')
                    encrypted.overwrite(
                        Bits(uint=com2us_decrypt_values[val], length=8), pos)
            except ReadError:
                # EOF
                pass

            # Write it back to the file
            with open(im_path, 'wb') as f:
                encrypted.tofile(f)

            continue

        # Check for weird jpeg format with extra header junk. Convert to png.
        encrypted.pos = 0
        if encrypted.peek('bytes:5') == b'Joker':
            print(f'Converting Joker container JPEG to PNG {im_path}')
            with open(im_path, 'rb') as f:
                img = JokerContainerFile(f)

            # Open it as a jpg and resave to disk
            try:
                new_imfile = Image.open(io.BytesIO(img.data.tobytes()))
                new_imfile.save(im_path)
            except IOError:
                print(f'Unable to open {im_path}')
コード例 #5
0
ファイル: com2us_data_parser.py プロジェクト: Veniad/swarfarm
def decrypt_com2us_png():
    com2us_decrypt_values = [
        0x2f, 0x7c, 0x47, 0x55, 0x32, 0x77, 0x9f, 0xfb, 0x5b, 0x86, 0xfe, 0xb6,
        0x3e, 0x06, 0xf4, 0xc4, 0x2e, 0x08, 0x49, 0x11, 0x0e, 0xce, 0x84, 0xd3,
        0x7b, 0x18, 0xa6, 0x5c, 0x71, 0x56, 0xe2, 0x3b, 0xfd, 0xb3, 0x2b, 0x97,
        0x9d, 0xfc, 0xca, 0xba, 0x8e, 0x7e, 0x6f, 0x0f, 0xe8, 0xbb, 0xc7, 0xc2,
        0xd9, 0xa4, 0xd2, 0xe0, 0xa5, 0x95, 0xee, 0xab, 0xf3, 0xe4, 0xcb, 0x63,
        0x25, 0x70, 0x4e, 0x8d, 0x21, 0x37, 0x9a, 0xb0, 0xbc, 0xc6, 0x48, 0x3f,
        0x23, 0x80, 0x20, 0x01, 0xd7, 0xf9, 0x5e, 0xec, 0x16, 0xd6, 0xd4, 0x1f,
        0x51, 0x42, 0x6c, 0x10, 0x14, 0xb7, 0xcc, 0x82, 0x7f, 0x13, 0x02, 0x00,
        0x72, 0xed, 0x90, 0x57, 0xc1, 0x2c, 0x5d, 0x28, 0x81, 0x1d, 0x38, 0x1a,
        0xac, 0xad, 0x35, 0x78, 0xdc, 0x68, 0xb9, 0x8b, 0x6a, 0xe1, 0xc3, 0xe3,
        0xdb, 0x6d, 0x04, 0x27, 0x9c, 0x64, 0x5a, 0x8f, 0x83, 0x0c, 0xd8, 0xa8,
        0x1c, 0x89, 0xd5, 0x43, 0x74, 0x73, 0x4d, 0xae, 0xea, 0x31, 0x6e, 0x1e,
        0x91, 0x1b, 0x59, 0xc9, 0xbd, 0xf7, 0x07, 0xe7, 0x8a, 0x05, 0x8c, 0x4c,
        0xbe, 0xc5, 0xdf, 0xe5, 0xf5, 0x2d, 0x4b, 0x76, 0x66, 0xf2, 0x50, 0xd0,
        0xb4, 0x85, 0xef, 0xb5, 0x3c, 0x7d, 0x3d, 0xe6, 0x9b, 0x03, 0x0d, 0x61,
        0x33, 0xf1, 0x92, 0x53, 0xff, 0x96, 0x09, 0x67, 0x69, 0x44, 0xa3, 0x4a,
        0xaf, 0x41, 0xda, 0x54, 0x46, 0xd1, 0xfa, 0xcd, 0x24, 0xaa, 0x88, 0xa7,
        0x19, 0xde, 0x40, 0xeb, 0x94, 0x5f, 0x45, 0x65, 0xf0, 0xb8, 0x34, 0xdd,
        0x0b, 0xb1, 0x29, 0xe9, 0x2a, 0x75, 0x87, 0x39, 0xcf, 0x79, 0x93, 0xa1,
        0xb2, 0x30, 0x15, 0x7a, 0x52, 0x12, 0x62, 0x36, 0xbf, 0x22, 0x4f, 0xc0,
        0xa2, 0x17, 0xc8, 0x99, 0x3a, 0x60, 0xa9, 0xa0, 0x58, 0xf6, 0x0a, 0x9e,
        0xf8, 0x6b, 0x26, 0x98
    ]

    for im_path in iglob('herders/static/herders/images/**/*.png',
                         recursive=True):
        encrypted = BitStream(filename=im_path)

        # Check if it is encrypted. 8th byte is 0x0B instead of the correct signature 0x0A
        encrypted.pos = 0x07 * 8
        signature = encrypted.peek('uint:8')
        if signature == 0x0B:
            print('Decrypting {}'.format(im_path))
            # Correct the PNG signature
            encrypted.overwrite('0x0A', encrypted.pos)

            # Replace bits with magic decrypted values
            try:
                while True:
                    pos = encrypted.pos
                    val = encrypted.peek('uint:8')
                    encrypted.overwrite(
                        Bits(uint=com2us_decrypt_values[val], length=8), pos)
            except ReadError:
                # EOF
                pass

            # Write it back to the file
            with open(im_path, 'wb') as f:
                encrypted.tofile(f)
コード例 #6
0
def find_mapping(infile, outfile):


    stream = BitStream()

    with open(infile) as f:
        byte = f.read(1)
        while byte:
            if byte == '\x01':
                stream.append('0b1')
            else:
                stream.append('0b0')
            byte = f.read(1)

    iteration = 0
    for mapping in bitmappings:

        stream.pos = 0
        tmpstream = BitStream()

        for pie in stream.cut(2):

            index = pie.read('uint:2')

            tmpstream.append( BitArray(uint=mapping[index], length=2) )


    # look for the start of the flag in the stream of bits
        pos = tmpstream.find(ZULU)

        if len(pos) > 0:

            # print("Found the bytes we are looking for on iteration {}".format(iteration))
            # print("pos = {}".format(pos))

            tmpstream <<= pos[0] % 8
            data = tmpstream.tobytes()

            # print(data)
            with open(outfile, 'wb') as fh:
                fh.write(data)

            break
        else:
            # print("Did not find the header")
            iteration += 1
コード例 #7
0
def change_reg(reg_no, data, pos_start):
    bit_array = BitStream(bin(read_reg(reg_no)))
    bit_array.pos = pos_start
    bit_array.overwrite('0b0101')
    return bit_array
コード例 #8
0
def main(argv):
    if len(argv) < 4:
        print("Usage: " + argv[0] + " <header dump> <type (hex|bin|raw)> <definition>")
        return
    
    filename = argv[1]
    typ = argv[2]
    definition = []
    for argc in range(3, len(argv)):
        definition.append(argv[argc])

    print("File: " + filename)
    print("Definition: " + ", ".join(definition))
    print("Type: " + typ)
    
    bits = []
    for d in definition:
        bits = parseDefinition(d, bits)
    
    content = None
    field = None
    with open(filename) as f:
            if typ == "hex":
                content = f.read().strip()
                field = BitStream("0x" + content)
                
            if typ == "bin":
                content = f.read().strip()
                field = BitStream("0b" + content)
        
            if typ == "raw":
                field = BitStream(f)
        
    parsed = {}
    pos = 0
    last_header = None
    for bit in bits:
        field.pos = pos
        
        bitlen = 0
        lenexpr = bit.getBits()
        condexpr = bit.getCondition()
        for p in sorted(parsed.keys(), key=len, reverse=True):
            lenexpr = lenexpr.replace(p, str(parsed[p]))
            condexpr = condexpr.replace(p, str(parsed[p]))
        try:
            bitlen = eval(lenexpr)
        except:
            print("Error: " + str(bit.getBits()) + " is not a valid size!")
            return
        try:
            cond = eval(condexpr)
        except:
            print("Error: " + str(bit.getCondition()) + " is not a valid condition! (Parsed to " + condexpr + ")")
            return
        
        if cond:
            try:
                val = field.read(bitlen)
            except:
                print("Could not read field " + str(bit.getName()) + " with " + str(bitlen) + " bits!")
                continue
            
            parsed[bit.getName()] = val.uint
            pos += bitlen
            if last_header is not bit.getPrefix():
                last_header = bit.getPrefix()
                print("")
            
            out = bit.getName() + ": "
            for t, endian in bit.getTypes():
                if t == "hex":
                    out += "0x" + val.hex + " "
                if t == "int":
                    out += str(endianness(val.uint, endian, int(bitlen))) + " "
                if t == "bin":
                    out += "0b" + val.bin + " "
                if t == "str":
                    s = ""
                    for si in range(0, len(str(val)[2:]), 2):
                        out += str(chr(int(str(val)[si + 2:si + 4], 16)))
            print(out)
コード例 #9
0
ファイル: hdec.py プロジェクト: H0K5/UniversalHeaderDecoder
def main(argv):
    if len(argv) < 4:
        print("Usage: " + argv[0] +
              " <header dump> <type (hex|bin|raw)> <definition>")
        return

    filename = argv[1]
    typ = argv[2]
    definition = []
    for argc in range(3, len(argv)):
        definition.append(argv[argc])

    print("File: " + filename)
    print("Definition: " + ", ".join(definition))
    print("Type: " + typ)

    bits = []
    for d in definition:
        bits = parseDefinition(d, bits)

    content = None
    field = None
    with open(filename) as f:
        if typ == "hex":
            content = f.read().strip()
            field = BitStream("0x" + content)

        if typ == "bin":
            content = f.read().strip()
            field = BitStream("0b" + content)

        if typ == "raw":
            field = BitStream(f)

    parsed = {}
    pos = 0
    last_header = None
    for bit in bits:
        field.pos = pos

        bitlen = 0
        lenexpr = bit.getBits()
        condexpr = bit.getCondition()
        for p in sorted(parsed.keys(), key=len, reverse=True):
            lenexpr = lenexpr.replace(p, str(parsed[p]))
            condexpr = condexpr.replace(p, str(parsed[p]))
        try:
            bitlen = eval(lenexpr)
        except:
            print("Error: " + str(bit.getBits()) + " is not a valid size!")
            return
        try:
            cond = eval(condexpr)
        except:
            print("Error: " + str(bit.getCondition()) +
                  " is not a valid condition! (Parsed to " + condexpr + ")")
            return

        if cond:
            try:
                val = field.read(bitlen)
            except:
                print("Could not read field " + str(bit.getName()) + " with " +
                      str(bitlen) + " bits!")
                continue

            parsed[bit.getName()] = val.uint
            pos += bitlen
            if last_header is not bit.getPrefix():
                last_header = bit.getPrefix()
                print("")

            out = bit.getName() + ": "
            for t, endian in bit.getTypes():
                if t == "hex":
                    out += "0x" + val.hex + " "
                if t == "int":
                    out += str(endianness(val.uint, endian, int(bitlen))) + " "
                if t == "bin":
                    out += "0b" + val.bin + " "
                if t == "str":
                    s = ""
                    for si in range(0, len(str(val)[2:]), 2):
                        out += str(chr(int(str(val)[si + 2:si + 4], 16)))
            print(out)
コード例 #10
0
ファイル: nvhsp.py プロジェクト: pat357/nv_hevc_hdr_patcher
def main():
    """
    """

    if args.infile == args.outfile :
        print ('Error! Source and Destination can not be the same file!')
        sys.exit()

    if not os.path.exists(args.infile) :
        print ('Error! Given input file name not found! Please check path given in CMD or set in script code!')
        sys.exit()
    if md_arg_str :
        md = re.findall('\d+',md_arg_str)
        if len(md) != 10 :
            print ('Specified wrong "-masterdisplay" parameter! Please check!\n Example: G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1) or do not specify')
            sys.exit()

    if maxcll :
        mcll = re.findall('\d+',maxcll)
    sei_ok = 0 
    
    F = open (args.infile,'r+b')
    o = open (args.outfile,'wb')

    print ('Parsing the infile:')
    print ('')
    print ('==========================')
    print ('')
    print ('Prepending SEI data')
    s = BitStream(F.read(chunk))
    
    nals = list(s.findall('0x000001', bytealigned=True))
    sps_nals = list(s.findall('0x00000142', bytealigned=True))
    sei_pref_nals = list (s.findall('0x0000014e', bytealigned=True))
    size = [y - x for x,y in zip(nals,nals[1:])]
    sps_pos = list(set(nals).intersection(sps_nals))
    sei_pref_nals_pos = list(set(nals).intersection(sei_pref_nals))
    sps_size = size[nals.index(sps_nals[0])]
    if sei_pref_nals :
        sei_pref_nal_size = ( size[nals.index(sei_pref_nals[0])])
### MAXCLL & MAXFALL ###

    if args.maxcll or md_arg_str :
        sei_forbidden_zero_bit  = 0
        sei_nal_unit_type = 39
        sei_nuh_layer_id = 0
        sei_nuh_temporal_id_plus1 = 1
        new_sei_string = pack ('uint:1,2*uint:6,uint:3',sei_forbidden_zero_bit,sei_nal_unit_type,sei_nuh_layer_id,sei_nuh_temporal_id_plus1)
        print ('Starting new SEI NALu...')

        if maxcll :
            sei_last_payload_type_byte = 144
            sei_last_payload_size_byte = 4
            sei_max_content_light_level = int(mcll[0])
            sei_max_pic_average_light_level = int(mcll[1])
            new_sei_string += pack ('2*uint:8,2*uint:16',sei_last_payload_type_byte,sei_last_payload_size_byte,sei_max_content_light_level,sei_max_pic_average_light_level)
            print ('SEI message with MaxCLL=',sei_max_content_light_level,' and MaxFall=',sei_max_pic_average_light_level,' created in SEI NAL')

        if md_arg_str :
            md_sei_last_payload_type_byte = 137
            md_sei_last_payload_size_byte = 24
            #MD string ref
            #G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1)
            new_sei_string += pack ('2*uint:8',md_sei_last_payload_type_byte,md_sei_last_payload_size_byte)
            for i in range (len(md)-2) :
                new_sei_string += pack ('uint:16',int(md[i]))

            new_sei_string += pack ('uint:32',int(md[8]))
            new_sei_string += pack ('uint:32',int(md[9]))

            new_sei_string.replace ('0x0000','0x000003',bytealigned=True)
            print ('SEI message Mastering Display Data',md_arg_str,'created in SEI NAL')     

        new_sei_string = '0x00000001' + new_sei_string + '0x00'
        sei_ok = True



### ------------------ ###   
    
    print ('Looking for SPS.........', sps_pos)
    print ('SPS_Nals_addresses', sps_pos)
    print ('SPS NAL Size', sps_size)
    print ('Starting reading SPS NAL contents')

    
    s.pos = sps_pos[0]
    t = s.peek(sps_size)

    t.pos = t.pos + 24

    forbidden_zero_bit  = t.read('uint:1')
    nal_unit_type = t.read('uint:6')
    nuh_layer_id = t.read('uint:6')
    nuh_temporal_id_plus1 = t.read('uint:3')
    nal_t = t[:]

# 7.3.1.1
    # Convert NAL data (Annex B format) to RBSP data

    t.tobytes()
    t.replace ('0x000003','0x0000')
    
    
# SPS parse block


    sps_video_parameter_set_id = t.read('uint:4')
    sps_max_sub_layers_minus1 = t.read('uint:3')
    sps_temporal_id_nesting_flag = t.read('uint:1')
    ptl = profile_tier_level(t, sps_max_sub_layers_minus1)
    sps_seq_parameter_set_id = t.read('ue')
    chroma_format_idc = t.read('ue')
    if chroma_format_idc == 3:
        separate_colour_plane_flag = t.read('uint:1')
    pic_width_in_luma_samples = t.read ('ue')
    pic_height_in_luma_samples = t.read ('ue')
    conformance_window_flag = t.read ('uint:1')
    if (conformance_window_flag) :
        conf_win_left_offset = t.read('ue')
        conf_win_right_offset = t.read('ue')
        conf_win_top_offset = t.read('ue')
        conf_win_bottom_offset = t.read('ue')
    bit_depth_luma_minus8 = t.read ('ue')
    bit_depth_chroma_minus8 = t.read ('ue')
    log2_max_pic_order_cnt_lsb_minus4 = t.read('ue')
    sps_sub_layer_ordering_info_present_flag = t.read('uint:1')
#   for (i = (sps_sub_layer_ordering_info_present_flag ? 0 : sps.max_sub_layers_minus1); i <= sps.max_sub_layers_minus1; i++)
    if sps_sub_layer_ordering_info_present_flag :
            sps_max_dec_pic_buffering_minus1 = t.read('ue')
            sps_max_num_reorder_pics = t.read('ue')
            sps_max_latency_increase_plus1 = t.read('ue')

    log2_min_luma_coding_block_size_minus3 = t.read ('ue')
    log2_diff_max_min_luma_coding_block_size = t.read ('ue')
    log2_min_luma_transform_block_size_minus2 = t.read ('ue')
    log2_diff_max_min_luma_transform_block_size = t.read ('ue')
    max_transform_hierarchy_depth_inter = t.read ('ue')
    max_transform_hierarchy_depth_intra = t.read ('ue')
    scaling_list_enabled_flag = t.read ('uint:1')
    """
    if( scaling_list_enabled_flag ) {
    sps_scaling_list_data_present_flag u(1)
    if( sps_scaling_list_data_present_flag )
    scaling_list_data( )
    }
    """
    amp_enabled_flag = t.read ('uint:1')
    sample_adaptive_offset_enabled_flag = t.read ('uint:1')
    pcm_enabled_flag = t.read ('uint:1')
    if pcm_enabled_flag :
        pcm_sample_bit_depth_luma_minus1 = t.read ('uint:4')
        pcm_sample_bit_depth_chroma_minus1 = t.read ('uint:4')
        log2_min_pcm_luma_coding_block_size_minus3  = t.read ('ue')
        log2_diff_max_min_pcm_luma_coding_block_size = t.read ('ue')
        pcm_loop_filter_disabled_flag = t.read ('uint:1')
    num_short_term_ref_pic_sets = t.read ('ue')
    if num_short_term_ref_pic_sets :
        for i in range (num_short_term_ref_pic_sets):
            if i != 0 :
                inter_ref_pic_set_prediction_flag = t.read ('uint:1')
        
            if not 'inter_ref_pic_set_prediction_flag' in globals() :
                """    
            
                if i == num_short_term_ref_pic_sets :
                    delta_idx_minus1 = t.read ('ue')
                if not 'delta_idx_minus1' in globals():
                    delta_idx_minus1 = 0
                delta_rps_sign = t.read ('uint:1')
                abs_delta_rps_minus1 = t.read ('ue')
                for j in range (NumDeltaPoc) :
                    used_by_curr_pic_flag[j] = t.read ('uint:1')
                if used_by_curr_pic_flag[j] :
                    use_delta_flag[j] = t.read ('uint:1')
        
             else:      
                """            
            
                num_negative_pics = t.read ('ue')
                num_positive_pics = t.read ('ue')
                delta_poc_s0_minus1 = [t.read ('ue') for _ in range (num_negative_pics)]
                used_by_curr_pic_s0_flag = [ t.read ('uint:1') for _ in range (num_negative_pics)]
                delta_poc_s1_minus1 = [t.read ('ue') for _ in range(num_positive_pics)]
                used_by_curr_pic_s1_flag = [t.read ('uint:1') for _ in range(num_positive_pics)]

          
    long_term_ref_pics_present_flag = t.read ('uint:1')
    if long_term_ref_pics_present_flag :
        num_long_term_ref_pics_sps = t.read ('ue')
        
        for i in range < (num_long_term_ref_pics_sps): 
            lt_ref_pic_poc_lsb_sps[i] = t.read ('ue')
            used_by_curr_pic_lt_sps_flag[i] = t.read ('uint:1')
       
    sps_temporal_mvp_enabled_flag = t.read ('uint:1')
    strong_intra_smoothing_enabled_flag = t.read ('uint:1')
    vui_parameters_present_flag = t.read ('uint:1')
    if vui_parameters_present_flag :
       vp = vui_parameters(t)
    sps_extension_present_flag = t.read ('uint:1')
    if sps_extension_present_flag :
        sps_range_extension_flag = t.read ('uint:1')
        sps_multilayer_extension_flag = t.read ('uint:1')
        sps_3d_extension_flag = t.read ('uint:1')
        sps_extension_5bits = t.read ('uint:1')
    tb = rbsp_trailing_bits(t,len(t))
    print ('Reading of SPS NAL finished. Read ',len(t),' of SPS NALu data.\n')
    
# print block
    """
    print ('sps_video_parameter_set_id', sps_video_parameter_set_id)
    print ('sps_max_sub_layers_minus1', sps_max_sub_layers_minus1)
    print ('sps_temporal_id_nesting_flag', sps_temporal_id_nesting_flag)
    ptl.show()
    print ('sps_seq_parameter_set_id', sps_seq_parameter_set_id)
    print ('chroma_format_idc', chroma_format_idc)
    if chroma_format_idc == 3:
        print ('separate_colour_plane_flag', separate_colour_plane_flag)
    print ('pic_width_in_luma_samples ', pic_width_in_luma_samples) #produces wrong number
    print ('pic_height_in_luma_samples', pic_height_in_luma_samples) #produces wrong number
    print ('conformance_window_flag', conformance_window_flag)
    print ('bit_depth_luma_minus8', bit_depth_luma_minus8)
    print ('bit_depth_chroma_minus8', bit_depth_chroma_minus8)
    print ('log2_max_pic_order_cnt_lsb_minus4', log2_max_pic_order_cnt_lsb_minus4)
    print ('sps_sub_layer_ordering_info_present_flag', sps_sub_layer_ordering_info_present_flag)

    if sps_sub_layer_ordering_info_present_flag :
       print ('sps_max_dec_pic_buffering_minus1', sps_max_dec_pic_buffering_minus1)
       print ('sps_max_num_reorder_pics', sps_max_num_reorder_pics)
       print ('sps_max_latency_increase_plus1', sps_max_latency_increase_plus1)
    
    print ('log2_min_luma_coding_block_size_minus3',log2_min_luma_coding_block_size_minus3)
    print ('log2_diff_max_min_luma_coding_block_size',log2_diff_max_min_luma_coding_block_size)
    print ('log2_min_luma_transform_block_size_minus2',log2_min_luma_transform_block_size_minus2)
    print ('log2_diff_max_min_luma_transform_block_size', log2_diff_max_min_luma_transform_block_size)
    print ('max_transform_hierarchy_depth_inter', max_transform_hierarchy_depth_inter)
    print ('max_transform_hierarchy_depth_intra', max_transform_hierarchy_depth_intra)
    print ('scaling_list_enabled_flag',scaling_list_enabled_flag)
    print ('amp_enabled_flag',amp_enabled_flag)
    print ('sample_adaptive_offset_enabled_flag',sample_adaptive_offset_enabled_flag)
    print ('pcm_enabled_flag',pcm_enabled_flag)
    if pcm_enabled_flag :
        print ('pcm_sample_bit_depth_luma_minus1',pcm_sample_bit_depth_luma_minus1)
        print ('pcm_sample_bit_depth_chroma_minus1',pcm_sample_bit_depth_chroma_minus1)
        print ('log2_min_pcm_luma_coding_block_size_minus3',log2_min_pcm_luma_coding_block_size_minus3)
        print ('log2_diff_max_min_pcm_luma_coding_block_size',log2_diff_max_min_pcm_luma_coding_block_size)
        print ('pcm_loop_filter_disabled_flag',pcm_loop_filter_disabled_flag)
    print ('num_short_term_ref_pic_sets',num_short_term_ref_pic_sets)
    print ('long_term_ref_pics_present_flag',long_term_ref_pics_present_flag)
    print ('sps_temporal_mvp_enabled_flag',sps_temporal_mvp_enabled_flag)
    print ('strong_intra_smoothing_enabled_flag',strong_intra_smoothing_enabled_flag)
    print ('vui_parameters_present_flag',vui_parameters_present_flag)
    if vui_parameters_present_flag :
        vp.show()
    print ('sps_extension_present_flag',sps_extension_present_flag)
    """
# New BS write Block
    print ('Making modified SPS NALu...')
    new_bs = BitStream()
    new_bs += pack('uint:4,uint:3,uint:1',sps_video_parameter_set_id,sps_max_sub_layers_minus1,sps_temporal_id_nesting_flag)
    new_bs += pack ('uint:2,uint:1,uint:5',ptl.general_profile_space, ptl.general_tier_flag,ptl.general_profile_idc)
    for i in range (32) :
        new_bs += pack('uint:1',int(ptl.general_profile_compatibility_flag[i]))
    new_bs += pack ('uint:1',ptl.general_progressive_source_flag)
    new_bs += pack ('uint:1',ptl.general_interlaced_source_flag)
    new_bs += pack ('uint:1',ptl.general_non_packed_constraint_flag)
    new_bs += pack ('uint:1',ptl.general_frame_only_constraint_flag)
    new_bs += pack ('uint:44',ptl.general_reserved_zero_44bits)
    new_bs += pack ('uint:8',ptl.general_level_idc)
    new_bs += pack ('ue',sps_seq_parameter_set_id)
    new_bs += pack ('ue',chroma_format_idc)
    if chroma_format_idc == 3:
        new_bs += pack ('uint:1',separate_colour_plane_flag)
    new_bs += pack ('ue',pic_width_in_luma_samples)
    new_bs += pack ('ue',pic_height_in_luma_samples)
    new_bs += pack ('uint:1',conformance_window_flag)
    if (conformance_window_flag) :
        new_bs += pack ('ue',conf_win_left_offset)
        new_bs += pack ('ue',conf_win_right_offset)
        new_bs += pack ('ue',conf_win_top_offset)
        new_bs += pack ('ue',conf_win_bottom_offset)
    new_bs += pack ('ue',bit_depth_luma_minus8)
    new_bs += pack ('ue',bit_depth_chroma_minus8)
    new_bs += pack ('ue',log2_max_pic_order_cnt_lsb_minus4)
    new_bs += pack ('uint:1',sps_sub_layer_ordering_info_present_flag)
#   for (i = (sps_sub_layer_ordering_info_present_flag ? 0 : sps.max_sub_layers_minus1); i <= sps.max_sub_layers_minus1; i++)
    if sps_sub_layer_ordering_info_present_flag :
            new_bs += pack ('ue',sps_max_dec_pic_buffering_minus1)
            new_bs += pack ('ue',sps_max_num_reorder_pics)
            new_bs += pack ('ue',sps_max_latency_increase_plus1)
    new_bs += pack ('ue',log2_min_luma_coding_block_size_minus3)
    new_bs += pack ('ue',log2_diff_max_min_luma_coding_block_size)
    new_bs += pack ('ue',log2_min_luma_transform_block_size_minus2)
    new_bs += pack ('ue',log2_diff_max_min_luma_transform_block_size)
    new_bs += pack ('ue',max_transform_hierarchy_depth_inter)
    new_bs += pack ('ue',max_transform_hierarchy_depth_intra)
    new_bs += pack ('uint:1',scaling_list_enabled_flag)
    #
    new_bs += pack ('uint:1',amp_enabled_flag)
    new_bs += pack ('uint:1',sample_adaptive_offset_enabled_flag)
    new_bs += pack ('uint:1',pcm_enabled_flag)
    if pcm_enabled_flag :
        new_bs += pack ('uint:4',pcm_sample_bit_depth_luma_minus1)
        new_bs += pack ('uint:4',pcm_sample_bit_depth_chroma_minus1)
        new_bs += pack ('ue',log2_min_pcm_luma_coding_block_size_minus3)
        new_bs += pack ('ue',log2_diff_max_min_pcm_luma_coding_block_size)
        new_bs += pack ('uint:1',pcm_loop_filter_disabled_flag)
    new_bs += pack ('ue',num_short_term_ref_pic_sets)


    if num_short_term_ref_pic_sets :
        for i in range (num_short_term_ref_pic_sets) :
            if i != 0 :
                new_bs += pack ('uint:1',inter_ref_pic_set_prediction_flag)

        
        
            if  not 'inter_ref_pic_set_prediction_flag' in globals() :
                """     
                if i == num_short_term_ref_pic_sets :
                    new_bs += pack ('ue',delta_idx_minus1)
                new_bs += pack ('uint:1', delta_rps_sign)
                new_bs += pack ('ue',abs_delta_rps_minus1)
                for j in range (NumDeltaPocs[i - (delta_idx_minus1 +1)]) :
                    new_bs += pack ('uint:1', used_by_curr_pic_flag[j])
                    if used_by_curr_pic_flag[j] :
                        new_bs += pack ('uint:1',use_delta_flag[j])
        
            else :
                """    
                new_bs += pack ('ue',num_negative_pics)
                new_bs += pack ('ue',num_positive_pics)
                new_bs += [pack ('ue',delta_poc_s0_minus1[_]) for _ in range (num_negative_pics)]
                new_bs += [pack ('uint:1',used_by_curr_pic_s0_flag[_]) for _ in range (num_negative_pics)]
                new_bs += [pack ('ue',delta_poc_s1_minus1[_]) for _ in range(num_positive_pics)]
                new_bs += [pack ('uint:1',used_by_curr_pic_s1_flag[_]) for _ in range(num_positive_pics)]
        

    new_bs += pack ('uint:1',long_term_ref_pics_present_flag)
    if long_term_ref_pics_present_flag :
        new_bs += pack ('ue',num_long_term_ref_pics_sps)
    new_bs += pack ('uint:1',sps_temporal_mvp_enabled_flag)
    new_bs += pack ('uint:1',strong_intra_smoothing_enabled_flag)
    new_bs += pack ('uint:1',vui_parameters_present_flag)
# VUI VP pack Section
    if vui_parameters_present_flag :
       new_bs += pack ('uint:1',vp.aspect_ratio_info_present_flag)
       if vp.aspect_ratio_info_present_flag :
            new_bs += pack ('uint:8',vp.aspect_ratio_idc)
            if vp.aspect_ratio_idc == 255 :
                new_bs += pack ('uint:16',vp.sar_width)
                new_bs += pack ('uint:16',vp.sar_height)
       new_bs += pack ('uint:1',vp.overscan_info_present_flag)
       if vp.overscan_info_present_flag :
           new_bs += pack ('uint:1',vp.overscan_appropriate_flag)
       new_bs += pack ('uint:1',vp.video_signal_type_present_flag)
       if vp.video_signal_type_present_flag :
           new_bs += pack ('uint:3',vp.video_format)
           new_bs += pack ('uint:1',vp.video_full_range_flag)
           new_bs += pack ('uint:1',vp.colour_description_present_flag)
           if vp.colour_description_present_flag :
               new_bs += pack ('uint:8',vp.colour_primaries)
               new_bs += pack ('uint:8',vp.transfer_characteristics)
               new_bs += pack ('uint:8',vp.matrix_coeffs)
       new_bs += pack ('uint:1',vp.chroma_loc_info_present_flag)
       if vp.chroma_loc_info_present_flag :
           new_bs += pack ('ue',vp.chroma_sample_loc_type_top_field)
           new_bs += pack ('ue',vp.chroma_sample_loc_type_bottom_field)
       new_bs += pack ('uint:1',vp.neutral_chroma_indication_flag)
       new_bs += pack ('uint:1',vp.field_seq_flag)
       new_bs += pack ('uint:1',vp.frame_field_info_present_flag)
       new_bs += pack ('uint:1',vp.default_display_window_flag)
       if vp.default_display_window_flag :
           new_bs += pack ('ue',vp.def_disp_win_left_offset)
           new_bs += pack ('ue',vp.def_disp_win_right_offset)
           new_bs += pack ('ue',vp.def_disp_win_top_offset)
           new_bs += pack ('ue',vp.def_disp_win_bottom_offset)
       new_bs += pack ('uint:1',vp.vui_timing_info_present_flag)
       if vp.vui_timing_info_present_flag :
           new_bs += pack ('uint:32',vp.vui_num_units_in_tick)
           new_bs += pack ('uint:32',vp.vui_time_scale)
           new_bs += pack ('uint:1',vp.vui_poc_proportional_to_timing_flag)
           if vp.vui_poc_proportional_to_timing_flag :
               new_bs += pack ('ue',vp.vui_num_ticks_poc_diff_one_minus1)
           new_bs += pack ('uint:1',vp.vui_hrd_parameters_present_flag)
           """
           if( vui_hrd_parameters_present_flag )
           hrd_parameters( 1, sps_max_sub_layers_minus1 )
           """
       new_bs += pack ('uint:1',vp.bitstream_restriction_flag)
       if vp. bitstream_restriction_flag :
           new_bs += pack ('uint:1',vp.tiles_fixed_structure_flag)
           new_bs += pack ('uint:1',vp.motion_vectors_over_pic_boundaries_flag)
           new_bs += pack ('uint:1',vp.restricted_ref_pic_lists_flag)
           new_bs += pack ('ue',vp.min_spatial_segmentation_idc)
           new_bs += pack ('ue',vp.max_bytes_per_pic_denom)
           new_bs += pack ('ue',vp.max_bits_per_min_cu_denom)
           new_bs += pack ('ue',vp.log2_max_mv_length_horizontal)
           new_bs += pack ('ue',vp.log2_max_mv_length_vertical)

    new_bs += pack ('uint:1',sps_extension_present_flag)
    if sps_extension_present_flag :
        new_bs += pack ('uint:1',sps_range_extension_flag)
        new_bs += pack ('uint:1',sps_multilayer_extension_flag)
        new_bs += pack ('uint:1',sps_3d_extension_flag)
        new_bs += pack ('uint:1',sps_extension_5bits)

    new_bs += pack ('uint:1',tb.rbsp_stop_one_bit)
    while len(new_bs) < t.pos :
        new_bs += pack ('uint:1',tb.rbsp_alignment_zero_bit)

#    self.sub_layer_profile_present_flag = []
#    self.sub_layer_level_present_flag = []
#    for i in range(maxNumSubLayersMinus1):
#        self.sub_layer_profile_present_flag.append(t.read('uint:1'))
#        self.sub_layer_level_present_flag.append(t.read('uint:1'))
    
    pre_new_bs = pack ('uint:1,2*uint:6,uint:3', forbidden_zero_bit,nal_unit_type,nuh_layer_id,nuh_temporal_id_plus1)
    new_bs.replace ('0x0000','0x000003',bytealigned=True)
    new_bs = pre_new_bs + new_bs + '0x00'
    nal_t_rep = nal_t[24:]
    repl = s.replace (nal_t_rep,new_bs, bytealigned=True)
    print ('Made modified SPS NALu - OK')
    if sei_ok :
        s.prepend (new_sei_string)
        print ('New SEI prepended')
    print ('Writing new stream...')
    s.tofile(o)
    progr = chunk
    while True:
        s = F.read(chunk)
        o.write(s)
        if progr < os.path.getsize(args.infile):
            print ('\rProgress ',int(round((progr/os.path.getsize(args.infile))*100)),'%',end='')
        progr = progr + chunk
        if not s:
            break
    o.close()
    F.close()
    print ('\rProgress: 100 %')
    print ('=====================')
    print ('Done!')
    print ('')
    print ('File ',args.outfile,' created.')
    sys.exit()
コード例 #11
0
def decrypt_images(**kwargs):
    path = kwargs.pop('path', 'herders/static/herders/images')
    for im_path in iglob(f'{path}/**/*.png', recursive=True):
        encrypted = BitStream(filename=im_path)

        # Check if it is 'encrypted'. 8th byte is 0x0B instead of the correct signature 0x0A
        encrypted.pos = 0x07 * 8
        signature = encrypted.peek('uint:8')
        if signature == 0x0B:
            print(f'Decrypting {im_path}')
            # Correct the PNG signature
            encrypted.overwrite('0x0A', encrypted.pos)

            # Replace bits with magic decrypted values
            try:
                while True:
                    pos = encrypted.pos
                    val = encrypted.peek('uint:8')
                    encrypted.overwrite(
                        Bits(uint=com2us_decrypt_values[val], length=8), pos)
            except ReadError:
                # EOF
                pass

            # Write it back to the file
            with open(im_path, 'wb') as f:
                encrypted.tofile(f)

            continue

        # Check for weird jpeg format with extra header junk. Convert to png.
        encrypted.pos = 0
        if encrypted.peek('bytes:5') == b'Joker':
            print(f'Converting Joker container JPEG to PNG {im_path}')
            with open(im_path, 'rb') as f:
                bts = f.read()
                first_img = bts.find(b'JFIF')
                second_img = bts.rfind(b'JFIF')
                imgs = []
                if second_img > -1 and first_img != second_img:
                    imgs = [bts[:second_img], bts[second_img:]]
                    # Add Joker & header to immitate new file
                    imgs[1] = imgs[0][imgs[0].find(b'Joker'
                                                   ):first_img] + imgs[1]
                    imgs = [
                        JokerContainerFile(img, read=False) for img in imgs
                    ]
                else:
                    img = JokerContainerFile(bts, read=False)

            # Open it as a jpg and resave to disk
            try:
                if len(imgs) > 1:
                    new_imfile = Image.open(io.BytesIO(imgs[0].data.tobytes()))
                    new_mask = Image.open(io.BytesIO(
                        imgs[1].data.tobytes())).convert('L')
                    new_imfile.putalpha(new_mask)
                else:
                    new_imfile = Image.open(io.BytesIO(img.data.tobytes()))
                new_imfile.save(im_path)
            except IOError:
                print(f'Unable to open {im_path}')
コード例 #12
0
# coding: utf-8

from bitstring import BitStream

s = BitStream(filename="t.bmp")
s.pos = 0x436 * 8

while s.pos <= s.len - 7:
    s.insert('0b0', s.pos)
    s.pos += 7

f = file('gen.bmp', 'wb')
s.tofile(f)
f.close()
print 'Done'