summaryrefslogtreecommitdiff
path: root/protected/Video.php
blob: 31494827a5604b73cb1abaa51c12285a3318b2e3 (plain)
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
<?php
/**
 * Created by IntelliJ IDEA.
 * User: root
 * Date: 8/15/13
 * Time: 11:17 AM
 * To change this template use File | Settings | File Templates.
 */

class Video {

    private $_cache = null;

    public function __construct(){
       $this->_cache = new Cache();
    }

    public function playVideo($url){
         $id = $this->_cache->urlToId($url);

        if($this->_cache->isCached($id)){
             $filePath = Settings::$CachePath . DIRECTORY_SEPARATOR .$id;
             $this->playFileVideo($filePath);
        }else{

            Async::createAsyncRequest("/async.php", array(
              "password" => Settings::$DeveloperPassword,
               "url" => $url,
               "method" => "cacheVideo"
            ));

            $this->playHttpVideo($url);
        }
    }

    public function playFileVideo($filePath){

        $path = $filePath;

        $size=filesize($path);

        $fm=@fopen($path,'rb');
        if(!$fm) {
            // You can also redirect here
            header ("HTTP/1.0 404 Not Found");
            die();
        }

        $begin=0;
        $end=$size;

        if(isset($_SERVER['HTTP_RANGE'])) {
            if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
                $begin=intval($matches[0]);
                if(!empty($matches[1])) {
                    $end=intval($matches[1]);
                }
            }
        }

        if($begin>0||$end<$size)
            header('HTTP/1.0 206 Partial Content');
        else
            header('HTTP/1.0 200 OK');

        header("Content-Type: video/mp4");
        header('Accept-Ranges: bytes');
        header('Content-Length:'.($end-$begin));
        header("Content-Disposition: inline;");
        header("Content-Range: bytes $begin-$end/$size");
        header("Content-Transfer-Encoding: binary\n");
        header('Connection: close');

        $cur=$begin;
        fseek($fm,$begin,0);

        while(!feof($fm)&&$cur<$end&&(connection_status()==0))
        { print fread($fm,min(1024*16,$end-$cur));
            $cur+=1024*16;
            usleep(1000);
        }
        die();

    }

    public function playHttpVideo($url){

       $command = Settings::$PythonCommand . " " . Settings::$BasePath."protected" ." play_online_video.cgi";

       header("Location: /play_video_online.cgi?url=$url");

    }


}