Unpack the FCI for a Receiver Estimated Maximum Bitrate report.

    https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03
175171
def unpack_remb_fci(data):
    
    if len(data) < 8 or data[0:4] != b'REMB':
        raise ValueError('Invalid REMB prefix')

    exponent = (data[5] & 0xfc) >> 2
    mantissa = ((data[5] & 0x03) << 16) | (data[6] << 8) | data[7]
    bitrate = mantissa << exponent

    pos = 8
    ssrcs = []
    for r in range(data[4]):
        ssrcs.append(unpack_from('!L', data, pos)[0])
        pos += 4

    return (bitrate, ssrcs)
360226
def int_to_bytes(int_value: int, length: int) -> bytes:
    
    if length == 1:
        fmt = "!B"
    elif length == 2:
        fmt = "!H"
    return pack(fmt, int_value)
648951
def hkm_fc(fdata, Nmax, m, s):
    

    f = fdata[:, m]
    L1 = f.size
    MM = int(L1 / 2)
    Q = s.size

    ff = np.zeros(Q, dtype=np.complex128)
    for n in xrange(MM, L1):
        ff[n] = f[n - MM]

    for n in xrange(0, MM):
        ff[n] = f[n + MM]

    # For larger problems, this speeds things up pretty good.
    F = np.fft.fft(ff)
    S = np.fft.fft(s)
    out = 4 * np.pi * np.fft.ifft(F * S)

    return out[0:Nmax + 1]
757047
def _recv_internal(self, timeout=None):
        
        arb_id = ctypes.c_long(0)
        data = ctypes.create_string_buffer(64)
        dlc = ctypes.c_uint(0)
        flags = ctypes.c_uint(0)
        timestamp = ctypes.c_ulong(0)

        if timeout is None:
            # Set infinite timeout
            # http://www.kvaser.com/canlib-webhelp/group___c_a_n.html#ga2edd785a87cc16b49ece8969cad71e5b
            timeout = 0xFFFFFFFF
        else:
            timeout = int(timeout * 1000)

        #log.log(9, 'Reading for %d ms on handle: %s' % (timeout, self._read_handle))
        status = canReadWait(
            self._read_handle,
            ctypes.byref(arb_id),
            ctypes.byref(data),
            ctypes.byref(dlc),
            ctypes.byref(flags),
            ctypes.byref(timestamp),
            timeout  # This is an X ms blocking read
        )

        if status == canstat.canOK:
            #log.debug('read complete -> status OK')
            data_array = data.raw
            flags = flags.value
            is_extended = bool(flags & canstat.canMSG_EXT)
            is_remote_frame = bool(flags & canstat.canMSG_RTR)
            is_error_frame = bool(flags & canstat.canMSG_ERROR_FRAME)
            is_fd = bool(flags & canstat.canFDMSG_FDF)
            bitrate_switch = bool(flags & canstat.canFDMSG_BRS)
            error_state_indicator = bool(flags & canstat.canFDMSG_ESI)
            msg_timestamp = timestamp.value * TIMESTAMP_FACTOR
            rx_msg = Message(arbitration_id=arb_id.value,
                             data=data_array[:dlc.value],
                             dlc=dlc.value,
                             is_extended_id=is_extended,
                             is_error_frame=is_error_frame,
                             is_remote_frame=is_remote_frame,
                             is_fd=is_fd,
                             bitrate_switch=bitrate_switch,
                             error_state_indicator=error_state_indicator,
                             channel=self.channel,
                             timestamp=msg_timestamp + self._timestamp_offset)
            #log.debug('Got message: %s' % rx_msg)
            return rx_msg, self._is_filtered
        else:
            #log.debug('read complete -> status not okay')
            return None, self._is_filtered
