Пример #1
0
    def __init__(self,
                 jack_client,
                 buffer_minutes,
                 channels,
                 dump_path='/tmp/muser/tmp'):
        self.jack_client = jack_client
        self.buffer_seconds = 60.0 * buffer_minutes
        self.channels = channels
        self.blocks = int(self.buffer_seconds / jack_client.blocktime)
        self.buffer_format = self.BUFFER_FORMAT.format(jack_client.blocksize)
        self.buffer_bytes = struct.calcsize(self.buffer_format)
        self.block_format = channels * self.buffer_format
        self.block_bytes = struct.calcsize(self.block_format)

        self.ringbuffer = jack.RingBuffer(self.blocks * self.block_bytes)
        self._active = False

        self.tmp_dir = dump_path
        dump_name_format = '{}-dump{{}}'.format(id(self))
        self.tmp_filepath = os.path.join(dump_path, dump_name_format)
        os.makedirs(self.tmp_dir, exist_ok=True)
        self.ringbuffer_dumper = utils.FileDumper(
            path=dump_path,
            name_format="{}-dump{{}}".format(id(self)),
        )
Пример #2
0
 def __init__(self,
              id,
              samplerate=48000,
              buffer_jack_size=3,
              database_path=None):
     self.samplerate = samplerate
     self.buffer_jack_size = buffer_jack_size
     self.ring_buffer = jack.RingBuffer(samplerate * buffer_jack_size)
     self.id = id
     self.portname = None
     self.file = None
     self.database_path = database_path + "/unchecked"
     self.filename = self.database_path
Пример #3
0
def init_buffers() -> None:
    global transfer_buffer1, transfer_buffer2
    transfer_buffer1 = Jack.RingBuffer(jack.samplerate * 10)
    transfer_buffer2 = Jack.RingBuffer(jack.samplerate * 10)
Пример #4
0
def _timeit_roll():
    _TIMEIT_REPEAT = 5
    _TIMEIT_NUMBER = 100

    _BLOCK_LENGTH = 4096
    _CHANNEL_COUNT = 50
    _BLOCK_COUNT = 10

    input_td = tools.generate_noise((_CHANNEL_COUNT, _BLOCK_LENGTH))
    buffer_ref = tools.generate_noise(
        (_BLOCK_COUNT, _CHANNEL_COUNT, _BLOCK_LENGTH))

    buffer = buffer_ref.copy()
    s = """\
buffer = globals().get("buffer")  # I don't know why this is necessary...
buffer = np.roll(buffer, 1, axis=0)  # roll buffer to the right
buffer[0] = input_td  # update the first element
result = buffer
"""
    ref = _timeit(
        description="numpy roll",
        stmt=s,
        setup="import numpy as np",
        _globals=locals(),
        repeat=_TIMEIT_REPEAT,
        number=_TIMEIT_NUMBER,
    )

    buffer = buffer_ref.copy()
    s = """\
buffer = globals().get("buffer")  # I don't know why this is necessary...
buffer[1:] = buffer[:-1]  # roll buffer to the right
buffer[0] = input_td  # update the first element
result = buffer
"""
    _timeit(
        description="slice indexing",
        stmt=s,
        setup="import numpy as np",
        _globals=locals(),
        repeat=_TIMEIT_REPEAT,
        number=_TIMEIT_NUMBER,
        reference=ref,
    )  # slower

    import jack

    rb = jack.RingBuffer(buffer_ref.nbytes)
    s = """\
bytes_written = rb.write(input_td.tobytes())
if bytes_written != input_td.nbytes:
    print("OVERFLOW")
read = np.frombuffer(rb.read(input_td.nbytes), dtype=input_td.dtype).reshape(
    input_td.shape
)
if read.nbytes != input_td.nbytes:
    print("UNDERFLOW")
result = read
"""
    # this is not expected to deliver the same result as the roll methods above
    _timeit(
        description="Ringbuffer",
        stmt=s,
        setup="import numpy as np",
        _globals=locals(),
        repeat=_TIMEIT_REPEAT,
        number=_TIMEIT_NUMBER,
        reference=ref,
    )

    rb = jack.RingBuffer(buffer_ref.nbytes)
    s = """\
if rb.write_space >= input_td.nbytes:
    rb.write_buffers[0][: input_td.nbytes] = input_td.tobytes()
    rb.write_advance(input_td.nbytes)
else:
    print("OVERFLOW")
read = np.frombuffer(
    rb.read_buffers[0][: input_td.nbytes], dtype=input_td.dtype
).reshape(input_td.shape)
rb.read_advance(read.nbytes)
if read.nbytes != input_td.nbytes:
    print("UNDERFLOW")
result = read
"""
    # this code does not run so far, I don't know how it is supposed to be done with
    # write_buffers() and read_buffers() independent of that I don't know why the timeit() code
    # does not run like that this is not expected to deliver the same result as the roll methods
    # above
    _timeit(
        description="Ringbuffer no copy",
        stmt=s,
        setup="import numpy as np",
        _globals=locals(),
        repeat=_TIMEIT_REPEAT,
        number=_TIMEIT_NUMBER,
        reference=ref,
    )
