1

I'd like to write a music DAW / synthesizer / drum machine with Kivy as the frontend.

Is there a way to do low-latency audio with Kivy?

(Ideally it would also compile and run on Android)

Aur Saraf
  • 3,214
  • 1
  • 26
  • 15

1 Answers1

1

I'm going to include my entire solution here, in case anybody needs to do low latency/realtime audio playback or input/recording with Kivy, either on Android or Windows/Linux/Mac, ever again:

Before you go down the path I chose, beware: I'm experiencing significant button click latency now, especially on Windows. This might be a showstopper for my project, and might be for yours too. Test your input latency before you start fighting with Android compilation of Cython-integrated C++ libraries!

Search my StackOverflow history of the past few days if you'd like to understand why certain funny lines exist in setup.py and the python-for-android recipe.

I ended up using miniaudio directly with Cython:

# engine.py
import cython
from midi import Message

cimport miniaudio
# this is my synth in another Cython file, you'll need to supply your own
from synthunit cimport RingBuffer, SynthUnit, int16_t, uint8_t

cdef class Miniaudio:
    cdef miniaudio.ma_device_config config
    cdef miniaudio.ma_device device

    def __init__(self, Synth synth):
        cdef void* p_data
        p_data = <void*>synth.get_synth_unit_address()
        self.config = miniaudio.ma_device_config_init(miniaudio.ma_device_type.playback);
        self.config.playback.format   = miniaudio.ma_format.s16
        self.config.playback.channels = 1
        self.config.sampleRate        = 0
        self.config.dataCallback      = cython.address(callback)
        self.config.pUserData         = p_data

        if miniaudio.ma_device_init(NULL, cython.address(self.config), cython.address(self.device)) != miniaudio.ma_result.MA_SUCCESS:
            raise RuntimeError("Error initializing miniaudio")

        SynthUnit.Init(self.device.sampleRate)

    def __enter__(self):
        miniaudio.ma_device_start(cython.address(self.device))

    def __exit__(self, type, value, tb):
        miniaudio.ma_device_uninit(cython.address(self.device))

cdef void callback(miniaudio.ma_device* p_device, void* p_output, const void* p_input, miniaudio.ma_uint32 frame_count) nogil:
    # this function must be realtime (never ever block), hence the `nogil`
    cdef SynthUnit* p_synth_unit
    p_synth_unit = <SynthUnit*>p_device[0].pUserData
    output = <int16_t*>p_output
    p_synth_unit[0].GetSamples(frame_count, output)
    # debug("row", 0)
    # debug("frame_count", frame_count)
    # debug("freq mHz", int(1000 * p_synth_unit[0].freq))

cdef class Synth:
    # wraps synth in an object that can be used from Python code, but can provice raw pointer
    cdef RingBuffer ring_buffer
    cdef SynthUnit* p_synth_unit

    def __cinit__(self):
        self.ring_buffer = RingBuffer()
        self.p_synth_unit = new SynthUnit(cython.address(self.ring_buffer))

    def __dealloc__(self):
        del self.p_synth_unit

    cdef SynthUnit* get_synth_unit_address(self):
        return self.p_synth_unit

    cpdef send_midi(self, midi):
        raw = b''.join(Message(midi, channel=1).bytes_content)
        self.ring_buffer.Write(raw, len(raw))

# can't do debug prints from a realtime function, but can write to a buffer:
cdef int d_index = 0
ctypedef long long addr
cdef addr[1024] d_data
cdef (char*)[1024] d_label

cdef void debug(char* label, addr x) nogil:
    global d_index
    if d_index < sizeof(d_data) * sizeof(d_data[0]):
        d_label[d_index] = label
        d_data[d_index] = x
        d_index += 1

def get_debug_data():
    result = []
    row = None
    for i in range(d_index):
        if d_label[i] == b"row":
            result.append(row)
            row = []
        else:
            row.append((d_label[i], d_data[i]))
    result.append(row)
    return result
# miniaudio.pxd
cdef extern from "miniaudio_define.h":
    pass # needed to do a #define that miniaudio.h expects, just put it in another C header

