mod_audio_stream

repository·main·Indexed 42 days ago

https://github.com/amigniter/mod_audio_stream

A high-performance FreeSWITCH module for real-time, bi-directional WebSocket audio streaming. It supports uni-directional streaming for ASR and analytics, as well as full-duplex audio (v1.1.0+) with automatic resampling. Features include support for base64-encoded and raw binary audio in PCMU, PCMA, L16/RAW, or Opus formats, and integration with uuid_record for unified recording.

Tokens
2.5K
Snippets
6
Records
11
Agent score
4%

What's inside mod_audio_stream

  1. Overview of mod_audio_stream

    main

    mod_audio_stream is a production-grade WebSocket audio streaming module for FreeSWITCH. It enables real-time audio streaming between FreeSWITCH and external systems using an RFC-6455 compliant WebSocket client (libwsc).

    Key Capabilities:

    • Uni-directional streaming: Suitable for ASR, transcription, and analytics.
    • Bi-directional streaming (v1.1.0+): Provides full-duplex audio (caller to WebSocket and vice-versa) with automatic resampling and dynamic playback control.
    • Audio Formats: Supports base64-encoded and raw binary audio. Returned audio can be in PCMU, PCMA, L16/RAW, or Opus formats.
    • Unified Recording: Supports uuid_record to capture both caller audio and returned WebSocket audio in a single recording.

    Licensing Note:

    • The pre-built release is free for use (including commercial) but is limited to 10 concurrent streaming channels.
    • For unlimited channels or source-code licensing, contact amsoftswitch@gmail.com.
  2. Implement Audio Playback from WebSocket

    main

    The module supports receiving audio from the WebSocket server to be played back to the user. The server must return a JSON object in the following format:

    {
      "type": "streamAudio",
      "data": {
        "audioDataType": "raw",
        "sampleRate": 8000,
        "audioData": "base64 encoded audio"
      }
    }

    When the mod_audio_stream::play event is generated, the module converts the base64 data into a temporary file. The event body will contain the audioDataType, sampleRate, and a file key pointing to the path of the temporary file:

    {
      "audioDataType": "raw",
      "sampleRate": 8000,
      "file": "/tmp/some_temp_file"
    }

    Note: All files generated for playback reside in a temporary directory and are deleted when the session is closed. The audioDataType can be raw, wav, mp3, or ogg.

    {
      "type": "streamAudio",
      "data": {
        "audioDataType": "raw",
        "sampleRate": 8000,
        "audioData": "SGVsbG8gd29ybGQ=
      }
    }
  3. Scripted Build & Installation

    main

    You can automate the build and installation process of mod_audio_stream using the provided shell script. This requires git and sudo privileges.

    Run the following command to clone the repository and execute the build script:

    sudo apt-get -y install git \
        && cd /usr/src/ \
        && git clone https://github.com/amigniter/mod_audio_stream.git \
        && cd mod_audio_stream \
        && sudo bash ./build-mod-audio-stream.sh
  4. Build mod_audio_stream from source

    main

    To build the module from source, ensure you have initialized the submodules first. If you are using a custom FreeSWITCH installation path (e.g., /usr/local/freeswitch), you must update your PKG_CONFIG_PATH so CMake can locate FreeSWITCH headers and libraries.

    Steps:

    1. Initialize submodules.
    2. (Optional) Set PKG_CONFIG_PATH for custom FreeSWITCH installs.
    3. Create a build directory and run CMake.
    4. Compile and install.

    Note on TLS: TLS support is OFF by default. Enable it by passing -DUSE_TLS=ON to the CMake command.

    # Initialize submodules
    git submodule init
    git submodule update
    
    # If FreeSWITCH is in a custom path
    export PKG_CONFIG_PATH=/usr/local/freeswitch/lib/pkgconfig
    
    # Build and install
    mkdir build && cd build
    cmake -DCMAKE_BUILD_TYPE=Release ..
    make
    sudo make install
  5. Configure mod_audio_stream via Channel Variables

    main

    Use the following channel variables to fine-tune WebSocket connections, audio buffering, and logging behavior:

    VariableDescriptionDefault
    STREAM_MESSAGE_DEFLATESet to true or 1 to disable per-message deflate compression.off
    STREAM_HEART_BEATInterval in seconds to send a heartbeat to prevent idle connection timeouts.off
    STREAM_SUPPRESS_LOGSet to true or 1 to suppress printing WebSocket responses to the log.off
    STREAM_BUFFER_SIZEAudio chunk duration in milliseconds (must be divisible by 20). Default is 20ms.20
    STREAM_EXTRA_HEADERSA JSON string representing additional HTTP headers.none
    STREAM_TLS_CA_FILECA cert/bundle. Use SYSTEM for defaults or NONE for no peer verification.SYSTEM
    STREAM_TLS_KEY_FILEOptional client key for WSS connections.none
    STREAM_TLS_CERT_FILEOptional client certificate for WSS connections.none
    STREAM_TLS_DISABLE_HOSTNAME_VALIDATIONSet to true or 1 to disable hostname checks in WSS.false

    Additional Details

    Extra Headers

    STREAM_EXTRA_HEADERS must be a JSON object where keys are header names and values are strings:

    {
        "Header1": "Value1",
        "Header2": "Value2"
    }

    TLS (WSS) Configuration

    • Use STREAM_TLS_CA_FILE to specify a CA certificate or bundle.
    • Use STREAM_TLS_CERT_FILE and STREAM_TLS_KEY_FILE for client-side certificate authentication.
    • Use STREAM_TLS_DISABLE_HOSTNAME_VALIDATION to bypass hostname verification.
  6. Install mod_audio_stream on Debian Bookworm

    main

    To install mod_audio_stream on a Debian Bookworm system, add the Amigniter repository to your APT sources and install the package via apt-get. This process involves downloading the GPG keyring for repository verification, creating a new source list file, updating your package index, and finally installing the module.

    Follow these steps in order:

    # 1. Download the GPG keyring
    wget -O /usr/share/keyrings/mod-audio-stream.gpg https://amigniter.github.io/mod-audio-stream/mod-audio-stream.gpg
    
    # 2. Add the repository to your sources list
    echo "deb [signed-by=/usr/share/keyrings/mod-audio-stream.gpg] https://amigniter.github.io/mod-audio-stream bookworm main" > /etc/apt/sources.list.d/mod-audio-stream.list
    
    # 3. Update the package index
    apt-get update
    
    # 4. Install the module
    apt-get install mod-audio-stream
  7. Use mod_audio_stream API commands

    main

    The module exposes several FreeSWITCH commands to control the audio stream via the channel UUID.

    Start Audio Stream

    uuid_audio_stream <uuid> start <wss-url> <mix-type> <sampling-rate> <metadata> Attaches a media bug and streams audio in L16 format to the specified WebSocket URL.

    • <uuid>: FreeSWITCH channel unique ID.
    • <wss-url>: The WebSocket URL (ws:// or wss://).
    • <mix-type>:
      • mono: Single channel with caller's audio.
      • mixed: Single channel with both caller and callee audio.
      • stereo: Two channels (caller in one, callee in the other).
    • <sampling-rate>:
      • 8k: 8000 Hz.
      • 16k: 16000 Hz (will be resampled if necessary).
    • <metadata>: (Optional) UTF-8 text sent before audio starts.

    Send Text

    uuid_audio_stream <uuid> send_text <metadata> Sends a UTF-8 text message to the WebSocket server.

    Stop Stream

    uuid_audio_stream <uuid> stop <metadata> Stops the audio stream and closes the connection. If <metadata> is provided, it is sent before closing.

    Pause/Resume Stream

    • uuid_audio_stream <uuid> pause: Pauses the audio stream.
    • uuid_audio_stream <uuid> resume: Resumes the audio stream.
    uuid_audio_stream <uuid> start wss://example.com/stream mixed 16k {"user_id": "123"}
  8. Handle mod_audio_stream Events

    main

    The module generates several FreeSWITCH events based on the WebSocket connection state and server responses.

    Connection Events

    • mod_audio_stream::connect: Triggered when successfully connected. Body: {"status": "connected"}.
    • mod_audio_stream::disconnect: Triggered when disconnected. Body includes a status and a message object containing a code (int) and reason (string).
    • mod_audio_stream::error: Triggered on connection errors. Body includes a status, message.code (int), and message.error (string).

    Data Events

    • mod_audio_stream::json: Triggered when a message is received from the WebSocket endpoint. The body contains the raw server response.
    • mod_audio_stream::play: Triggered when the WebSocket server returns audio to be played by the user.

    Error Codes

    CodeNameMeaning
    1IOI/O error during socket read/write
    2INVALID_HEADERMalformed WebSocket header
    3SERVER_MASKEDServer frames were masked (not allowed)
    4NOT_SUPPORTEDRequested feature not supported
    5PING_TIMEOUTNo PONG received within timeout
    6CONNECT_FAILEDTCP connection or DNS lookup failed
    7TLS_INIT_FAILEDFailed to initialize SSL/TLS context
    8SSL_HANDSHAKE_FAILEDSSL/TLS handshake failed
    9SSL_ERRORGeneric OpenSSL error
    10TIMEOUTTimeout
    11PROTOCOLWebSocket protocol error