Пример #1
0
def receive_data(settings, role):
    """Receive data from the other node."""
    # Setup kodo encoder_factory and decoder
    decoder_factory = kodo.RLNCDecoderFactory(
        field=kodo.field.binary,
        symbols=settings['symbols'],
        symbol_size=settings['symbol_size'])

    decoder = decoder_factory.build()
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Set receiving sockets
    data_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data_socket.settimeout(settings['timeout'])
    data_socket.bind(('', settings['data_port']))

    if role == 'client':
        address = (settings['server_ip'], settings['server_control_port'])
        send_settings(settings)
    else:  # server
        address = (settings['client_ip'], settings['client_control_port'])
        send(send_socket, "settings OK, receiving", address)

    # Decode coded packets
    received = 0
    start = time.clock()
    end = None
    while 1:
        try:
            packet = data_socket.recv(settings['symbol_size'] + 100)

            if not decoder.is_complete():
                decoder.read_payload(bytearray(packet))
                received += 1

            if decoder.is_complete():
                if end is None:
                    end = time.clock()  # stopping time once
                send(send_socket, "Stop sending", address)

        except socket.timeout:
            break  # no more data arriving

    # in case we did not complete
    if end is None:
        end = time.clock()

    data_socket.close()

    if not decoder.is_complete():
        print("Decoding failed")

    size = decoder.block_size() * (float(received) / settings['symbols'])
    microseconds = 1e6 * (end - start)
    print("Received {0} packets, {1} kB in {2:.0f} microseconds at "
          "{3:.2f} Mbit/s.".format(received, size / 1000, microseconds,
                                   decoder.block_size() * 8 / microseconds))
Пример #2
0
def simulation(g, k, systematic=True, data=None):
    factory = kodo.RLNCEncoderFactory(field, g, k)
    encoder = factory.build()
    if data == None:
        data_in = bytearray(os.urandom(encoder.block_size()))
    else:
        data_in = bytearray(data)

    encoder.set_const_symbols(data_in)
    if systematic == True:
        encoder.set_systematic_off()
    else:
        encoder.set_systematic_on()

    #if encoder.is_systematic_on():
    #print("Systematic is on")
    #else:
    #print("Systematic is off")

    decoder_factory = kodo.RLNCDecoderFactory(field, g, k)
    decoder = decoder_factory.build()
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    #print('Measurering time of encode-decode')

    while not decoder.is_complete():
        # Encode a packet into the payload buffer
        start_encode = time.time() * 1000  # milliseconds
        packet = encoder.write_payload()
        end_encode = time.time() * 1000  # milliseconds
        # Pass that packet to the decoder
        start_decode = time.time() * 1000  # milliseconds
        decoder.read_payload(packet)
        end_decode = time.time() * 1000  # milliseconds

        #print("Rank of decoder {}".format(decoder.rank()))

        # Symbols that were received in the systematic phase correspond
        # to the original source symbols and are therefore marked as
        # decoded
        #print("Symbols decoded {}".format(decoder.symbols_uncoded()))

    #print("Coding finished")

    # The decoder is complete, the decoded symbols are now available in
    # the data_out buffer: check if it matches the data_in buffer
    timing_encode = end_encode - start_encode
    timing_decode = end_decode - start_decode
    #print('%s milliseconds' %(timing))
    #print("Checking results...")
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unable to decode please file a bug report :)")
        sys.exit(1)
    return timing_encode, timing_decode
Пример #3
0
def decode(data, size):
    symbol_size = int(math.ceil(size / float(symbols)))
    # Create decoder
    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    for i in data:
        decoder.read_payload(i)

    return data_out
Пример #4
0
def main():
    """Simple example showing how to encode and decode a block of memory."""
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 8
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    packet_number = 0
    while not decoder.is_complete():
        # Generate an encoded packet
        packet = encoder.write_payload()
        print("Packet {} encoded!".format(packet_number))

        # Pass that packet to the decoder
        decoder.read_payload(packet)
        print("Packet {} decoded!".format(packet_number))
        packet_number += 1
        print("rank: {}/{}".format(decoder.rank(), decoder.symbols()))

    print("Coding finished")

    # The decoder is complete, the decoded symbols are now available in
    # the data_out buffer: check if it matches the data_in buffer
    print("Checking results...")
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unable to decode please file a bug report :)")
        sys.exit(1)