cdef extern from "miniaudio.h":
    ctypedef unsigned int ma_uint32
    cdef enum ma_result:
        MA_SUCCESS = 0
    cdef enum ma_device_type:
        playback "ma_device_type_playback" = 1
        capture "ma_device_type_capture"  = 2
        duplex "ma_device_type_duplex"   = playback | capture
        loopback "ma_device_type_loopback" = 4
    cdef enum ma_format:
        unknown "ma_format_unknown" = 0
        u8 "ma_format_u8"      = 1
        s16 "ma_format_s16"     = 2
        s24 "ma_format_s24"     = 3
        s32 "ma_format_s32"     = 4
        f32 "ma_format_f32"     = 5
    ctypedef struct ma_device_id:
        pass
    ctypedef struct ma_device_config_playback:
        const ma_device_id* pDeviceID
        ma_format format
        ma_uint32 channels
    ctypedef void (* ma_device_callback_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
    ctypedef struct ma_device_config:
        ma_uint32 sampleRate
        ma_uint32 periodSizeInMilliseconds
        ma_device_config_playback playback
        ma_device_callback_proc dataCallback
        void* pUserData
    ctypedef struct ma_device:
        ma_uint32 sampleRate
        void* pUserData
        ma_context* pContext
    ctypedef struct ma_context:
        pass
    ma_device_config ma_device_config_init(ma_device_type deviceType)
    ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
    ma_result ma_device_start(ma_device* pDevice)
    void ma_device_uninit(ma_device* pDevice)
// minidaudio_define.h
#define MA_NO_DECODING
#define MA_NO_ENCODING
#define MINIAUDIO_IMPLEMENTATION

and miniaudio.h from miniaudio needs to be in the same directory.

# setup.py
from setuptools import setup, Extension
from Cython.Build import cythonize

setup(
    name = 'engine',
    version = '0.1',
    ext_modules = cythonize([Extension("engine",
        ["engine.pyx"] + ['synth/' + p for p in [
            'synth_unit.cc', 'util.cc'
        ]],
        include_path = ['synth/'],
        language = 'c++',
    )])
)

Since pymidi crashes on Android because import serial doesn't work, and since I didn't yet know about writing python-for-android recipes and adding patches, I just added a serial.py that does nothing to my root directory:

"""
Override pySerial because it doesn't work on Android.

TODO: Use https://source.android.com/devices/audio/midi to implement MIDI support for Android
"""

Serial = lambda *args, **kwargs: None

and finally main.py (has to be called that for python-for-android to invoke it):

# main.py

class MyApp(App):
    # a Kivy app
    ...

if __name__ == '__main__':
    synth = engine.Synth()
    with engine.Miniaudio(synth):
        MyApp(synth).run()
        print('Goodbye')  # for some strange reason without this print the program sometimes hangs on close
        #data = engine.get_debug_data()
        #for x in data: print(x)

To build this on Windows, just pip install the directory with the setup.py.

To build this on Android, you'll need a Linux machine with pip install buildozer (I used Ubuntu in Windows Linux Subsystem 2 - wsl2, and made sure that I had a git checkout of the sources in a linux directory because there is a LOT of compilation involved and IO of Windows directories from WSL is very slow).

# python-for-android/recipes/engine/__init__.py
from pythonforandroid.recipe import IncludedFilesBehaviour, CppCompiledComponentsPythonRecipe
import os
import sys

class SynthRecipe(IncludedFilesBehaviour, CppCompiledComponentsPythonRecipe):
    version = 'stable'
    src_filename = "../../../engine"
    name = 'engine'

    depends = ['setuptools']

    call_hostpython_via_targetpython = False
    install_in_hostpython = True

    def get_recipe_env(self, arch):
        env = super().get_recipe_env(arch)
        env['LDFLAGS'] += ' -lc++_shared'
        return env



recipe = SynthRecipe()
$ buildozer init
# in buildozer.spec change:

requirements = python3,kivy,cython,py-midi,phase-engine
# ...
p4a.local_recipes = ./python-for-android/recipes/
$ buildozer android debug

Now you can either copy bin/yourapp.apk to a Windows directory and run adb install yourapp.apk from CMD, or follow my instructions here so buildozer android debug deploy run just works: Running React Native in WSL with the emulator running directly in Windows

Aur Saraf
  • 3,214
  • 1
  • 26
  • 15