Use IMFSplitter to extract encoded KLV packets from an MPEG-TS container. The same MFCodecsCoreLib interfaces are used in MFormats and MPlatform.
The examples below read UAS Datalink Local Sets identified by the Universal Key defined in MISB ST 0601.8. Sample files: Night Flight IR.mpg and Day Flight.mpg.
Reading packets with IMFSplitter
SplitterStreamInfoGet identifies data streams by eMediaType == eMFMT_Data. SplitterBeginSegment starts reading the selected stream; SplitterPacketGet returns its encoded packets. The code reads each data stream and checks the UAS Local Set key before passing the bytes to OnPacket.
PacketInfoGet returns cbPacketData and lpPacketData. Copy the bytes before releasing the packet.
public void ExtractKlv(String FilePath, Action<Byte[]> OnPacket)
{
var Splitter = new MFCodecsCoreLib.MFSplitterClass();
try
{
Splitter.SplitterOpen(FilePath, "", out Int32 StreamsCount);
for (Int32 StreamIndex = 0; StreamIndex < StreamsCount; StreamIndex++)
{
Splitter.SplitterStreamInfoGet(StreamIndex,
out MFCodecsCoreLib.M_STREAM_INFO StreamInfo, out String StreamXml);
if (StreamInfo.eMediaType != MFCodecsCoreLib.eMFMediaType.eMFMT_Data)
continue;
// Start each data stream from the beginning of the file.
Splitter.SplitterBeginSegment(0, StreamXml);
try
{
while (true)
{
MFCodecsCoreLib.IMFPacket Packet;
try
{
Splitter.SplitterPacketGet(StreamIndex, out Packet, "");
}
catch (COMException ex) when (ex.ErrorCode == unchecked((Int32)0x8007044C))
{
break; // End of source (ERROR_NO_DATA).
}
if (Packet == null)
break;
Boolean Last;
try
{
Packet.PacketInfoGet(out MFCodecsCoreLib.M_PACKET_INFO Info);
Last = (Info.eFlags & MFCodecsCoreLib.eMFPacketFlags.eMFPF_Last) != 0;
if (Info.cbPacketData > 0)
{
if (Info.lpPacketData == 0)
throw new InvalidOperationException("Packet data pointer is null.");
Byte[] Data = new Byte[Info.cbPacketData];
Marshal.Copy(new IntPtr(Info.lpPacketData), Data, 0, Data.Length);
if (IsUasLocalSet(Data, 0, Data.Length))
OnPacket(Data);
}
}
finally
{
Marshal.ReleaseComObject(Packet);
}
if (Last)
break;
}
}
finally
{
Splitter.SplitterStop();
}
}
}
finally
{
try { Splitter.SplitterClose(); }
finally { Marshal.ReleaseComObject(Splitter); }
}
}private static readonly Byte[] UasKey =
{
0x06, 0x0E, 0x2B, 0x34, 0x02, 0x0B, 0x01, 0x01,
0x0E, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00
};
private static Boolean IsUasLocalSet(Byte[] Data, Int32 Position, Int32 End)
{
if (End - Position < UasKey.Length)
return false;
for (Int32 i = 0; i < UasKey.Length; i++)
if (Data[Position + i] != UasKey[i])
return false;
return true;
}To print the encoded bytes:
ExtractKlv(@"C:\Media\Night Flight IR.mpg", Data =>
Console.WriteLine(BitConverter.ToString(Data).Replace("-", " ")));KLV packet structure
KLV consists of a Key, a BER-encoded Length, and a Value. For a UAS Datalink Local Set, the Key is 16 bytes and the Value contains local Tag-Length-Value items. Tags use BER-OID encoding; item lengths use BER encoding.
The beginning of a packet from Night Flight IR.mpg:
06 0E 2B 34 02 0B 01 01 0E 01 03 01 01 00 00 00 Universal Key
81 90 Local Set length: 144 bytes
02 08 00 04 6C AE 70 F9 80 CF Tag 2, length 8, timestamp
41 01 01 Tag 65, length 1, version 1
05 02 E1 91 Tag 5, length 2, heading
...81 90 means that one byte follows to encode the length: 0x90 = 144. The complete Set occupies 16 + 2 + 144 = 162 bytes. Length describes the Value only.
Decoding MISB fields
Field meanings and scaling come from the metadata standard, not from KLV itself. Multibyte integers use big-endian byte order.
| Tag | Field | Conversion |
|---|---|---|
| 2 | Precision Time Stamp | UInt64: microseconds since 1970-01-01 UTC; one microsecond = 10 .NET ticks |
| 5 | Platform Heading Angle | UInt16 × 360 / 65535 degrees |
| 13 | Sensor Latitude | Int32 × 90 / 2147483647 degrees |
| 14 | Sensor Longitude | Int32 × 180 / 2147483647 degrees |
For Tag 5, E1 91 is 57745: 57745 × 360 / 65535 = 317.207599 degrees. For latitude and longitude, Int32.MinValue is a reserved error value.
DecodeKlv checks Set and item boundaries, decodes these four fields, and prints other tags as hexadecimal bytes. It accepts consecutive complete UAS Local Sets in one buffer. It does not reassemble Sets split across packets or validate the checksum (Tag 1).
private static Int32 ReadBerLength(Byte[] Data, ref Int32 Position, Int32 End)
{
if (Position >= End)
throw new FormatException("Missing BER length.");
Int32 First = Data[Position++];
if (First < 0x80)
return First;
Int32 Count = First & 0x7F;
if (Count == 0 || Count > 4 || Count > End - Position)
throw new FormatException("Invalid or unsupported BER length.");
UInt32 Length = 0;
for (Int32 i = 0; i < Count; i++)
Length = (Length << 8) | Data[Position++];
if (Length > Int32.MaxValue)
throw new FormatException("BER length exceeds Int32 range.");
return (Int32)Length;
}
private static Int32 ReadTag(Byte[] Data, ref Int32 Position, Int32 End)
{
Int32 Tag = 0;
while (Position < End)
{
Byte Part = Data[Position++];
if (Tag > (Int32.MaxValue >> 7))
throw new FormatException("BER-OID tag exceeds Int32 range.");
Tag = (Tag << 7) | (Part & 0x7F);
if ((Part & 0x80) == 0)
return Tag;
}
throw new FormatException("Incomplete BER-OID tag.");
}
private static UInt64 ReadUnsigned(Byte[] Data, Int32 Position, Int32 Length)
{
UInt64 Value = 0;
for (Int32 i = 0; i < Length; i++)
Value = (Value << 8) | Data[Position + i];
return Value;
}
public static void DecodeKlv(Byte[] Data)
{
Int32 Position = 0;
while (Position < Data.Length)
{
if (!IsUasLocalSet(Data, Position, Data.Length))
throw new FormatException("Expected a UAS Datalink Local Set key.");
Position += 16;
Int32 SetLength = ReadBerLength(Data, ref Position, Data.Length);
if (SetLength > Data.Length - Position)
throw new FormatException("Truncated KLV set.");
Int32 End = Position + SetLength;
while (Position < End)
{
Int32 Tag = ReadTag(Data, ref Position, End);
Int32 Length = ReadBerLength(Data, ref Position, End);
if (Length > End - Position)
throw new FormatException("Local item exceeds the set boundary.");
String Value;
switch (Tag)
{
case 2:
if (Length != 8)
throw new FormatException("Tag 2 requires 8 bytes.");
UInt64 Microseconds = ReadUnsigned(Data, Position, Length);
DateTimeOffset Epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
UInt64 MaxMicroseconds = (UInt64)((DateTimeOffset.MaxValue.Ticks - Epoch.Ticks) / 10);
if (Microseconds > MaxMicroseconds)
throw new FormatException("Timestamp exceeds the .NET date range.");
Value = "Precision Time Stamp: " + Epoch.AddTicks((Int64)Microseconds * 10)
.ToString("yyyy-MM-dd HH:mm:ss.ffffff 'UTC'", CultureInfo.InvariantCulture);
break;
case 5:
if (Length != 2)
throw new FormatException("Tag 5 requires 2 bytes.");
Double Heading = ReadUnsigned(Data, Position, Length) * 360.0 / UInt16.MaxValue;
Value = "Platform Heading Angle: " + Heading.ToString("F6", CultureInfo.InvariantCulture) + " degrees";
break;
case 13:
case 14:
if (Length != 4)
throw new FormatException("Latitude/longitude requires 4 bytes.");
Int32 Coordinate = unchecked((Int32)(UInt32)ReadUnsigned(Data, Position, Length));
Double Scale = Tag == 13 ? 90.0 : 180.0;
Value = (Tag == 13 ? "Sensor Latitude: " : "Sensor Longitude: ") +
(Coordinate == Int32.MinValue ? "Reserved error value" :
(Coordinate * Scale / Int32.MaxValue).ToString("F8", CultureInfo.InvariantCulture) + " degrees");
break;
default:
Value = "Tag " + Tag + ": " + BitConverter.ToString(Data, Position, Length).Replace("-", " ");
break;
}
Console.WriteLine(Value);
Position += Length;
}
}
}To extract and decode:
ExtractKlv(@"C:\Media\Night Flight IR.mpg", DecodeKlv);Reading KLV during playback
To receive encoded data packets as frame attachments, open the source with:
external_process=false experimental.out_subtitle_packets=1experimental.out_subtitle_packets also controls data packet attachments on this decoder path. A frame may have zero, one, or multiple attachments: the packets are attached as objects named data.encoded_packet, data.encoded_packet.1 and so on, together with subtitle packets if the source has subtitles. Check each attached object for IMFPacket, the data stream type, and the Universal Key.
Read attachments from the source frame before video conversion. The examples below process the first 150 frames; increase or remove the limit to read the rest of the file.
MFormats: SourceFrameGet
public void ReadKlvWithMFormats(String FilePath)
{
MFReaderClass m_objReader = new MFReaderClass();
MFPreviewClass m_objPreview = new MFPreviewClass();
try
{
m_objReader.ReaderOpen(FilePath, "external_process=false experimental.out_subtitle_packets=1");
m_objPreview.PreviewEnable("", 1, 1);
for (Int32 FrameIndex = 0; FrameIndex < 150; FrameIndex++)
{
m_objReader.SourceFrameGet(-1, out MFFrame Frame, "");
if (Frame == null)
break;
try
{
Frame.MFAllGet(out MF_FRAME_INFO FrameInfo);
for (Int32 ObjectIndex = 0; ObjectIndex < FrameInfo.nObjCount; ObjectIndex++)
{
Frame.MFObjGetByIndex(ObjectIndex, out String ObjectId, out Object AttachedObject, 1);
if (AttachedObject == null)
continue;
try
{
MFCodecsCoreLib.IMFPacket KlvPacket = AttachedObject as MFCodecsCoreLib.IMFPacket;
if (KlvPacket == null)
continue;
KlvPacket.PacketStreamInfoGet(out MFCodecsCoreLib.M_STREAM_INFO StreamInfo);
if (StreamInfo.eMediaType != MFCodecsCoreLib.eMFMediaType.eMFMT_Data)
continue;
KlvPacket.PacketInfoGet(out MFCodecsCoreLib.M_PACKET_INFO PacketInfo);
if (PacketInfo.cbPacketData < 17 || PacketInfo.lpPacketData == 0)
continue;
Byte[] KlvData = new Byte[PacketInfo.cbPacketData];
Marshal.Copy(new IntPtr(PacketInfo.lpPacketData), KlvData, 0, KlvData.Length);
if (BitConverter.ToString(KlvData, 0, 16) != "06-0E-2B-34-02-0B-01-01-0E-01-03-01-01-00-00-00")
continue;
Console.WriteLine("Frame #" + FrameIndex + ", object=" + ObjectId + ", size=" + KlvData.Length + " bytes");
Console.WriteLine("RAW data: " + BitConverter.ToString(KlvData).Replace("-", " "));
DecodeKlv(KlvData);
}
finally
{
Marshal.ReleaseComObject(AttachedObject);
}
}
m_objPreview.ReceiverFramePut(Frame, -1, "");
if ((FrameInfo.mTime.eFFlags & eMFrameFlags.eMFF_Last) != 0)
break;
}
finally
{
Marshal.ReleaseComObject(Frame);
}
}
}
finally
{
m_objPreview.MFClose();
m_objReader.ReaderClose();
Marshal.ReleaseComObject(m_objPreview);
Marshal.ReleaseComObject(m_objReader);
}
}MPlatform: OnFrameSafe
object::on_frame.sync=true makes the SDK wait for the handler before forwarding the frame to receivers. object::on_frame.data=true enables frame data access. object::events.use_window=false delivers events without a GUI message loop.
public void ReadKlvWithMPlatform(String FilePath)
{
MFileClass m_objFile = new MFileClass();
MPreviewClass m_objPreview = new MPreviewClass();
ManualResetEventSlim Completed = new ManualResetEventSlim(false);
Exception CallbackError = null;
Int32 FrameIndex = 0;
IMEventsFrame_OnFrameSafeEventHandler OnFrame = (String bsChannelID, Object pMFrame) =>
{
try
{
if (Completed.IsSet)
return;
IMFFrame Frame = (IMFFrame)pMFrame;
Frame.MFAllGet(out MF_FRAME_INFO FrameInfo);
for (Int32 ObjectIndex = 0; ObjectIndex < FrameInfo.nObjCount; ObjectIndex++)
{
Frame.MFObjGetByIndex(ObjectIndex, out String ObjectId, out Object AttachedObject, 1);
if (AttachedObject == null)
continue;
try
{
MFCodecsCoreLib.IMFPacket KlvPacket = AttachedObject as MFCodecsCoreLib.IMFPacket;
if (KlvPacket == null)
continue;
KlvPacket.PacketStreamInfoGet(out MFCodecsCoreLib.M_STREAM_INFO StreamInfo);
if (StreamInfo.eMediaType != MFCodecsCoreLib.eMFMediaType.eMFMT_Data)
continue;
KlvPacket.PacketInfoGet(out MFCodecsCoreLib.M_PACKET_INFO PacketInfo);
if (PacketInfo.cbPacketData < 17 || PacketInfo.lpPacketData == 0)
continue;
Byte[] KlvData = new Byte[PacketInfo.cbPacketData];
Marshal.Copy(new IntPtr(PacketInfo.lpPacketData), KlvData, 0, KlvData.Length);
if (BitConverter.ToString(KlvData, 0, 16) != "06-0E-2B-34-02-0B-01-01-0E-01-03-01-01-00-00-00")
continue;
Console.WriteLine("Frame #" + FrameIndex + ", object=" + ObjectId + ", size=" + KlvData.Length + " bytes");
Console.WriteLine("RAW data: " + BitConverter.ToString(KlvData).Replace("-", " "));
DecodeKlv(KlvData);
}
finally
{
Marshal.ReleaseComObject(AttachedObject);
}
}
FrameIndex += 1;
if (FrameIndex >= 150 || (FrameInfo.mTime.eFFlags & eMFrameFlags.eMFF_Last) != 0)
Completed.Set();
}
catch (Exception ex)
{
CallbackError = ex;
Completed.Set();
}
finally
{
Marshal.ReleaseComObject(pMFrame);
}
};
try
{
m_objFile.PropsSet("object::events.use_window", "false");
m_objFile.PropsSet("object::on_frame.sync", "true");
m_objFile.PropsSet("object::on_frame.data", "true");
m_objFile.OnFrameSafe += OnFrame;
m_objFile.FileNameSet(FilePath, "external_process=false experimental.out_subtitle_packets=1");
m_objPreview.PreviewEnable("", 1, 1);
m_objPreview.ObjectStart(m_objFile);
m_objFile.FilePlayStart();
Boolean Finished = Completed.Wait(30_000);
m_objFile.FilePlayStop(0.0d);
if (CallbackError != null)
throw new InvalidOperationException("Failed to read KLV in OnFrameSafe.", CallbackError);
if (!Finished)
throw new TimeoutException("Frame processing did not finish within 30 seconds.");
}
finally
{
m_objPreview.ObjectClose();
m_objFile.ObjectClose();
m_objFile.OnFrameSafe -= OnFrame;
Marshal.ReleaseComObject(m_objPreview);
Marshal.ReleaseComObject(m_objFile);
Completed.Dispose();
}
}Copy packet bytes in the synchronous handler. Move decoding to a worker thread if its processing time delays playback.
Packet time and video time
IMFPacket.PacketTimeGet returns packet times in 100-nanosecond units. MISB Tag 2 stores an absolute UTC timestamp. A frame attachment alone does not establish that these time values refer to the same instant; use the source's timing relationship to associate metadata with video.
Still have questions?
Tell us what didn’t work or what you’d like clarified.