> ## Documentation Index
> Fetch the complete documentation index at: https://humain.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# C library reference

> Complete kiosk.h API reference — configuration, session lifecycle, streaming, error codes, memory model, and thread safety.

The `kiosk-c` library is a C99 client for the Humain Kiosk Device API. It requires
**libcurl >= 7.68.0** and provides both blocking and streaming message APIs.

Source and prebuilt binaries: [github.com/humain/kiosk-c](https://github.com/humain/kiosk-c)

***

## Build and install

```bash theme={null}
git clone https://github.com/humain/kiosk-c.git
cd kiosk-c

# Text sessions only
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build

# Text + voice (WebRTC)
cmake -B build -DCMAKE_BUILD_TYPE=Release \
  -DKIOSK_WITH_VOICE=ON
cmake --build build

# Text + voice + built-in ALSA helper
cmake -B build -DCMAKE_BUILD_TYPE=Release \
  -DKIOSK_WITH_VOICE=ON \
  -DKIOSK_WITH_ALSA=ON
cmake --build build

sudo cmake --install build
```

> [accordion] Dependencies
>
> ```text theme={null}
> Text sessions: libcurl >= 7.68.0, OpenSSL or mbedTLS
>
> Voice sessions (-DKIOSK_WITH_VOICE=ON):
>   + libdatachannel >= 0.18
>   + libopus >= 1.3
>   + libsrtp2 >= 2.4 (transitive — installed by libdatachannel)
>
> ALSA helper (-DKIOSK_WITH_ALSA=ON):
>   + libasound >= 1.2
> ```

Link your application against `libkiosk` and `libcurl`:

```bash theme={null}
gcc my_app.c -lkiosk -lcurl -o my_app
```

Or in CMake:

```cmake theme={null}
find_package(kiosk REQUIRED)
target_link_libraries(my_target PRIVATE kiosk::kiosk)
```

***

## Minimal complete example

```c theme={null}
#include <stdio.h>
#include <stdlib.h>
#include "kiosk.h"

int main(void) {
    const char *credential = getenv("HUMAIN_CREDENTIAL");
    if (!credential) {
        fprintf(stderr, "HUMAIN_CREDENTIAL not set\n");
        return 1;
    }

    kiosk_config_t cfg = {0};
    cfg.credential = credential;

    kiosk_client_t *client = kiosk_client_create(&cfg);
    if (!client) {
        fprintf(stderr, "Failed to create client\n");
        return 1;
    }

    kiosk_session_t *session = NULL;
    kiosk_error_t err = kiosk_session_open(client, KIOSK_SESSION_TEXT, &session);
    if (err != KIOSK_OK) {
        fprintf(stderr, "open: %s\n", kiosk_error_string(err));
        kiosk_client_destroy(client);
        return 1;
    }

    char response[4096];
    size_t response_len = 0;
    err = kiosk_session_message(session, "Hello!", response, sizeof(response), &response_len);
    if (err == KIOSK_OK) {
        printf("AI: %.*s\n", (int)response_len, response);
    } else {
        fprintf(stderr, "message: %s\n", kiosk_error_string(err));
    }

    kiosk_session_close(session);
    kiosk_client_destroy(client);
    return (err == KIOSK_OK) ? 0 : 1;
}
```

***

## Streaming example

```c theme={null}
#include <stdio.h>
#include "kiosk.h"

static int on_chunk(const char *chunk, size_t chunk_len, void *userdata) {
    (void)userdata;
    fwrite(chunk, 1, chunk_len, stdout);
    fflush(stdout);
    return 0; /* return non-zero to cancel the stream early */
}

int main(void) {
    kiosk_config_t cfg = { .credential = getenv("HUMAIN_CREDENTIAL") };
    kiosk_client_t *client = kiosk_client_create(&cfg);

    kiosk_session_t *session = NULL;
    kiosk_session_open(client, KIOSK_SESSION_TEXT, &session);

    kiosk_session_stream(session, "Tell me about our opening hours.", on_chunk, NULL);
    printf("\n");

    kiosk_session_close(session);
    kiosk_client_destroy(client);
    return 0;
}
```

***

## Error handling

```c theme={null}
kiosk_error_t err = kiosk_session_message(session, input, buf, sizeof(buf), &len);
switch (err) {
    case KIOSK_OK:
        /* success */
        break;
    case KIOSK_ERR_RATE_LIMITED: {
        int wait_secs = kiosk_retry_after(session);
        fprintf(stderr, "Rate limited — retry after %d seconds\n", wait_secs);
        sleep((unsigned)wait_secs);
        /* retry ... */
        break;
    }
    case KIOSK_ERR_SESSION_ENDED:
        /* session expired — open a new one */
        kiosk_session_close(session);
        kiosk_session_open(client, KIOSK_SESSION_TEXT, &session);
        break;
    case KIOSK_ERR_PROVIDER:
        fprintf(stderr, "Provider temporarily unavailable: %s\n", kiosk_error_string(err));
        sleep(2); /* brief back-off before retry */
        break;
    case KIOSK_ERR_NETWORK:
    case KIOSK_ERR_TIMEOUT:
        fprintf(stderr, "Transient error: %s — retrying\n", kiosk_error_string(err));
        break;
    default:
        fprintf(stderr, "Fatal error: %s\n", kiosk_error_string(err));
        break;
}
```

***

## `kiosk_config_t` fields

**credential** `const char *` *required*

Device API credential in the form `hk_live_XXXXXXXXXXXXXXXXXX` (production) or
`hk_test_XXXXXXXXXXXXXXXXXX` (sandbox — see [Sandbox mode](https://humain.mintlify.site/concepts/sandbox-mode.md)). Read
from an environment variable — never hard-code in source files.

```c theme={null}
cfg.credential = getenv("HUMAIN_CREDENTIAL");
```

**base\_url** `const char *` (default: [https://api.humain.ai](https://api.humain.ai))

Override the API base URL. There is no separate sandbox host — sandbox behavior comes from
using an `hk_test_` credential against this same URL. Leave as `NULL` unless you're pointing
at a self-hosted deployment.

**timeout\_ms** `int` (default: 30000)

HTTP request timeout in milliseconds. Set to `0` to use the default (30 000 ms).
Streaming requests use this timeout per chunk, not for the entire stream.

**max\_retries** `int` (default: 3)

Maximum number of automatic retries for `KIOSK_ERR_NETWORK` and `KIOSK_ERR_TIMEOUT` errors.
Retries use exponential back-off with jitter capped at 30 seconds. Set to `0` to disable
automatic retries.

**sandbox** `int` (default: 0)

When non-zero, routes all requests to the sandbox endpoint regardless of `base_url`. Sandbox
responses are instant and consume no AI credits.

***

## Error codes

| Code | Value | Trigger | Retry strategy |
| - | - | - | - |
| `KIOSK_OK` | 0 | Success | — |
| `KIOSK_ERR_INVALID_ARG` | 1 | A required argument was NULL or invalid | Fix caller code — do not retry |
| `KIOSK_ERR_NETWORK` | 2 | DNS, TCP, or TLS failure | Exponential back-off (1 s, 2 s, 4 s) |
| `KIOSK_ERR_AUTH` | 3 | Credential missing, malformed, or revoked (HTTP 401) | Fix credential — do not retry |
| `KIOSK_ERR_INACTIVE` | 4 | Kiosk is disabled in the admin panel (HTTP 403) | Activate kiosk — do not retry |
| `KIOSK_ERR_BLOCKED` | 5 | Credential blocked by FraudGuard (HTTP 403) | Wait `blocked_until` — do not retry |
| `KIOSK_ERR_RATE_LIMITED` | 6 | Rate limit exceeded — call `kiosk_retry_after()` (HTTP 429) | Retry after `kiosk_retry_after()` seconds |
| `KIOSK_ERR_REJECTED` | 7 | Message rejected by content policy (HTTP 400) | Do not retry — show neutral message |
| `KIOSK_ERR_SESSION_ENDED` | 8 | Session already closed (HTTP 400) | Open a new session |
| `KIOSK_ERR_PROVIDER` | 9 | Upstream AI provider error (HTTP 503) | Exponential back-off (1 s, 2 s, 4 s) |
| `KIOSK_ERR_PLAN_LIMIT` | 10 | Workspace plan limit reached (HTTP 402) | Upgrade plan — do not retry |
| `KIOSK_ERR_INTERNAL` | 11 | Unexpected server error (HTTP 500) | Exponential back-off; contact support if persistent |
| `KIOSK_ERR_TIMEOUT` | 12 | Request or connection timed out | Retry immediately once, then back-off |
| `KIOSK_ERR_OUT_OF_MEMORY` | 13 | Memory allocation failed | Increase heap or reduce buffer size |

***

## Voice sessions

> [!NOTE]
>
> Voice session functions are only available when built with `-DKIOSK_WITH_VOICE=ON`.
> They are not available on FreeRTOS or Zephyr targets.

## `kiosk_voice_config_t` fields

**capture\_fn** `kiosk_audio_capture_fn` *required*

Audio capture callback. Called from the library's internal audio thread at `frame_ms`
intervals. Fill the provided buffer with 16-bit signed PCM (16 kHz, mono) and return
the number of frames written.

**Must be real-time safe** — no heap allocation, no blocking mutex calls, no stdio.
Any violation causes audio glitches and WebRTC packet loss.

**playback\_fn** `kiosk_audio_playback_fn` *required*

Audio playback callback. Called with synthesised speech PCM received from the AI.
Write the provided samples to your speaker hardware.

**vad\_fn** `kiosk_vad_fn` (default: NULL)

Voice activity detection callback. Called with `speaking = 1` on speech onset and
`speaking = 0` on silence detection. Use for UI feedback — for example, showing a
"listening" indicator. Pass `NULL` to disable.

**event\_fn** `kiosk_voice_event_fn` (default: NULL)

Lifecycle event callback. Called on transitions between `KIOSK_VOICE_CONNECTING`,
`KIOSK_VOICE_LISTENING`, `KIOSK_VOICE_PROCESSING`, `KIOSK_VOICE_SPEAKING`, and
`KIOSK_VOICE_ENDED`. Pass `NULL` to disable.

**userdata** `void *` (default: NULL)

Opaque pointer passed unchanged to all four callbacks.

**sample\_rate** `int` (default: 16000)

Audio sample rate in Hz. Must match your audio hardware. Gemini Live performs best
at 16 000 Hz or 48 000 Hz.

**frame\_ms** `int` (default: 20)

Capture frame duration in milliseconds. Determines how often `capture_fn` is invoked.
20 ms is the standard WebRTC frame size.

### ALSA example

Complete voice session using the built-in ALSA helper (`-DKIOSK_WITH_ALSA=ON`):

```c theme={null}
#include <signal.h>
#include <stdio.h>
#include "kiosk.h"

static volatile int running = 1;
static void on_sigint(int s) { (void)s; running = 0; }

static void on_event(kiosk_voice_event_t ev, void *ud) {
    (void)ud;
    const char *names[] = {
        "connecting", "listening", "processing", "speaking", "ended"
    };
    printf("[voice] %s\n", names[ev]);
}

int main(void) {
    signal(SIGINT, on_sigint);

    kiosk_config_t cfg = {
        .credential = "hk_live_your_credential_here",
        .timeout_ms = 30000,
    };
    kiosk_client_t *client = kiosk_client_create(&cfg);
    if (!client) { fprintf(stderr, "out of memory\n"); return 1; }

    /* Set up ALSA capture and playback */
    kiosk_alsa_config_t alsa_cfg = {
        .capture_device  = "hw:1,0",
        .playback_device = "default",
        .sample_rate     = 16000,
    };
    kiosk_audio_capture_fn  cap_fn;
    kiosk_audio_playback_fn play_fn;
    void                   *alsa_ctx = NULL;
    kiosk_error_t err = kiosk_alsa_create(&alsa_cfg, &cap_fn, &play_fn, &alsa_ctx);
    if (err != KIOSK_OK) {
        fprintf(stderr, "ALSA init failed: %s\n", kiosk_error_string(err));
        kiosk_client_destroy(client);
        return 1;
    }

    /* Open and start voice session */
    kiosk_voice_config_t vcfg = {
        .capture_fn  = cap_fn,
        .playback_fn = play_fn,
        .event_fn    = on_event,
        .userdata    = alsa_ctx,
    };
    kiosk_voice_session_t *session = NULL;
    err = kiosk_voice_session_open(client, &vcfg, &session);
    if (err != KIOSK_OK) {
        fprintf(stderr, "voice session failed: %s\n", kiosk_error_string(err));
        goto cleanup;
    }
    kiosk_voice_session_start(session);
    printf("Voice session active. Press Ctrl+C to stop.\n");
    while (running) pause();
    kiosk_voice_session_stop(session);

cleanup:
    kiosk_alsa_destroy(alsa_ctx);
    kiosk_client_destroy(client);
    return err == KIOSK_OK ? 0 : 1;
}
```

### Custom audio hardware

For teams not using ALSA — implement `capture_fn` and `playback_fn` directly for your
platform's audio driver:

```c theme={null}
static int my_capture(int16_t *buf, size_t buf_len, int frames, void *ud) {
    (void)ud;
    /*
     * Read `frames` frames from your audio hardware into `buf`.
     * Must return within frame_ms (default 20 ms) — runs on a real-time thread.
     * No malloc, no mutex, no I/O other than audio.
     *
     * Example: read from a custom I2S driver
     */
    return my_i2s_read(buf, frames);   /* platform-specific */
}

static void my_playback(const int16_t *buf, int frames, void *ud) {
    (void)ud;
    /* Write `frames` frames to your speaker hardware */
    my_i2s_write(buf, frames);         /* platform-specific */
}

kiosk_voice_config_t vcfg = {
    .capture_fn  = my_capture,
    .playback_fn = my_playback,
    .userdata    = NULL,
};
```

> [accordion] Audio thread requirements
>
> The capture callback runs on an internal real-time audio thread. It must complete
> within `frame_ms` (default 20 ms). Violations cause audio glitches and WebRTC packet
> loss.
>
> **Requirements:**
>
> * No dynamic memory allocation (`malloc`, `free`, `new`)
> * No blocking mutex calls
> * No stdio (`printf`, `fwrite`)
>
> **For I2S hardware:** use DMA-backed ring buffers. Copy from the DMA ring buffer into
> the library's provided `buf` — the copy should take under 1 ms.
>
> **For USB audio:** use ALSA's `snd_pcm_readi` with a pre-allocated buffer. Set the
> capture thread to `SCHED_FIFO` priority to avoid scheduler jitter.

> [accordion] ICE and NAT traversal
>
> The library uses STUN to discover the device's public address. The default STUN server
> is Google's public STUN (`stun.l.google.com:19302`).
>
> No TURN server is required in most network configurations — the Humain Kiosk platform
> handles the server-side connectivity. If the device is behind a symmetric NAT, contact
> [support@humain.ai](mailto:support@humain.ai) to enable TURN relay credentials for
> your workspace.

***

## Memory model

> [accordion] Memory model
>
> **Client and session handles** — the library allocates these internally.
> `kiosk_client_destroy()` frees the client; `kiosk_session_close()` frees the session.
> Never free these pointers yourself.
>
> **Response buffers** — for `kiosk_session_message()`, the caller provides a stack- or
> heap-allocated buffer. The library writes the NUL-terminated response into it and never
> allocates additional memory for the response. If the response does not fit,
> `KIOSK_ERR_OUT_OF_MEMORY` is returned and the buffer contains a partial response.
>
> **Recommended buffer sizes:**
>
> | Use case | Minimum | Recommended |
> | - | - | - |
> | Short Q\&A responses | 1 KB | 4 KB |
> | Detailed product descriptions | 4 KB | 16 KB |
> | Long-form content | 16 KB | 64 KB |
>
> **Streaming** — `kiosk_session_stream()` allocates only a small internal CURL write buffer.
> The `chunk` pointer passed to your callback is valid only for the duration of that callback
> invocation; copy it if you need to retain the data.
>
> **`kiosk_config_t`** — the struct is copied by `kiosk_client_create()`. You may free or
> reuse the config struct immediately after that call returns. The `credential` and `base_url`
> strings are copied — you do not need to keep them alive.

## Thread safety

> [accordion] Thread safety
>
> | Object | Thread safety |
> | - | - |
> | `kiosk_client_t` | Safe to call `kiosk_session_open()` concurrently from multiple threads |
> | `kiosk_session_t` | **Not thread-safe** — one session must be used from one thread at a time |
> | `kiosk_session_stream()` | Blocks the calling thread. Call from a dedicated thread if needed |
> | `kiosk_error_string()` | Thread-safe — returns a pointer to a static string |
> | `kiosk_version()` | Thread-safe — returns a pointer to a static string |
>
> To handle concurrent conversations, open one session per conversation (not one session per
> thread). Multiple sessions can be open simultaneously on a single client.
>
> `kiosk_session_stream()` is safe to cancel from another thread by returning a non-zero value
> from the callback — but the callback itself is always invoked on the thread that called
> `kiosk_session_stream()`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.