forked from chrisyue/php-m3u8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.php
102 lines (80 loc) · 2.67 KB
/
Parser.php
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
95
96
97
98
99
100
101
102
<?php
/*
* This file is part of the PhpM3u8 package.
*
* (c) Chrisyue <http://chrisyue.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Chrisyue\PhpM3u8;
use Chrisyue\PhpM3u8\Loader\LoaderInterface;
use Chrisyue\PhpM3u8\M3u8\M3u8;
use Chrisyue\PhpM3u8\M3u8\MediaSegment\MediaSegment;
use Chrisyue\PhpM3u8\M3u8\Playlist;
class Parser
{
private $loader;
public function setLoader(LoaderInterface $loader)
{
$this->loader = $loader;
return $this;
}
public function parseFromUri($uri)
{
if (null === $this->loader) {
throw new \BadMethodCallException('You should set an m3u8 loader first');
}
return $this->parse($this->loader->load($uri));
}
public function parse($content)
{
$data = $this->content2Data($content);
$version = 3;
$mediaSequence = 0;
extract($data); // to $version, $mediaSequence, $targetDuration
$playlist = new Playlist();
foreach ($data['playlist'] as $index => $row) {
$mediaSegment = new MediaSegment(
$row['uri'],
$row['duration'],
$mediaSequence + $index,
!empty($row['isDiscontinuity'])
);
$playlist->add($mediaSegment);
}
return new M3u8($playlist, $version, $targetDuration);
}
private function content2Data($content)
{
$data = array();
$mediaSequence = 0;
$lines = explode("\n", $content);
foreach ($lines as $line) {
if (preg_match('/^#EXT-X-VERSION:(\d+)/', $line, $matches)) {
$data['version'] = $matches[1];
continue;
}
if (preg_match('/^#EXT-X-TARGETDURATION:(\d+)/', $line, $matches)) {
$data['targetDuration'] = +$matches[1];
continue;
}
if (preg_match('/^#EXT-X-MEDIA-SEQUENCE:(\d+)/', $line, $matches)) {
$data['mediaSequence'] = +$matches[1];
continue;
}
if (preg_match('/^#EXT-X-DISCONTINUITY/', $line)) {
$data['playlist'][$mediaSequence]['isDiscontinuity'] = true;
}
if (preg_match('/^#EXTINF:(.+),/', $line, $matches)) {
$data['playlist'][$mediaSequence]['duration'] = +$matches[1];
continue;
}
if (preg_match('/^[^#]+/', $line, $matches)) {
$data['playlist'][$mediaSequence]['uri'] = $matches[0];
++$mediaSequence;
}
}
return $data;
}
}