How to read a float from binary WebM file?

499 Views Asked by At

I'm trying to learn binary and create a simple WebM parser in PHP based on Matroska.

I read TimecodeScale, MuxingAppm WritingApp, etc. with unpack(format, data). My problem is when I reach Duration (0x4489) in Segment Information (0x1549a966) I must read a float and based on TimecodeScale convert it to seconds: 261.564s->00:04:21.564 and I don't know how.

This is a sample sequence:

`2A D7 B1 83 0F 42 40 4D 80 86 67 6F 6F 67 6C 65 57 41 86 67 6F 6F 67 6C 65 44 89 88 41 0F ED E0 00 00 00 00 16 54 AE 6B`

TimecodeScale := 2ad7b1 uint [ def:1000000; ]

MuxingApp := 4d80 string; ("google")

WritingApp := 5741 string; ("google")

Duration := 4489 float [ range:>0.0; ]

Tracks := 1654ae6b container [ card:*; ]{...}

I must read a float after (0x4489) and return 261.564s.

1

There are 1 best solutions below

1
On BEST ANSWER

The duration is a double precision floating point value (64-bits) represented in the IEEE 754 format. If you want to see how the conversion is done check this.

The TimecodeScale is the timestamp scale in nanoseconds.

In php you can do:

$bin = hex2bin('410fede000000000');
$timecode_scale = 1e6;

// endianness
if (unpack('S', "\xff\x00")[1] === 0xff) {
    $bytes = unpack('C8', $bin);
    $bytes = array_reverse($bytes);
    $bin = implode('', array_map('chr', $bytes));
}

$duration = unpack('d', $bin)[1];
$duration_s = $duration * $timecode_scale / 1e9;

echo "duration=${duration_s}s\n";

Result:

duration=261.564s