776993
def _recv_cf(self, data):
        """"""
        if self.rx_state != ISOTP_WAIT_DATA:
            return 0

        self.rx_timer.cancel()

        # CFs are never longer than the FF
        if len(data) > self.rx_ll_dl:
            return 1

        # CFs have usually the LL_DL length
        if len(data) < self.rx_ll_dl:
            # this is only allowed for the last CF
            if self.rx_len - self.rx_idx > self.rx_ll_dl:
                warning("Received a CF with insuffifient length")
                return 1

        if six.indexbytes(data, 0) & 0x0f != self.rx_sn:
            # Wrong sequence number
            warning("RX state was reset because wrong sequence number was "
                    "received")
            self.rx_state = ISOTP_IDLE
            return 1

        self.rx_sn = (self.rx_sn + 1) % 16
        self.rx_buf += data[1:]
        self.rx_idx = len(self.rx_buf)

        if self.rx_idx >= self.rx_len:
            # we are done
            self.rx_buf = self.rx_buf[0:self.rx_len]
            self.rx_state = ISOTP_IDLE
            self.rx_queue.put(self.rx_buf)
            for cb in self.rx_callbacks:
                cb(self.rx_buf)
            self.call_release()
            self.rx_buf = None
            return 0

        # perform blocksize handling, if enabled
        if self.rxfc_bs != 0:
            self.rx_bs += 1

            # check if we reached the end of the block
            if self.rx_bs >= self.rxfc_bs and not self.listen_mode:
                # send our FC frame
                load = self.ea_hdr
                load += struct.pack("BBB", N_PCI_FC, self.rxfc_bs,
                                    self.rxfc_stmin)
                self.can_send(load)

        # wait for another CF
        self.rx_timer.set_timeout(self.cf_timeout, self._rx_timer_handler)
        return 0
1258121
def _recv_mbus(self):
        
        # receive
        # modbus TCP receive
        if self.__mode == const.MODBUS_TCP:
            # 7 bytes header (mbap)
            rx_buffer = self._recv_all(7)
            # check recv
            if not (rx_buffer and len(rx_buffer) == 7):
                self.__last_error = const.MB_RECV_ERR
                self.__debug_msg('_recv MBAP error')
                self.close()
                return None
            rx_frame = rx_buffer
            # decode header
            (rx_hd_tr_id, rx_hd_pr_id,
             rx_hd_length, rx_hd_unit_id) = struct.unpack('>HHHB', rx_frame)
            # check header
            if not ((rx_hd_tr_id == self.__hd_tr_id) and
                    (rx_hd_pr_id == 0) and
                    (rx_hd_length < 256) and
                    (rx_hd_unit_id == self.__unit_id)):
                self.__last_error = const.MB_RECV_ERR
                self.__debug_msg('MBAP format error')
                if self.__debug:
                    rx_frame += self._recv_all(rx_hd_length - 1)
                    self._pretty_dump('Rx', rx_frame)
                self.close()
                return None
            # end of frame
            rx_buffer = self._recv_all(rx_hd_length - 1)
            if not (rx_buffer and
                    (len(rx_buffer) == rx_hd_length - 1) and
                    (len(rx_buffer) >= 2)):
                self.__last_error = const.MB_RECV_ERR
                self.__debug_msg('_recv frame body error')
                self.close()
                return None
            rx_frame += rx_buffer
            # dump frame
            if self.__debug:
                self._pretty_dump('Rx', rx_frame)
            # body decode
            rx_bd_fc = struct.unpack('B', rx_buffer[0:1])[0]
            f_body = rx_buffer[1:]
        # modbus RTU receive
        elif self.__mode == const.MODBUS_RTU:
            # receive modbus RTU frame (max size is 256 bytes)
            rx_buffer = self._recv(256)
            # on _recv error
            if not rx_buffer:
                return None
            rx_frame = rx_buffer
            # dump frame
            if self.__debug:
                self._pretty_dump('Rx', rx_frame)
            # RTU frame min size is 5 bytes
            if len(rx_buffer) < 5:
                self.__last_error = const.MB_RECV_ERR
                self.__debug_msg('short frame error')
                self.close()
                return None
            # check CRC
            if not self._crc_is_ok(rx_frame):
                self.__last_error = const.MB_CRC_ERR
                self.__debug_msg('CRC error')
                self.close()
                return None
            # body decode
            (rx_unit_id, rx_bd_fc) = struct.unpack("BB", rx_frame[:2])
            # check
            if not (rx_unit_id == self.__unit_id):
                self.__last_error = const.MB_RECV_ERR
                self.__debug_msg('unit ID mismatch error')
                self.close()
                return None
            # format f_body: remove unit ID, function code and CRC 2 last bytes
            f_body = rx_frame[2:-2]
        # for auto_close mode, close socket after each request
        if self.__auto_close:
            self.close()
        # check except
        if rx_bd_fc > 0x80:
            # except code
            exp_code = struct.unpack('B', f_body[0:1])[0]
            self.__last_error = const.MB_EXCEPT_ERR
            self.__last_except = exp_code
            self.__debug_msg('except (code ' + str(exp_code) + ')')
            return None
        else:
            # return
            return f_body