Пример #5
0
client = jack.Client("audio2DMX512")
client.blocksize = 128  # устанавливает буффер сервера
in_port = client.inports.register("input", is_terminal=True)
# client.get_ports()


@client.set_shutdown_callback
def shutdown(status, reason):
    print('JACK shutdown!')
    print('status:', status)
    print('reason:', reason)
    event.set()


ring_buffer = jack.RingBuffer(2048)


@client.set_process_callback
def process(frames):
    # assert frames == client.blocksize
    try:
        # ring_buffer.write_buffers[0][0:128] = in_port.get_array()  # отдаёт 128 - то что настроено в сервере
        ring_buffer.write_buffers[0][0:512] = in_port.get_buffer()[
            0:512]  # работает!!!
    except (IndexError, ValueError):
        pass
    finally:
        ring_buffer.write_advance(512)

Пример #6
0
client.blocksize = 128  # устанавливает буффер сервера
in_port = client.inports.register("input", is_terminal=True)
# client.get_ports()


# jack.OwnPort
# jack.Ports

@client.set_shutdown_callback
def shutdown(status, reason):
    print('JACK shutdown!')
    print('status:', status)
    print('reason:', reason)
    event.set()

ring_buffer = jack.RingBuffer(1024)


@client.set_process_callback
def process(frames):
    # assert frames == client.blocksize
    try:
        # print(len(in_port.get_buffer())) # отдает 512
        # ring_buffer.write_buffers[0][0:128] = in_port.get_array()  # отдаёт 128 - то что настроено в сервере
        ring_buffer.write_buffers[0][0:512] = in_port.get_buffer()[0:512]  # работает!!!
    except (IndexError, ValueError):
        # print('pass')
        pass
    finally:
        # print('read_space', ring_buffer.read_space)
        ring_buffer.write_advance(512)
Пример #7
0
 def __init__(self, size):
     self.ringbuffer = jack.RingBuffer(size)
Пример #8
0
    def load_stream(self):
        try:
             # Wait that all jack ports are properly disconnected
            App.log(1, "Reset the Jack client.")
            self.client.inports.clear()
            self.client.outports.clear()
            time.sleep(1)

            self.client.deactivate()
            self.client.close()
            #
            self.init_client()
            self.mustReload = False

            App.log(1, "Stream initialization tentative.")

            # Clean all connections and buffers
            self.ports          = []
            self.channels       = []
            self.ring_buffer    = []
            self.channels_data  = []
            self.mapping        = []
            self.channels_state = {}
            self.client.inports.clear()

            App.log(1, "List of automatic port connections:")
            App.log(1, self.jack_ports_toload)

            # Load the port patterns to connect
            for port in self.jack_ports_toload:
                self.ports = self.ports + self.client.get_ports(port, is_output=True)
            sorted_nicely(self.ports)

            # Register TidZam inputs for each MPV ports
            for i in range(0, len(self.ports)):
                self.channels.append(self.client.inports.register("input_"+str(i)))
                self.ring_buffer.append(jack.RingBuffer(self.buffer_jack))

            # Activate TidZam ports and connecto MPV
            App.log(1, "Tidzam client activation: " +str(len(self.ports))+" ports")
            self.client.activate()

            for i in range(0, len(self.ports)):
                # Connect Tidzam
                if "input" not in self.ports[i].name:
                    App.log(2, "Connection " + self.ports[i].name + " -> " + self.channels[i].name)
                    self.client.connect(self.ports[i], self.channels[i])

                    # Store the stream mapping
                    self.mapping.append([self.ports[i].name, self.channels[i].name])

                    # If there is no starting time defined for this stream, we create one
                    tmp = self.ports[i].name.split(":")[0]
                    found = False
                    for source in self.sources:
                        if source["name"] in tmp:
                            found = True
                    if found is False:
                        self.sources.append({"name":tmp,"starting_time":time.strftime("%Y-%m-%d-%H-%M-%S")})

            App.log(2, "Audio stream mapping: ")
            App.log(2, self.mapping)

            # Wait that all jack ports are connected
            time.sleep(0)

        except Exception as e:
            App.error(0, "Loading stream exception: " + str(e))