Пример #5
0
def main():

    # Setup canvas and viewer
    size = 512
    canvas = kodo_helpers.CanvasScreenEngine(size * 2, size)

    encoder_viewer = kodo_helpers.EncodeStateViewer(
        size=size,
        canvas=canvas)

    decoder_viewer = kodo_helpers.DecodeStateViewer(
        size=size,
        canvas=canvas,
        canvas_position=(size, 0))

    canvas.start()
    try:
        field = kodo.field.binary8
        symbols = 64
        symbol_size = 16

        encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
        encoder = encoder_factory.build()

        decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
        decoder = decoder_factory.build()

        data_in = bytearray(os.urandom(encoder.block_size()))
        encoder.set_const_symbols(data_in)

        data_out = bytearray(decoder.block_size())
        decoder.set_mutable_symbols(data_out)

        def decoder_callback(zone, msg):
            decoder_viewer.trace_callback(zone, msg)
        decoder.set_trace_callback(decoder_callback)

        def encoder_callback(zone, msg):
            encoder_viewer.trace_callback(zone, msg)
        encoder_viewer.set_symbols(encoder.symbols())
        encoder.set_trace_callback(encoder_callback)

        while not decoder.is_complete():
            # Encode a packet into the payload buffer
            packet = encoder.write_payload()

            # Here we "simulate" a packet loss of approximately 50%
            # by dropping half of the encoded packets.
            # When running this example you will notice that the initial
            # symbols are received systematically (i.e. uncoded). After
            # sending all symbols once uncoded, the encoder will switch
            # to full coding, in which case you will see the full encoding
            # vectors being sent and received.
            if random.choice([True, False]):
                continue

            # Pass that packet to the decoder
            decoder.read_payload(packet)

        time.sleep(1)
    finally:
        # What ever happens, make sure we stop the viewer.
        canvas.stop()

    # Check we properly decoded the data
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
Пример #6
0
def main():

    # Get directory of this file
    directory = os.path.dirname(os.path.realpath(__file__))

    # The name of the file to use for the test
    filename = 'lena.jpg'

    # Open the image convert it to RGB and get the height and width
    image = Image.open(os.path.join(directory, filename)).convert("RGB")
    image_width = image.size[0]
    image_height = image.size[1]

    # The canvas should be able to contain both the image and the decoding
    # state. Note the decoding state is the same width as the image height.
    canvas_width = image_height + image_width + image_height

    # Create the canvas
    canvas = kodo_helpers.CanvasScreenEngine(width=canvas_width,
                                             height=image_height)

    # Create the decoding coefficient viewer
    encoding_state_viewer = kodo_helpers.EncodeStateViewer(size=image_height,
                                                           canvas=canvas)

    # Create the image viewer
    image_viewer = kodo_helpers.ImageViewer(width=image_width,
                                            height=image_height,
                                            canvas=canvas,
                                            canvas_position=(image_width, 0))

    # Create the decoding coefficient viewer
    decoding_state_viewer = kodo_helpers.DecodeStateViewer(
        size=image_height, canvas=canvas, canvas_position=(image_width * 2, 0))

    # Pick a symbol size (image_width * 3 will create a packet for each
    # horizontal line of the image, that is three bytes per pixel (RGB))
    symbol_size = image_width * 3

    # Based on the size of the image and the symbol size, calculate the number
    # of symbols needed for containing the image in a single generation.
    symbols = int(math.ceil(image_width * image_height * 3.0 / symbol_size))

    field = kodo.field.binary8

    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Connect the tracing callback to the decode state viewer
    def encoding_callback(zone, msg):
        encoding_state_viewer.trace_callback(zone, msg)

    encoding_state_viewer.set_symbols(encoder.symbols())
    encoder.set_trace_callback(encoding_callback)

    def decoding_callback(zone, msg):
        decoding_state_viewer.trace_callback(zone, msg)

    decoder.set_trace_callback(decoding_callback)

    # Create a bytearray from the image to use in the encoding (only pick the
    # data we have room for).
    data_in = bytearray(image.tobytes()[-encoder.block_size():])

    # Set the converted image data
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    # Create an image viwer and run the following code in a try catch;
    # this prevents the program from locking up, as the finally clause will
    # close down the image viewer.
    canvas.start()
    try:
        while not decoder.is_complete():
            packet = encoder.write_payload()

            # Drop some packets
            if random.choice([True, False]):
                decoder.read_payload(packet)

            # The data_out buffer is continuously updated
            image_viewer.set_image(data_out)

        # Let the user see the complete photo before closing the application
        for i in range(100):
            image_viewer.set_image(data_out)
    finally:
        canvas.stop()

    # Check we properly decoded the data
    if data_out[:len(data_in)] == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
