Decode your first native packet
Open your installed SDK directory or extract the portable native ZIP. Run the archive-root commands below from that directory. Keep lib/, examples/, and example.klv together. Start with no token set. For a web application, follow the browser and Node.js quickstart.
The sample ST 0601 packet
The examples below decode this 87-byte MISB ST 0601 revision 19 packet, supplied as example.klv.

- Key. The first 16 bytes,
06 0E 2B 34 02 0B 01 01 0E 01 03 01 01 00 00 00, identify the ST 0601 UAS Datalink Local Set. - Length. The next byte,
46in hexadecimal, is the BER length. It declares 70 bytes of value, including the checksum item. - Value. The local set contains tag-length-value items. For example,
41 01 13means tag 65 has a one-byte value of0x13, which identifies revision 19. Tag 3 carriesTest missionand tag 10 carriesTest platform. - Checksum. The last item is
01 02 68 9C. Tag 1 has a two-byte checksum value of0x689C(26780), computed over the packet bytes through01 02.
Select a language below. The Go, Java, and Python commands use the Windows filename misb0601.dll. On Linux use misb0601.so. On macOS use misb0601.dylib.
- C
- C++
- C#
- Go
- Java
- Python
From the extracted archive root, use the command pair for your platform. Putting the executable beside the library lets it find the runtime.C commands
#include <stdio.h>
#include <stdlib.h>
#include "misb0601.h"
#include "roundtrip.h"
#include "fields.h"
#include "stream.h"
#include <string.h>
// Read a complete sample file without silently accepting a prefix.
static int read_sample(const char *path, uint8_t *buffer, size_t capacity, size_t *size) {
FILE *file = fopen(path, "rb");
if (!file) {
perror(path);
return 0;
}
*size = fread(buffer, 1, capacity, file);
int complete = fgetc(file) == EOF && !ferror(file);
fclose(file);
if (!complete) fprintf(stderr, "Could not read the complete sample file %s\n", path);
return complete;
}
int main(int argc, char **argv) {
if (argc < 2) return 1;
int encode = argc >= 3 && strcmp(argv[2], "--roundtrip") == 0;
if (encode && argc != 4) {
fputs("Usage: read <packet.klv> --roundtrip <input.json>\n", stderr);
return 1;
}
uint8_t packet[65536];
size_t size;
if (!read_sample(argv[1], packet, sizeof(packet), &size)) return 1;
// Validate the optional license token and report the decoder mode.
misb0601_license_status license = {0};
Misb0601LicenseInitialize(getenv("LIBMISB_NATIVE_TOKEN"), &license);
puts(license.is_decoder_demo ? "demo" : "licensed");
// Decode the complete KLV buffer to tag-keyed JSON with raw integer timestamps.
// Both OK and PARTIAL can return JSON that the caller must free.
misb0601_buffer json = {0};
int status = Misb0601DecodeJSON(packet, size, MISB0601_SORT_BY_TAG, MISB0601_JSON_KEYS_TAGS,
MISB0601_JSON_COMPACT, MISB0601_TIMESTAMPS_RAW, &json);
if (json.len) fwrite(json.data, 1, json.len, stdout);
putchar('\n');
Misb0601BufferFree(&json);
// Run the requested follow-up example, if any.
if (argc == 3 && strcmp(argv[2], "--fields") == 0) read_fields(packet, size);
int extra_ok = 1;
if (encode) {
uint8_t input[65536];
size_t input_size;
extra_ok = read_sample(argv[3], input, sizeof(input), &input_size) && roundtrip(input, input_size);
}
if (argc == 3 && strcmp(argv[2], "--stream") == 0) extra_ok = stream_packet(packet, size);
Misb0601LicenseShutdown();
return !extra_ok || (status != MISB0601_STATUS_OK && status != MISB0601_STATUS_PARTIAL);
}
From the archive root, use a C++17 compiler and the command pair for your platform.C++ commands
#include "misb0601.hpp"
#include "roundtrip.hpp"
#include "fields.hpp"
#include "../c/stream.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main(int argc, char **argv) {
if (argc < 3) return 1;
const bool encode = argc >= 4 && std::string(argv[3]) == "--roundtrip";
if (encode && argc != 5) {
std::cerr << "Usage: read <library> <packet.klv> --roundtrip <input.json>\n";
return 1;
}
// Load the native library, validate the optional token, and report the decoder mode.
misb0601::Library lib(argv[1]);
auto token = std::getenv("LIBMISB_NATIVE_TOKEN");
auto license = lib.ValidateLicense(token ? token : "");
std::cout << (license.isDecoderDemo ? "demo" : "licensed") << '\n';
// Read the binary packet from disk.
std::ifstream file(argv[2], std::ios::binary);
if (!file) return 1;
std::vector<uint8_t> packet{std::istreambuf_iterator<char>(file), {}};
// Decode the packet to JSON with raw integer timestamps. The wrapper owns the result buffer.
misb0601::DecoderOptions options;
options.timestampMode = MISB0601_TIMESTAMPS_RAW;
std::cout << lib.DecodeJson(packet.data(), packet.size(), options).ReadString() << '\n';
// Run the requested follow-up example, if any.
if (argc == 4 && std::string(argv[3]) == "--fields") read_fields(lib, packet);
bool ok = argc != 4 || std::string(argv[3]) != "--stream" || stream_packet(packet.data(), packet.size());
if (encode) {
// Pass the JSON bytes from disk straight to the encoder.
std::ifstream input(argv[4], std::ios::binary);
if (input) {
std::string json{std::istreambuf_iterator<char>(input), {}};
roundtrip(lib, options, json);
} else {
std::cerr << "Could not open " << argv[4] << '\n';
ok = false;
}
}
lib.ShutdownLicense();
return ok ? 0 : 1;
}
Install the .NET 8 SDK. On Windows, open examples/csharp/Example.sln in Visual Studio and press F5. The project restores from the bundled NuGet folder and decodes the included packet.
To run from a terminal, start at the SDK root.C# command
using LibMisb.Misb0601;
if (args.Length == 1) throw new ArgumentException("Supply both the library and packet paths.");
var roundTripIndex = Array.IndexOf(args, "--roundtrip", Math.Min(args.Length, 2));
if (roundTripIndex >= 0 && roundTripIndex + 1 == args.Length)
throw new ArgumentException("Supply the JSON input path after --roundtrip.");
// Use the bundled library and packet when no paths are supplied.
var libraryName = OperatingSystem.IsWindows() ? "misb0601.dll"
: OperatingSystem.IsMacOS() ? "misb0601.dylib"
: "misb0601.so";
var libraryPath = args.Length == 0 ? Path.Combine(AppContext.BaseDirectory, libraryName) : args[0];
var packetPath = args.Length == 0 ? Path.Combine(AppContext.BaseDirectory, "example.klv") : args[1];
// Load the native library and validate the optional license token.
using var library = Misb0601Library.Load(libraryPath);
var status = library.ValidateLicense(Environment.GetEnvironmentVariable("LIBMISB_NATIVE_TOKEN") ?? "");
try
{
Console.WriteLine(status.IsDecoderDemo ? "demo" : "licensed");
// Configure the decoder to return raw integer timestamps.
var decoder = library.CreateDecoder(new Misb0601DecoderOptions(TimestampMode: Misb0601TimestampMode.Raw));
// Read the complete KLV packet and decode it. Dispose the SDK-owned JSON buffer after use.
var packet = File.ReadAllBytes(packetPath);
using var result = decoder.DecodeJson(packet);
Console.WriteLine(result.ReadUtf8());
// Run the follow-up examples selected on the command line.
if (args.Contains("--stream")) PacketStream.Run(libraryPath, packet);
if (args.Contains("--fields")) Fields.Read(decoder, packet);
if (roundTripIndex >= 0) RoundTrip.Run(library, decoder, File.ReadAllBytes(args[roundTripIndex + 1]));
}
finally
{
library.ShutdownLicense();
}
Use Go 1.22 or later with cgo enabled and a C compiler on your PATH. The example's go.mod already points at the standalone module in the archive.GO commands
For your own application, require github.com/impleotv/libmisb-sdk-go v0.0.0 and add a local replace directive pointing at the extracted go/ directory.
package main
import (
"fmt"
"os"
sdk "github.com/impleotv/libmisb-sdk-go/misb0601abi"
)
func main() {
if len(os.Args) < 3 {
panic("supply library and packet paths")
}
// Load the native library and validate the optional license token.
lib, err := sdk.Load(os.Args[1])
must(err)
defer lib.Close()
status, err := lib.ValidateLicense(os.Getenv("LIBMISB_NATIVE_TOKEN"))
must(err)
defer lib.ShutdownLicense()
if status.IsDecoderDemo {
fmt.Println("demo")
} else {
fmt.Println("licensed")
}
// Preserve field order and return timestamps as raw integers.
options := sdk.DefaultDecoderOptions()
options.SortMode = sdk.PreserveInputOrder
options.TimestampMode = sdk.TimestampsRaw
decoder := lib.CreateDecoder(options)
// Read the complete KLV packet and decode it to JSON.
packet, err := os.ReadFile(os.Args[2])
must(err)
fields, err := decoder.DecodeJSON(packet)
must(err)
fmt.Println(string(fields))
// Run the requested follow-up example, if any.
if len(os.Args) == 4 && os.Args[3] == "--fields" {
readFields(decoder, packet)
}
if len(os.Args) == 4 && os.Args[3] == "--stream" {
streamPacket(decoder, packet)
}
if len(os.Args) >= 4 && os.Args[3] == "--roundtrip" {
if len(os.Args) != 5 {
panic("supply the JSON input path after --roundtrip")
}
input, err := os.ReadFile(os.Args[4])
must(err)
roundtrip(lib, decoder, input)
}
}
func must(err error) {
if err != nil {
panic(err)
}
}
Use a 64-bit JDK 22 or later. From the archive root, run the source file directly. The two arguments select the shared library and the binary ST 0601 packet.Java commands
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
/** Decodes one binary ST 0601 packet using the 64-bit misb0601.h ABI. */
public class DecodePacket {
static final int OK = 0, PARTIAL = 3;
static final MemoryLayout BUFFER = MemoryLayout.structLayout(
ADDRESS.withName("data"), JAVA_LONG.withName("len"), JAVA_LONG.withName("capacity"));
private static final MemoryLayout LICENSE = MemoryLayout.structLayout(
JAVA_INT.withName("initialized"), JAVA_INT.withName("mode"), JAVA_INT.withName("is_decoder_demo"),
JAVA_INT.withName("is_encoder_demo"), JAVA_INT.withName("is_validate_demo"),
JAVA_INT.withName("max_decoders"), JAVA_INT.withName("max_encoders"), JAVA_INT.withName("max_validators"));
private final SymbolLookup library;
private final MethodHandle lastError;
final MethodHandle free;
private DecodePacket(Path path) {
// Keep the loaded runtime resident for the life of this process.
library = SymbolLookup.libraryLookup(path.toAbsolutePath(), Arena.global());
lastError = bind("Misb0601LastErrorMessage", FunctionDescriptor.of(JAVA_INT, ADDRESS));
free = bind("Misb0601BufferFree", FunctionDescriptor.ofVoid(ADDRESS));
}
MethodHandle bind(String name, FunctionDescriptor signature) {
return Linker.nativeLinker().downcallHandle(library.find(name).orElseThrow(
() -> new UnsatisfiedLinkError(name)), signature);
}
static MemorySegment data(MemorySegment buffer) {
long length = buffer.get(JAVA_LONG, BUFFER.byteOffset(groupElement("len")));
return buffer.get(ADDRESS, BUFFER.byteOffset(groupElement("data"))).reinterpret(length);
}
static String text(MemorySegment buffer) {
return new String(data(buffer).toArray(JAVA_BYTE), StandardCharsets.UTF_8);
}
private String diagnostic(Arena arena, int status) throws Throwable {
MemorySegment message = arena.allocate(BUFFER);
try {
int result = (int) lastError.invokeExact(message);
return "ST 0601 status " + status + (result == OK ? ": " + text(message) : "");
} finally {
free.invokeExact(message);
}
}
void check(Arena arena, int status) throws Throwable {
if (status != OK) throw new IllegalStateException(diagnostic(arena, status));
}
void checkDecode(Arena arena, int status) throws Throwable {
if (status == PARTIAL) System.err.println(diagnostic(arena, status));
else check(arena, status);
}
void printJSON(MemorySegment input, Arena arena) throws Throwable {
// Bind the native packet decoder and allocate its output buffer.
MethodHandle decode = bind("Misb0601DecodeJSON", FunctionDescriptor.of(
JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_INT, ADDRESS));
MemorySegment json = arena.allocate(BUFFER);
try {
// Decode to compact, tag-keyed JSON with raw integer timestamps.
// A partial result can contain JSON alongside the diagnostic.
checkDecode(arena, (int) decode.invokeExact(input, input.byteSize(), 1, 1, 0, 0, json));
System.out.println(text(json));
} finally {
free.invokeExact(json);
}
}
private void run(byte[] packet, String option, byte[] json, Arena arena) throws Throwable {
// Validate the optional license token through the native API.
MethodHandle initialize = bind("Misb0601LicenseInitialize", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS));
MethodHandle shutdown = bind("Misb0601LicenseShutdown", FunctionDescriptor.of(JAVA_INT));
String token = System.getenv("LIBMISB_NATIVE_TOKEN");
MemorySegment license = arena.allocate(LICENSE);
MemorySegment tokenText = token == null ? MemorySegment.NULL : arena.allocateFrom(token);
int status = (int) initialize.invokeExact(tokenText, license);
if (status != OK && status != PARTIAL) throw new IllegalStateException(diagnostic(arena, status));
try {
boolean demo = license.get(JAVA_INT, LICENSE.byteOffset(groupElement("is_decoder_demo"))) != 0;
System.out.println(demo ? "demo" : "licensed");
// Copy the packet into native memory and decode it.
MemorySegment input = arena.allocateFrom(JAVA_BYTE, packet);
printJSON(input, arena);
// Run the requested follow-up example, if any.
switch (option) {
case "" -> { }
case "--fields" -> Fields.read(this, arena, input);
case "--roundtrip" -> RoundTrip.run(this, arena, json);
case "--stream" -> PacketStream.run(this, arena, input);
default -> throw new IllegalArgumentException("Unknown option " + option);
}
} finally {
int shutdownStatus = (int) shutdown.invokeExact();
if (shutdownStatus != OK) throw new IllegalStateException(diagnostic(arena, shutdownStatus));
}
}
public static void main(String[] args) throws Throwable {
String option = args.length >= 3 ? args[2] : "";
boolean encode = option.equals("--roundtrip");
if (args.length < 2 || (encode ? args.length != 4 : args.length > 3))
throw new IllegalArgumentException(
"Usage: DecodePacket <library> <packet.klv> [--fields|--stream|--roundtrip <input.json>]");
if (ADDRESS.byteSize() != 8) throw new IllegalStateException("A 64-bit JDK is required");
// Read the binary packet and, for the round trip, the encoder's JSON input.
byte[] packet = Files.readAllBytes(Path.of(args[1]));
byte[] json = encode ? Files.readAllBytes(Path.of(args[3])) : null;
try (Arena arena = Arena.ofConfined()) {
new DecodePacket(Path.of(args[0])).run(packet, option, json, arena);
}
}
}
Use Python 3.10 or later. In your virtual environment, run these commands from the archive root.Python commands
import json
import os
import sys
from pathlib import Path
from misb0601 import Misb0601DecoderOptions, Misb0601Library, Misb0601TimestampMode
from fields import read_fields
from roundtrip import roundtrip
from stream import stream_packet
flags = sys.argv[3:]
json_path = None
if "--roundtrip" in flags:
index = flags.index("--roundtrip") + 1
if index == len(flags):
sys.exit("Supply the JSON input path after --roundtrip.")
json_path = Path(flags[index])
# Load the native library and validate the optional license token.
library = Misb0601Library(sys.argv[1])
status = library.validate_license(os.getenv("LIBMISB_NATIVE_TOKEN", ""))
try:
print("demo" if status.is_decoder_demo else "licensed")
# Configure the decoder to return raw integer timestamps.
options = Misb0601DecoderOptions(timestamp_mode=Misb0601TimestampMode.RAW)
decoder = library.create_decoder(options)
# Read and decode the complete KLV packet. Python keeps the raw timestamp as an integer.
packet = Path(sys.argv[2]).read_bytes()
fields = json.loads(decoder.decode_json(packet))
print(json.dumps(fields))
# Run the follow-up examples selected on the command line.
if "--stream" in flags:
stream_packet(sys.argv[1], packet)
if "--fields" in flags:
read_fields(decoder, packet)
if json_path is not None:
roundtrip(library, decoder, json_path.read_bytes())
finally:
library.shutdown_license()
Recognize the result
The first line is demo. The next line contains these fields. Key order and whitespace may vary.
{
"1": 9400,
"2": 1795433587745520,
"3": "Test mission",
"4": "24",
"5": 147.9991,
"10": "Test platform",
"13": 41.093374324,
"14": -104.868772498,
"65": 19
}
Tag 2 is the precision timestamp in microseconds. Demo mode omits sensor true altitude (tag 15) and reports a checksum of 9400 for the filtered packet. A licensed decode includes tag 15 and reports the original checksum 26780.
The native SDK also includes example.json with the full sample fields used in the encoding and validation walkthrough. See reading fields to extract the timestamp and version in code.
How decoding works

