forked from alexjustesen/speedtest-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitrate.php
More file actions
94 lines (79 loc) · 2.48 KB
/
Bitrate.php
File metadata and controls
94 lines (79 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace App\Helpers;
use InvalidArgumentException;
class Bitrate
{
/**
* Units conversion map to bits
* Base unit is bits (not bytes)
*/
private const UNITS = [
'b' => 1,
'kb' => 1000,
'kib' => 1024,
'mb' => 1000000,
'mib' => 1048576,
'gb' => 1000000000,
'gib' => 1073741824,
'tb' => 1000000000000,
'tib' => 1099511627776,
];
/**
* Convert bytes to bits.
*/
public static function bytesToBits(int|float $bytes): int|float
{
if ($bytes < 0) {
throw new InvalidArgumentException('Bytes value cannot be negative');
}
// 1 byte = 8 bits
return round($bytes * 8);
}
/**
* Parse and normalize any bit rate to bits.
*/
public static function normalizeToBits(float|int|string $bitrate): float
{
// If numeric, assume it's already in bits
if (is_numeric($bitrate)) {
return (float) $bitrate;
}
// Convert to lowercase and remove any whitespace
$bitrate = strtolower(trim($bitrate));
// Remove 'ps' or 'per second' suffix if present
$bitrate = str_replace(['ps', 'per second'], '', $bitrate);
// Extract numeric value and unit
if (! preg_match('/^([\d.]+)\s*([kmgt]?i?b)$/', $bitrate, $matches)) {
throw new InvalidArgumentException(
"Invalid bitrate format. Expected format: '1.5 Mb', '500kb', etc."
);
}
$value = (float) $matches[1];
$unit = $matches[2];
// Validate unit
if (! isset(self::UNITS[$unit])) {
throw new InvalidArgumentException(
"Invalid unit '$unit'. Supported units: ".implode(', ', array_keys(self::UNITS))
);
}
// Convert to bits
return $value * self::UNITS[$unit];
}
/**
* Format bits to human readable string.
*/
public static function formatBits(float $bits, bool $useBinaryPrefix = false, int $precision = 2): string
{
$units = $useBinaryPrefix
? ['b', 'Kib', 'Mib', 'Gib', 'Tib']
: ['b', 'kb', 'Mb', 'Gb', 'Tb'];
$divisor = $useBinaryPrefix ? 1024 : 1000;
$power = floor(($bits ? log($bits) : 0) / log($divisor));
$power = min($power, count($units) - 1);
return sprintf(
"%.{$precision}f %s",
$bits / pow($divisor, $power),
$units[$power]
);
}
}