Пример #7
0
import network as vc
from global_variables import *
import coefficients_getter as cg
from redundancychecker import get_greedy_stategy_pfs

dst_counter = 0

transmission_counter = 0
forwarding_counter = 0
buffer = deque([])
tot_send_time = 0
tot_m = 0

encoder_factory = kodo.RLNCEncoderFactory(kodo.field.binary16, SYMBOLS,
                                          SYMBOL_SIZE)
decoder_factory = kodo.RLNCDecoderFactory(kodo.field.binary16, SYMBOLS,
                                          SYMBOL_SIZE)
recoder_factory = kodo.RLNCPureRecoderFactory(kodo.field.binary16, SYMBOLS,
                                              SYMBOL_SIZE)
recoder_factory.set_recoder_symbols(100)


def get_err_list(transmission_number, err):
    err_ellements = int(transmission_number * err)
    err_list = ['loss'] * err_ellements + ['success'] * (transmission_number -
                                                         err_ellements)
    random.shuffle(err_list)
    return err_list


def calc(node, coop_groups, fr_mode, greedy_mode, fail_nodes=[], dst=None):
    """
def main():
    """Example showing the result of enabling the symbol status updater."""
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 50
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    # Create two decoders, one which has the status updater turned on, and one
    # which has it off.
    decoder1 = decoder_factory.build()
    decoder2 = decoder_factory.build()

    decoder2.set_status_updater_on()

    print("decoder 1 status updater: {}".format(
        decoder1.is_status_updater_enabled()))
    print("decoder 2 status updater: {}".format(
        decoder2.is_status_updater_enabled()))

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out1 = bytearray(decoder1.block_size())
    data_out2 = bytearray(decoder1.block_size())
    decoder1.set_mutable_symbols(data_out1)
    decoder2.set_mutable_symbols(data_out2)

    # Skip the systematic phase as the effect of the symbol status decoder is
    # only visible when reading coded packets.
    encoder.set_systematic_off()

    print("Processing")
    while not decoder1.is_complete():
        # Generate an encoded packet
        payload = encoder.write_payload()
        payload_copy = copy.copy(payload)

        # Pass that packet to the decoder
        decoder1.read_payload(payload)
        decoder2.read_payload(payload_copy)
        print("decoder 1: {}".format(decoder1.symbols_uncoded()))
        print("decoder 2: {}".format(decoder2.symbols_uncoded()))
        print("-----------------")

    print("Processing finished")

    # Check if both decoders properly decoded the original data
    print("Checking results")
    if data_out1 == data_in and data_out2 == data_in:
        print("Data decoded correctly")
    else:
        print("Unable to decode please file a bug report :)")
        sys.exit(1)
def main():
    """
    Encode recode decode example.

    In Network Coding applications one of the key features is the
    ability of intermediate nodes in the network to recode packets
    as they traverse them. In Kodo it is possible to recode packets
    in decoders which provide the write_payload() function.

    This example shows how to use one encoder and two decoders to
    simulate a simple relay network as shown below (for simplicity
    we have error free links, i.e. no data packets are lost when being
    sent from encoder to decoder1 and decoder1 to decoder2):

            +-----------+     +-----------+     +-----------+
            |  encoder  |+---.| decoder1  |+---.|  decoder2 |
            +-----------+     | (recoder) |     +-----------+
                              +-----------+
    In a practical application recoding can be using in several different
    ways and one must consider several different factors e.g. such as
    reducing linear dependency by coordinating several recoding nodes
    in the network.
    Suggestions for dealing with such issues can be found in current
    research literature (e.g. MORE: A Network Coding Approach to
    Opportunistic Routing).
    """
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 42
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder1 = decoder_factory.build()
    decoder2 = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearrays where the symbols should be decoded
    # These bytearrays must not go out of scope while the encoder exists!
    data_out1 = bytearray(decoder1.block_size())
    data_out2 = bytearray(decoder1.block_size())
    decoder1.set_mutable_symbols(data_out1)
    decoder2.set_mutable_symbols(data_out2)

    while not decoder2.is_complete():

        # Encode a packet into the payload buffer
        packet = encoder.write_payload()

        # Pass that packet to decoder1
        decoder1.read_payload(packet)

        # Now produce a new recoded packet from the current
        # decoding buffer, and place it into the payload buffer
        packet = decoder1.write_payload()

        # Pass the recoded packet to decoder2
        decoder2.read_payload(packet)

    # Both decoder1 and decoder2 should now be complete,
    # check if the output buffers match the data_in buffer
    if data_out1 == data_in and data_out2 == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
def main():
    """
    Encode pure recode decode example.

    This example is very similar to encode_recode_decode_simple.py.
    The only difference is that this example uses a pure recoder instead of
    a decoder acting as a recoder. By "pure", we mean that the recoder will
    not decode the incoming data, it will only re-encode it.
    This example shows how to use an encoder, recoder, and decoder to
    simulate a simple relay network as shown below. For simplicity,
    we have error free links, i.e. no data packets are lost when being
    sent from encoder to recoder to decoder:

            +-----------+      +-----------+      +------------+
            |  encoder  |+---->| recoder   |+---->|  decoder   |
            +-----------+      +-----------+      +------------+

    The pure recoder does not need to decode all symbols, so in a sense
    the data block is "compressed" before recoding is performed.
    This could be interesting in a P2P network where an intermidiate node
    might not have enough storage to store all decoded content after it is
    decoded and consumed locally.
    """
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 42
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    recoder_factory = kodo.RLNCPureRecoderFactory(field, symbols, symbol_size)
    # Set the "capacity" for storing coded symbols in our recoder.
    # In this example, we demonstrate that this can be less than "symbols".
    # The stored coded symbols are combinations of previously received symbols.
    # When a new symbol is received, the pure recoder will combine it with
    # its existing symbols using random coefficients.
    recoder_factory.set_recoder_symbols(20)
    recoder = recoder_factory.build()

    print("Recoder properties:\n"
          "  Symbols: {}\n"
          "  Recoder symbols: {}".format(recoder.symbols(),
                                         recoder.recoder_symbols()))

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearrays where the symbols should be decoded
    # These bytearrays must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    while not decoder.is_complete():

        # Encode a packet into the payload buffer
        packet = encoder.write_payload()

        # Pass that packet to the recoder
        recoder.read_payload(packet)

        # Now produce a new recoded packet from the current decoding buffer
        recoded_packet = recoder.write_payload()

        # Pass the recoded packet to the decoder
        decoder.read_payload(recoded_packet)

    # Check we properly decoded the data
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
Пример #11
0
def main():
    """An example for using the trace functionality."""
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary8
    symbols = 5
    symbol_size = 16

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    # Setup tracing

    # Enable the stdout trace function of the encoder
    encoder.set_trace_stdout()
    encoder.set_zone_prefix("encoder")

    # Define a custom trace function for the decoder which filters the
    # trace message based on their zones
    def callback_function(zone, message):
        if zone in ["decoder_state", "symbol_coefficients_before_read_symbol"]:
            print("{}:".format(zone))
            print(message)

    decoder.set_trace_callback(callback_function)

    while not decoder.is_complete():

        # Encode a packet into the payload buffer
        packet = encoder.write_payload()

        # Here we "simulate" a packet loss of approximately 50%
        # by dropping half of the encoded packets.
        # When running this example you will notice that the initial
        # symbols are received systematically (i.e. uncoded). After
        # sending all symbols once uncoded, the encoder will switch
        # to full coding, in which case you will see the full encoding
        # vectors being sent and received.
        if random.choice([True, False]):
            print("Packet dropped.\n")
            continue

        # Pass that packet to the decoder
        decoder.read_payload(packet)

    # The decoder is complete, the decoded symbols are now available in
    # the data_out buffer: check if it matches the data_in buffer
    print("Checking results...")
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
Пример #12
0
def run_decoder(ifce):
    """Main IO loop"""

    buf = bytearray(BUFFER_SIZE)
    generation = 0
    udp_cnt = 0

    try:
        logger.info("Create the raw packet socket.")
        sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
                             socket.htons(3))
    except socket.error as error:
        raise error

    logger.info("Bind the socket to the interface: {}".format(ifce))
    sock.bind((ifce, 0))

    logger.info("Init kodo decoder.")
    # Create an encoder factory that are used to build the actual encoders
    decoder_factory = kodo.RLNCDecoderFactory(FIELD, SYMBOLS, SYMBOL_SIZE)
    decoder = decoder_factory.build()
    # Mutable bytearray to store decoded symbols from decoder.
    decode_buf = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(decode_buf)
    not_decoded_indces = list(range(decoder.symbols()))

    logger.info("Entering IO loop.")

    while True:
        time.sleep(IO_SLEEP)
        ret = rsh.recv_ipv4(sock, buf, MTU)
        if not ret:
            logger.debug("Recv a non-IPv4 frame, frame is ignored.")
            continue
        frame_len, ip_hd_offset, ip_hd_len, proto = ret

        if proto == rsh.IP_PROTO_UDP:
            udp_cnt += 1
            logger.debug(
                "Recv a UDP segment, total received UDP segments: %d "
                "frame len: %d",
                udp_cnt,
                frame_len,
            )
        else:
            logger.debug("Recv a non-UDP segment. Ignore it.")
            continue

        # Only handle UDP segments
        udp_hd_offset, _, udp_pl_offset, udp_pl_len = rsh.parse_udp(
            buf, ip_hd_offset, ip_hd_len)

        _type, cur_gen, md_pl_len = common.pull_metadata(buf, udp_pl_offset)
        logger.debug(
            "Generation number in payload: %d, current decode generation: %d, md_pl_len: %d",
            cur_gen,
            generation,
            md_pl_len,
        )

        if cur_gen > generation:
            logger.debug("Cleanup decoder for a new generation.")
            decoder = decoder_factory.build()
            decode_buf = bytearray(decoder.block_size())
            decoder.set_mutable_symbols(decode_buf)
            not_decoded_indces = list(range(decoder.symbols()))
            generation = cur_gen

        elif cur_gen == 0 and generation == 255:
            logger.debug("Cleanup decoder for a new interation.")
            decoder = decoder_factory.build()
            decode_buf = bytearray(decoder.block_size())
            decoder.set_mutable_symbols(decode_buf)
            not_decoded_indces = list(range(decoder.symbols()))
            generation = 0

        head = udp_pl_offset + META_DATA_LEN
        tail = udp_pl_offset + META_DATA_LEN + udp_pl_len
        decoder.read_payload(buf[head:tail])
        logger.debug(
            "Decode rank: %d/%d, coded symbol len: %d",
            decoder.rank(),
            decoder.symbols(),
            udp_pl_offset,
        )

        # Loop over un-decoded symbols
        for i in not_decoded_indces:
            if decoder.is_symbol_uncoded(i):
                del not_decoded_indces[not_decoded_indces.index(i)]
                logger.debug(
                    "Decoder symbol: %d, not_decoded_symbols_indces: %s",
                    i,
                    ",".join(map(str, not_decoded_indces)),
                )

                if _type == MD_TYPE_UDP:
                    buf[udp_pl_offset:udp_pl_offset +
                        md_pl_len] = decode_buf[i *
                                                SYMBOL_SIZE:i * SYMBOL_SIZE +
                                                md_pl_len]
                    udp_total_len = rsh.UDP_HDL + md_pl_len
                    ip_total_len = udp_total_len + ip_hd_len
                    frame_len = ip_total_len + rsh.ETH_HDL
                    logger.debug(
                        "[Decoder TX] UDP total len: %d, ip_total_len: %d",
                        udp_total_len,
                        ip_total_len,
                    )
                    rsh.update_ip_udp_len(buf, ip_hd_offset, udp_hd_offset,
                                          ip_total_len, udp_total_len)
                    struct.pack_into(">H", buf, udp_hd_offset + 6, 0)
                    rsh.update_cksum_ipv4(buf, ip_hd_offset, ip_hd_len)
                    sock.send(buf[:frame_len])
Пример #13
0
# g
symbols = 4

# k
symbol_size = 16

# finite field
field = kodo.field.binary8

# Create encoder
factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
encoder = factory.build()

# Create decoder
decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
decoder = decoder_factory.build()

# Define data in
data_in = bytearray(os.urandom(encoder.block_size()))
encoder.set_const_symbols(data_in)

# Define data out
data_out = bytearray(decoder.block_size())
decoder.set_mutable_symbols(data_out)

# Start Decoding-Encoding
packet_number = 0
while not decoder.is_complete():
    # Generate an encoded packet
    packet = encoder.write_payload()
def main():
    """
    Switch systematic off example.

    This example shows how to enable or disable systematic coding for
    coding stacks that support it.
    Systematic coding is used to reduce the amount of work done by an
    encoder and a decoder. This is achieved by initially sending all
    symbols which has not previously been sent uncoded. Kodo allows this
    feature to be optionally turn of or off.
    """
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 10
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size and assign it to the encoder.
    # This bytearray must not go out of scope while the encoder exists!
    data_in = bytearray(os.urandom(encoder.block_size()))
    encoder.set_const_symbols(data_in)

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    print("Starting encoding / decoding...")

    while not decoder.is_complete():

        # If the chosen codec stack supports systematic coding
        if 'is_systematic_on' in dir(encoder):

            # Toggle systematic mode with 50% probability
            if random.choice([True, False]):

                if encoder.is_systematic_on():
                    print("Turning systematic OFF")
                    encoder.set_systematic_off()
                else:
                    print("Turning systematic ON")
                    encoder.set_systematic_on()

        # Encode a packet into the payload buffer
        packet = encoder.write_payload()

        if random.choice([True, False]):
            print("Packet dropped.")
            continue

        # Pass that packet to the decoder
        decoder.read_payload(packet)

        print("Rank of decoder {}".format(decoder.rank()))

        # Symbols that were received in the systematic phase correspond
        # to the original source symbols and are therefore marked as
        # decoded
        print("Symbols decoded {}".format(decoder.symbols_uncoded()))

    # The decoder is complete, the decoded symbols are now available in
    # the data_out buffer: check if it matches the data_in buffer
    print("Checking results...")
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)
def simulation(data, symbols, symbol_size, redundancy, clouds, lost=0.0):

    if clouds <= lost:
        print('The amount of clouds lost must be less than the number of clouds')
        return

    cloud_locations = _make_clouds(clouds)

    field = kodo.field.binary8

    factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = factory.build()
    encoder.set_const_symbols(data)
    encoder.set_systematic_off()

    remainder = (symbols + redundancy) % clouds
    payloads_per_cloud = ((symbols + redundancy) - remainder) / clouds

    cloud = 0
    current_payload = 0
    for i in range(0, payloads_per_cloud * clouds):
        # print(cloud)
        payload = encoder.write_payload()
        cloud_locations[cloud].append(payload)
        current_payload += 1
        if current_payload == payloads_per_cloud:
            cloud += 1
            current_payload = 0

    cloud -= 1 # Adjust for last iterations
    if not remainder == 0:
        for i in range(0, remainder):
            payload = encoder.write_payload()
            cloud_locations[cloud].append(payload)

    lost = int(clouds * lost)
    for i in range(0, lost):
        cloud = _select_cloud(clouds, len(cloud_locations))
        del cloud_locations[cloud]

    factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = factory.build()

    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    clouds_accessed = 0
    number_of_payloads = 0
    for cloud in cloud_locations:
        clouds_accessed += 1
        for payload in cloud:
            number_of_payloads += 1
            decoder.read_payload(payload)
            if decoder.is_complete():
                break
        else:
            continue
        break

    #if decoder.is_complete():
    #    print('Decoding completed by accessing {!s} clouds and getting {!s} payloads'.format(clouds_accessed, number_of_payloads))
    #else:
    #    print('Decoding failed after accessing {!s} clouds and getting {!s} payloads'.format(clouds_accessed, number_of_payloads))

    if is_complete(data, data_out):
        #print('Decoding completed by accessing {!s} clouds and getting {!s} payloads'.format(clouds_accessed, number_of_payloads))
        return True
    else:
        #print('Decoding failed after accessing {!s} clouds and getting {!s} payloads'.format(clouds_accessed, number_of_payloads))
        return False
    write_bytearray_to_file('pika3.jpg', data_out)
Пример #16
0
def main():
    """
    Multicast example, reciever part.

    An example where data is received, decoded, and finally written to a file.
    """
    parser = argparse.ArgumentParser(description=main.__doc__)
    parser.add_argument('--output-file',
                        type=str,
                        help='Path to the file which should be received.',
                        default='output_file')

    parser.add_argument('--ip',
                        type=str,
                        help='The IP address to use.',
                        default=MCAST_GRP)

    parser.add_argument('--port',
                        type=int,
                        help='The port to use.',
                        default=MCAST_PORT)

    parser.add_argument('--dry-run',
                        action='store_true',
                        help='Run without network use.')

    args = parser.parse_args()

    field = kodo.field.binary
    symbols = 64
    symbol_size = 1400

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    sock = socket.socket(family=socket.AF_INET,
                         type=socket.SOCK_DGRAM,
                         proto=socket.IPPROTO_UDP)

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('', args.port))
    mreq = struct.pack("4sl", socket.inet_aton(args.ip), socket.INADDR_ANY)

    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    if args.dry_run:
        sys.exit(0)

    print("Processing...")
    while not decoder.is_complete():
        time.sleep(0.2)
        packet = sock.recv(10240)

        decoder.read_payload(bytearray(packet))
        print("Packet received!")
        print("Decoder rank: {}/{}".format(decoder.rank(), decoder.symbols()))

    # Write the decoded data to the output file
    f = open(args.output_file, 'wb')
    f.write(data_out)
    f.close()

    print("Processing finished.")
Пример #17
0
def main():
    """
    Encode on the fly example.

    This example shows how to use a storage aware encoder which will
    allow you to encode from a block before all symbols have been
    specified. This can be useful in cases where the symbols that
    should be encoded are produced on-the-fly.
    """
    # Choose the finite field, the number of symbols (i.e. generation size)
    # and the symbol size in bytes
    field = kodo.field.binary
    symbols = 10
    symbol_size = 160

    # Create an encoder/decoder factory that are used to build the
    # actual encoders/decoders
    encoder_factory = kodo.RLNCEncoderFactory(field, symbols, symbol_size)
    encoder = encoder_factory.build()

    decoder_factory = kodo.RLNCDecoderFactory(field, symbols, symbol_size)
    decoder = decoder_factory.build()

    # Generate some random data to encode. We create a bytearray of the same
    # size as the encoder's block size
    data_in = bytearray(os.urandom(encoder.block_size()))

    # Define the data_out bytearray where the symbols should be decoded
    # This bytearray must not go out of scope while the encoder exists!
    data_out = bytearray(decoder.block_size())
    decoder.set_mutable_symbols(data_out)

    # Let's split the data into symbols and feed the encoder one symbol at a
    # time
    symbol_storage = [
        data_in[i:i + symbol_size] for i in range(0, len(data_in), symbol_size)
    ]

    while not decoder.is_complete():

        # Randomly choose to insert a symbol
        if random.choice([True, False]) and encoder.rank() < symbols:
            # For an encoder the rank specifies the number of symbols
            # it has available for encoding
            rank = encoder.rank()
            encoder.set_const_symbol(rank, symbol_storage[rank])
            print("Symbol {} added to the encoder".format(rank))

        # Encode a packet into the payload buffer
        packet = encoder.write_payload()
        print("Packet encoded")

        # Send the data to the decoders, here we just for fun
        # simulate that we are loosing 50% of the packets
        if random.choice([True, False]):
            print("Packet dropped on channel")
            continue

        # Packet got through - pass that packet to the decoder
        decoder.read_payload(packet)
        print("Decoder received packet")
        print("Encoder rank = {}".format(encoder.rank()))
        print("Decoder rank = {}".format(decoder.rank()))
        uncoded_symbol_indces = []
        for i in range(decoder.symbols()):
            if decoder.is_symbol_uncoded(i):
                uncoded_symbol_indces.append(str(i))

        print("Decoder uncoded = {} ({}) symbols".format(
            decoder.symbols_uncoded(), " ".join(uncoded_symbol_indces)))
        print("Decoder partially decoded = {}".format(
            decoder.symbols_partially_decoded()))

    print("Coding finished")

    # The decoder is complete, the decoded symbols are now available in
    # the data_out buffer: check if it matches the data_in buffer
    print("Checking results...")
    if data_out == data_in:
        print("Data decoded correctly")
    else:
        print("Unexpected failure to decode please file a bug report :)")
        sys.exit(1)