Complete KLV packet or stream chunks
↓
KLV framing and parsing
↓
ST 0601 revision-aware decoding
↓
Decoded fields and diagnostics
- Supply the bytes. Pass a complete packet to the packet API, or feed successive chunks to a stream that assembles packets across chunk boundaries. For media input, pass the PES payload extracted by your demultiplexer. If available, pass its presentation timestamp (PTS) separately from the timestamp carried inside the metadata.
- Read the KLV envelope. The parser reads the key, length, and value. Raw KLV operations give applications access to packet and item structure. ST 0601 operations interpret the local set carried in the packet value.
- Decode using the applicable revision. The decoder can use the version in tag 65 to select field definitions. It interprets values and nested metadata, such as security or VMTI, according to the applicable definitions.
- Consume the result. Check the status and diagnostic before using the fields. A partial result can contain usable fields alongside a recoverable error. When sending large integers through JavaScript, keep the exact JSON text or use an integer-preserving parser.
Complete packets and fragmented input
Complete packet. Use the packet API when you already have one complete KLV packet, such as example.klv. Pass its key, BER length, and entire value together in one call.
Fragmented input. For MPEG-TS, use a demultiplexer to select the KLV metadata stream by PID and extract its packetized elementary stream (PES) payload bytes. Feed the payload chunks in order to one libmisb stream decoder. Supply the presentation timestamp (PTS) separately when it is available. PTS identifies a time on the media timeline. ST 0601 tag 2 carries the metadata's own timestamp.
libmisb uses the KLV key and BER length to frame each packet. If the first chunk ends inside packet A, the decoder holds those bytes. If the next chunk finishes A and starts B, the decoder emits A and keeps the start of B for the next push. A push can yield zero, one, or several packets.
Flush the stream at end of input to detect a truncated final packet. For native streams, poll for events after each push and after flushing. On the web, callbacks run during push and flush.
Decode fragmented packets and PES payloads · Revisions, exact JSON, and partial results