1290014
def fan_maxcfm(ddtt):
    """"""
    if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize':
    # str can fail with unicode chars :-(
        return 'autosize'
    else:
        m3s = float(ddtt.Maximum_Flow_Rate)
        return m3s2cfm(m3s)
130496
def _bandpass(self, fc_low=5, fc_high=20):
        
        self.fc_low = fc_low
        self.fc_high = fc_high

        b, a = signal.butter(2, [float(fc_low) * 2 / self.fs,
                                 float(fc_high) * 2 / self.fs], 'pass')
        self.sig_f = signal.filtfilt(b, a, self.sig[self.sampfrom:self.sampto],
                                     axis=0)
        # Save the passband gain (x2 due to double filtering)
        self.filter_gain = get_filter_gain(b, a, np.mean([fc_low, fc_high]),
                                           self.fs) * 2
609665
def from_bytes(cls, bitstream, decode_payload=True):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the version
        version = bitstream.read('uint:4')
        if version != packet.version:
            raise ValueError('Provided bytes do not contain an IPv4 packet')

        # Read the header length
        ihl = bitstream.read('uint:4')
        if ihl < 5:
            raise ValueError('Invalid IPv4 header length')

        # Now that we know the length of the header we store it to be able
        # to easily recalculate the header checksum later
        remaining_header_bits = (ihl * 32) - 8
        header = (BitStream('uint:4=4, uint:4=%d' % ihl) +
                  bitstream.peek(remaining_header_bits))

        # Read the type of service
        packet.tos = bitstream.read('uint:8')

        # Read the total length
        total_length = bitstream.read('uint:16')
        if total_length < ihl * 4:
            raise ValueError('Total length is shorter than the header')

        # Read the identification
        packet.identification = bitstream.read('uint:16')

        # Read the flags
        (reserved,
         packet.dont_fragment,
         packet.more_fragments) = bitstream.readlist('3*bool')

        if reserved:
            raise ValueError('Reserved flag must be 0')

        # Read the fragment offset
        packet.fragment_offset = bitstream.read('uint:13')

        # Read the TTL
        packet.ttl = bitstream.read('uint:8')

        # Read the protocol number
        packet.protocol = bitstream.read('uint:8')

        # Read the header checksum
        header_checksum = bitstream.read('uint:16')

        # Set the checksum bits in the header to 0 and re-calculate
        header[80:96] = BitStream(16)
        my_checksum = checksum.ones_complement(header.bytes)

        if my_checksum != header_checksum:
            raise ValueError('Header checksum does not match')

        # Read the source and destination addresses
        packet.source = IPv4Address(bitstream.read('uint:32'))
        packet.destination = IPv4Address(bitstream.read('uint:32'))

        # Read the options
        option_len = (ihl - 5) * 4
        packet.options = bitstream.read('bytes:%d' % option_len)

        # And the rest is payload
        payload_bytes = (total_length) - (ihl * 4)
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        if decode_payload:
            payload_class = protocol_registry.get_type_class(packet.protocol)
            if payload_class:
                packet.payload = payload_class.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
