Decode fragmented packets and PES payloads
Pass the payload bytes from your demultiplexer. A chunk can contain part of a KLV packet or several packets. Supply PTS when it is known for a demuxed PES payload. The ST 0601 timestamp inside the decoded metadata is a separate value.
Native polling
Append --stream to the native quickstart run command. Each example splits the supplied packet, attaches PTS to the first chunk, and prints the decoded event. Drain after each push and again after the final flush. For ordinary byte chunks use the push operation without PES metadata.
- C
- C++
- C#
- Go
- Python
#pragma once
#include "misb0601.h"
#include <stdio.h>
static int drain_events(misb0601_stream_decoder stream) {
for (;;) {
misb0601_stream_event event = {0};
int status = Misb0601StreamDecoderNext(stream, &event);
if (status == MISB0601_STATUS_NO_DATA) return 1;
if (status != MISB0601_STATUS_OK) return 0;
int decoded = event.kind == MISB0601_STREAM_EVENT_RESULT;
FILE *out = decoded ? stdout : stderr;
if (event.json.len) fwrite(event.json.data, 1, event.json.len, out);
fputc('\n', out);
Misb0601StreamEventFree(&event);
if (!decoded) return 0;
}
}
static int stream_packet(uint8_t *packet, size_t size) {
misb0601_stream_decoder_config options = {0};
options.output_buffer = 8;
options.output_flags = MISB0601_STREAM_OUTPUT_JSON;
options.key_mode = MISB0601_JSON_KEYS_TAGS;
options.timestamp_mode = MISB0601_TIMESTAMPS_RAW;
misb0601_stream_decoder stream = Misb0601StreamDecoderCreate(&options);
if (!stream) return 0;
size_t split = size / 2;
int ok = Misb0601StreamDecoderPushPES(stream, packet, split, 90000, 1) == MISB0601_STATUS_OK
&& drain_events(stream)
&& Misb0601StreamDecoderPushPES(stream, packet + split, size - split, 0, 0) == MISB0601_STATUS_OK
&& drain_events(stream)
&& Misb0601StreamDecoderFlush(stream) == MISB0601_STATUS_OK
&& drain_events(stream);
Misb0601StreamDecoderFree(stream);
return ok;
}
C++ calls the same linked C stream functions as the C example. Include the shared helper from the archive.
#pragma once
#include "misb0601.h"
#include <stdio.h>
static int drain_events(misb0601_stream_decoder stream) {
for (;;) {
misb0601_stream_event event = {0};
int status = Misb0601StreamDecoderNext(stream, &event);
if (status == MISB0601_STATUS_NO_DATA) return 1;
if (status != MISB0601_STATUS_OK) return 0;
int decoded = event.kind == MISB0601_STREAM_EVENT_RESULT;
FILE *out = decoded ? stdout : stderr;
if (event.json.len) fwrite(event.json.data, 1, event.json.len, out);
fputc('\n', out);
Misb0601StreamEventFree(&event);
if (!decoded) return 0;
}
}
static int stream_packet(uint8_t *packet, size_t size) {
misb0601_stream_decoder_config options = {0};
options.output_buffer = 8;
options.output_flags = MISB0601_STREAM_OUTPUT_JSON;
options.key_mode = MISB0601_JSON_KEYS_TAGS;
options.timestamp_mode = MISB0601_TIMESTAMPS_RAW;
misb0601_stream_decoder stream = Misb0601StreamDecoderCreate(&options);
if (!stream) return 0;
size_t split = size / 2;
int ok = Misb0601StreamDecoderPushPES(stream, packet, split, 90000, 1) == MISB0601_STATUS_OK
&& drain_events(stream)
&& Misb0601StreamDecoderPushPES(stream, packet + split, size - split, 0, 0) == MISB0601_STATUS_OK
&& drain_events(stream)
&& Misb0601StreamDecoderFlush(stream) == MISB0601_STATUS_OK
&& drain_events(stream);
Misb0601StreamDecoderFree(stream);
return ok;
}
using System.Runtime.InteropServices;
using LibMisb.Native.St0601;
using static LibMisb.Native.St0601.Constants;
static unsafe class PacketStream
{
internal static void Run(string libraryPath, byte[] packet)
{
using var api = new Api(libraryPath);
var options = new misb0601_stream_decoder_config {
output_buffer = 8, output_flags = MISB0601_STREAM_OUTPUT_JSON,
key_mode = MISB0601_JSON_KEYS_TAGS, timestamp_mode = MISB0601_TIMESTAMPS_RAW
};
var stream = api.Misb0601StreamDecoderCreate(&options);
if (stream == 0) throw new InvalidOperationException("Could not create a stream.");
try
{
fixed (byte* bytes = packet)
{
var split = packet.Length / 2;
Check(api.Misb0601StreamDecoderPushPES(stream, bytes, (nuint)split, 90000, 1));
Drain(api, stream);
Check(api.Misb0601StreamDecoderPushPES(stream, bytes + split, (nuint)(packet.Length - split), 0, 0));
Drain(api, stream);
}
Check(api.Misb0601StreamDecoderFlush(stream));
Drain(api, stream);
}
finally { api.Misb0601StreamDecoderFree(stream); }
}
static void Drain(Api api, nuint stream)
{
while (true)
{
misb0601_stream_event item = default;
var status = api.Misb0601StreamDecoderNext(stream, &item);
if (status == MISB0601_STATUS_NO_DATA) return;
Check(status);
try
{
var text = Marshal.PtrToStringUTF8((nint)item.json.data, checked((int)item.json.len));
if (item.kind == MISB0601_STREAM_EVENT_ERROR) throw new InvalidDataException(text);
Console.WriteLine(text);
}
finally { api.Misb0601StreamEventFree(&item); }
}
}
static void Check(int status)
{
if (status != MISB0601_STATUS_OK) throw new InvalidOperationException($"Stream status {status}");
}
}
package main
import (
"fmt"
sdk "github.com/impleotv/libmisb-sdk-go/misb0601abi"
)
func streamPacket(decoder *sdk.Decoder, packet []byte) {
stream, err := decoder.OpenStream(8)
must(err)
defer stream.Close()
drain := func() {
for {
event, err := stream.Next()
must(err)
if event == nil {
return
}
if event.WireError {
panic(string(event.JSON))
}
fmt.Println(string(event.JSON))
}
}
pts := uint64(90000)
split := len(packet) / 2
must(stream.PushPES(packet[:split], &pts))
drain()
must(stream.PushPES(packet[split:], nil))
drain()
must(stream.Flush())
drain()
}
import ctypes as C
from misb0601 import st0601_abi as abi
def stream_packet(path, packet):
api = abi.load(path)
options = abi.misb0601_stream_decoder_config(
output_buffer=8, output_flags=abi.MISB0601_STREAM_OUTPUT_JSON,
key_mode=abi.MISB0601_JSON_KEYS_TAGS, timestamp_mode=abi.MISB0601_TIMESTAMPS_RAW)
stream = api.Misb0601StreamDecoderCreate(C.byref(options))
if not stream:
raise RuntimeError("could not create a stream")
def check(status):
if status != abi.MISB0601_STATUS_OK:
raise RuntimeError(f"stream status {status}")
def drain():
while True:
event = abi.misb0601_stream_event()
status = api.Misb0601StreamDecoderNext(stream, C.byref(event))
if status == abi.MISB0601_STATUS_NO_DATA:
return
check(status)
try:
text = C.string_at(event.json.data, event.json.len).decode()
if event.kind == abi.MISB0601_STREAM_EVENT_ERROR:
raise ValueError(text)
print(text)
finally:
api.Misb0601StreamEventFree(C.byref(event))
try:
split = len(packet) // 2
for chunk, pts in [(packet[:split], 90000), (packet[split:], None)]:
data = (C.c_uint8 * len(chunk)).from_buffer_copy(chunk)
check(api.Misb0601StreamDecoderPushPES(stream, data, len(chunk), pts or 0, pts is not None))
drain()
check(api.Misb0601StreamDecoderFlush(stream))
drain()
finally:
api.Misb0601StreamDecoderFree(stream)
Check the event kind for a wire error and its PTS presence flag before reading the presentation timestamp. The ST 0601 ABI lists the stream and event ownership rules.
Web callbacks and TypeScript
The archive includes stream-example.mts and index.d.mts. Call decodePayload(bytes, pts) with one packet to try the example. With TypeScript 5 or later and Node.js installed, run these commands in the extracted web ZIP:
tsc --module nodenext --target es2022 --strict stream-example.mts
node --input-type=module -e "import {readFile} from 'node:fs/promises'; import {decodePayload} from './stream-example.mjs'; await decodePayload(await readFile('example.klv'), 90000)"
The single event starts with byte offset 0 and PTS 90000. In a live application, create the stream once and feed successive chunks to it. Decoded callbacks run synchronously during push and flush.
import {createDecoder, type StreamMetadata} from './index.mjs';
export async function decodePayload(payload: Uint8Array, pts: number) {
const decoder = await createDecoder();
try {
const stream = decoder.createStream({operation: 'packet'}, (json: string, meta: StreamMetadata) => {
console.log(meta.offset, meta.pts, json);
});
try {
const split = Math.floor(payload.length / 2);
stream.pushPES(payload.subarray(0, split), pts);
stream.pushPES(payload.subarray(split));
stream.flush();
} finally {
stream.close();
}
} finally {
await decoder.close();
}
}
The callback receives the exact JSON envelope and a byte offset. Inspect its status for partial results. Supply a third callback to createStream to handle wire errors; without one they throw. Closing the decoder releases its active streams.