-
Notifications
You must be signed in to change notification settings - Fork 0
/
remotFile.go
86 lines (78 loc) · 1.75 KB
/
remotFile.go
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
package gmp4
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
)
//RemoteVideo define a web video
type RemoteVideo struct {
url *url.URL
timeout time.Duration
header http.Header
mvhdBox
}
// NewRemote return a RemoteVideo object
func NewRemote(rawurl string) (*RemoteVideo, error) {
if !strings.Contains(rawurl, "mp4") {
return nil, fmt.Errorf("%s is invalid\n make sure the type of url resource is mp4 ", rawurl)
}
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return &RemoteVideo{url: u}, nil
}
// SetHeader can manually set webClient cookie UA etc
func (r *RemoteVideo) SetHeader(h http.Header) {
r.header = h
}
// SetTimeout can manually set webClient timeout
func (r *RemoteVideo) SetTimeout(time time.Duration) {
r.timeout = time
}
func (r *RemoteVideo) getMvhdBox() mvhdBox {
return r.mvhdBox
}
func (r *RemoteVideo) collectData() {
client := &http.Client{Timeout: r.timeout}
req, err := http.NewRequest("GET", r.url.String(), nil)
if err != nil {
panic("Request build failed")
}
if r.header != nil {
req.Header = r.header
}
var (
i = 1
skip = 0
)
for {
//Split video to receive quickly
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", (i-1)*128+skip, i*128+skip))
resp, err := client.Do(req)
//Handle resource is not mp4
if resp.Header.Get("Content-Type") != "video/mp4" {
panic(r.url.String() + "%s is invalid resource")
}
if err != nil {
log.Println("remoteFile.go:send request failed!", err)
continue
}
body, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
switch n, cas := check(body); cas {
case "mvhd":
r.metadataIndex = n
r.metadata = body
return
case "mdat":
skip = int(byteSliceToInt(body[n-5 : n-1]))
default:
i++
}
}
}