# SRT message framing

<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

To send and receive Realtime Media Streams (RTMS) messages over a Secure Reliable Transport (SRT) data connection, your app must frame each message. Framing adds a length prefix to each message you send, and reads that prefix to find where each incoming message starts and ends. This topic describes the framing format and how to encode and parse records. WebSocket signaling doesn't use this prefix, because WebSocket messages already keep message boundaries.

## Why framing is needed

SRT in file or stream mode delivers a continuous stream of bytes, similar to TCP. It doesn't keep RTMS message boundaries, so the following can happen.

-   A read can return a chunk of any size.
-   One read can contain several RTMS messages.
-   A single message, including its length prefix, can be split across several reads.

RTMS uses a fixed-length package format to mark where each message begins and ends. The fixed-length package format is an application-layer format. It's separate from SRT's own transport headers, so your client must encode and decode it on every SRT data connection.

## Record structure

Each record has a 4-byte length header followed by one serialized RTMS message. The header is fixed-width, and the message body length varies. The diagram shows one record's layout as a box, and as byte offsets below it.

```plaintext
                 Fixed-length package record: 4 + N bytes
┌──────────────────────┬───────────────────────────────────┐
│ Length: 4 bytes      │ Message body: N bytes             │
│ Big-endian uint32    │ Serialized JSON or protobuf       │
└──────────────────────┴───────────────────────────────────┘

Offset:  0       1       2       3       4       ...     N+3
       ┌───────┬───────┬───────┬───────┬───────┬─────┬───────────┐
       │Len[0] │Len[1] │Len[2] │Len[3] │Data[0]│ ... │Data[N-1]  │
       └───────┴───────┴───────┴───────┴───────┴─────┴───────────┘

uint32_be(N) || message_body(N bytes)
```

| Field          | Size (bytes) | Description                                                                                                                     |
| -------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `length`       | 4            | The number of bytes in `message_body`, stored as an unsigned big-endian integer. This count excludes the `length` field itself. |
| `message_body` | N            | One complete serialized RTMS message, where `1 <= N <= 1,048,576`.                                                              |

For example, to send a message body of 1,000 bytes:

-   The header is `00 00 03 e8`, which is 1,000 as a big-endian `uint32`.
-   The body is the 1,000 serialized bytes.
-   The full record is 1,004 bytes.

The 32-bit length field can hold values up to `2^32 - 1`, but RTMS rejects bodies over 1 MiB (1,048,576 bytes), not counting the 4-byte header. Count the entire serialized body, including its metadata and any Base64 expansion.

Individual RTMS requests can also have stricter validation limits. Staying within the framing limit doesn't make a request valid by itself.

The fixed-length package length and a media message's `content.length` count different things. `content.length` counts only the media payload bytes. The fixed-length package length counts the entire serialized RTMS message.

## Relationship to SRT packets

SRT carries the framed byte stream over UDP. It handles packetization, encryption, and reassembly. One record can span several SRT packets, and one packet can contain parts of several records. A length header can also cross a packet boundary.

The diagram shows how an application stream is split into network packets and read back by the client.

![Diagram of an application stream made of length-prefixed messages. SRT splits the stream into network packets, each with IP, UDP, and SRT headers. On receipt, SRT reassembles and decrypts the stream, and the client reads it in chunks whose sizes don't match the message or packet boundaries.](/img/rtms_srt_packet_flow.png)

The length header is the first 4 bytes of each application record, not the first 4 bytes of each SRT packet. Transport payload sizes depend on the path MTU and SRT settings. Don't assume a fixed payload size, and don't use UDP or SRT packet boundaries to find RTMS messages. The SRT library handles the network headers, and your app only processes the reassembled stream.

## Encoding and decoding rules

Apply these rules to every record you encode or decode.

-   JSON bodies are UTF-8. Count encoded bytes, not characters.
-   Protobuf bodies are binary, serialized `RtmsMessage` envelopes that contain the matching typed message in `payload`. Don't prefix only the inner typed message.
-   Don't add a delimiter, a NUL terminator, an HTTP header, or a WebSocket frame. Don't use protobuf's variable-length delimited-message prefix.
-   Apply framing to every message on the SRT data connection, including the data handshake, the handshake response, media, and keep-alives.
-   Handle partial writes. A single send call doesn't have to write the whole record. If several tasks write to the same connection, serialize the writes so records can't interleave.
-   WebSocket signaling uses WebSocket message boundaries, and doesn't use this prefix.

## Parse records from the byte stream

Follow these steps to split the incoming byte stream into complete RTMS messages.

1.  Accumulate received bytes until you have at least 4.
2.  Read and validate the length `N`.
3.  Wait until all `N` body bytes are available before you dispatch the message.
4.  Remove exactly `4 + N` bytes.
5.  Repeat for any complete records that follow, and keep any incomplete bytes for the next read.