740969
def effsnr(snr, reduced_x2, fac=250.):
    
    snr = numpy.array(snr, ndmin=1, dtype=numpy.float64)
    rchisq = numpy.array(reduced_x2, ndmin=1, dtype=numpy.float64)
    esnr = snr / (1 + snr ** 2 / fac) ** 0.25 / rchisq ** 0.25

    # If snr input is float, return a float. Otherwise return numpy array.
    if hasattr(snr, '__len__'):
        return esnr
    else:
        return esnr[0]
244806
def unpack_float16(src):
    
    bc = BitConsumer(src)
    sign = bc.u_get(1)
    exponent = bc.u_get(5)
    mantissa = bc.u_get(10)
    exponent -= 16
    mantissa /= 2 ** 10
    num = (-1 ** sign) * mantissa * (10 ** exponent)
    return num
635476
static public long unpackRecid(DataInput2 in) throws IOException {
        long val = in.readPackedLong();
        val = DataIO.parity1Get(val);
        return val >>> 1;
    }
863835
def pack(self):
    
    buf = np.zeros(512, dtype=np.uint8)
    packed_len = self._get_framed(buf, 0, self._copy_payload)
    d = buf[:packed_len]
    return d.tobytes()
960634
def _unpack_bin(self, packed):
        

        output = struct.unpack('H', packed)
        bits16 = output[0]
        r = (bits16 & 0xF800) >> 11
        g = (bits16 & 0x7E0) >> 5
        b = (bits16 & 0x1F)
        return [int(r << 3), int(g << 2), int(b << 3)]
349445
def return_rri(self, begsam, endsam):
        """"""
        interval = endsam - begsam
        dat = empty(interval)
        k = 0
            
        with open(self.filename, 'rt') as f:
            [next(f) for x in range(12)]
            
            for j, datum in enumerate(f):
                
                if begsam <= j < endsam:
                    dat[k] = float64(datum[:datum.index('\t')])
                    k += 1
                    if k == interval:
                        break
                    
        return dat
171216
def parse_volumedetect_stats(self):
        
        logger.info(
            "Running first pass volumedetect filter for stream {}".format(self.stream_id)
        )

        filter_str = '[0:{}]volumedetect'.format(self.stream_id)

        cmd = [
            self.media_file.ffmpeg_normalize.ffmpeg_exe, '-nostdin', '-y',
            '-i', self.media_file.input_file,
            '-filter_complex', filter_str,
            '-vn', '-sn', '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        for progress in cmd_runner.run_ffmpeg_command():
            yield progress
        output = cmd_runner.get_output()

        logger.debug("Volumedetect command output:")
        logger.debug(output)

        mean_volume_matches = re.findall(r"mean_volume: ([\-\d\.]+) dB", output)
        if mean_volume_matches:
            self.loudness_statistics['mean'] = float(mean_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get mean volume for {}".format(self.media_file.input_file)
            )

        max_volume_matches = re.findall(r"max_volume: ([\-\d\.]+) dB", output)
        if max_volume_matches:
            self.loudness_statistics['max'] = float(max_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get max volume for {}".format(self.media_file.input_file)
            )
62592
def to_bytes(self):
        '''
        
        '''
        # Check properties
        self.sanitize()

        # Start with reserved bits
        bitstream = self._to_rsvd1()

        # Add zeroes for the flags
        bitstream += self._to_flags()

        # Add the type
        bitstream += BitArray('uint:8=%d' % self.lcaf_type)

        # Some more reserved bits
        bitstream += self._to_rsvd2()

        # Construct the data
        data = self._to_data_bytes()

        # Add the length
        data_length = data.len / 8
        bitstream += BitArray('uint:16=%d' % data_length)

        return (bitstream + data).bytes