forked from plexdrive/plexdrive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.go
238 lines (195 loc) · 5.43 KB
/
buffer.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"fmt"
"io/ioutil"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
. "github.com/claudetech/loggo/default"
"github.com/orcaman/concurrent-map"
)
var instances cmap.ConcurrentMap
var chunkPath string
var chunkSize int64
var chunkDirMaxSize int64
func init() {
instances = cmap.New()
}
// Buffer is a buffered stream
type Buffer struct {
numberOfInstances int
client *http.Client
object *APIObject
tempDir string
preload bool
chunkDir string
}
// GetBufferInstance gets a singleton instance of buffer
func GetBufferInstance(client *http.Client, object *APIObject) (*Buffer, error) {
if !instances.Has(object.ObjectID) {
i, err := newBuffer(client, object)
if nil != err {
return nil, err
}
instances.Set(object.ObjectID, i)
}
instance, ok := instances.Get(object.ObjectID)
// if buffer allocation failed due to race conditions it will try to fetch a new one
if !ok {
i, err := GetBufferInstance(client, object)
if nil != err {
return nil, err
}
instance = i
}
instance.(*Buffer).numberOfInstances++
return instance.(*Buffer), nil
}
// SetChunkPath sets the global chunk path
func SetChunkPath(path string) {
chunkPath = path
}
// SetChunkSize sets the global chunk size
func SetChunkSize(size int64) {
chunkSize = size
}
// SetChunkDirMaxSize sets the maximum size of the chunk directory
func SetChunkDirMaxSize(size int64) {
chunkDirMaxSize = size
}
// NewBuffer creates a new buffer instance
func newBuffer(client *http.Client, object *APIObject) (*Buffer, error) {
Log.Infof("Starting playback of %v", object.Name)
Log.Debugf("Creating buffer for object %v", object.ObjectID)
tempDir := filepath.Join(chunkPath, object.ObjectID)
if err := os.MkdirAll(tempDir, 0777); nil != err {
Log.Debugf("%v", err)
return nil, fmt.Errorf("Could not create temp path for object %v", object.ObjectID)
}
if 0 == chunkSize {
Log.Debugf("ChunkSize was 0, setting to default (5 MB)")
chunkSize = 5 * 1024 * 1024
}
buffer := Buffer{
numberOfInstances: 0,
client: client,
object: object,
tempDir: tempDir,
preload: true,
}
return &buffer, nil
}
// Close all handles
func (b *Buffer) Close() error {
b.numberOfInstances--
if 0 == b.numberOfInstances {
Log.Infof("Stopping playback of %v", b.object.Name)
Log.Debugf("Stop buffering for object %v", b.object.ObjectID)
b.preload = false
instances.Remove(b.object.ObjectID)
}
return nil
}
// ReadBytes on a specific location
func (b *Buffer) ReadBytes(start, size int64, isPreload bool) ([]byte, error) {
fOffset := start % chunkSize
offset := start - fOffset
offsetEnd := offset + chunkSize
Log.Debugf("Getting object %v bytes %v - %v (is preload: %v)", b.object.ObjectID, offset, offsetEnd, isPreload)
filename := filepath.Join(b.tempDir, strconv.Itoa(int(offset)))
if f, err := os.Open(filename); nil == err {
defer f.Close()
buf := make([]byte, size)
if n, err := f.ReadAt(buf, fOffset); nil == err && n > 0 {
Log.Debugf("Found object %v bytes %v - %v in cache", b.object.ObjectID, offset, offsetEnd)
// update the last modified time for files that are often in use
if err := os.Chtimes(filename, time.Now(), time.Now()); nil != err {
Log.Warningf("Could not update last modified time for %v", filename)
}
return buf[:size], nil
}
}
if chunkDirMaxSize > 0 {
if err := cleanChunkDir(chunkPath); nil != err {
Log.Debugf("%v", err)
return nil, fmt.Errorf("Could not delete oldest chunk")
}
}
Log.Debugf("Requesting object %v bytes %v - %v from API", b.object.ObjectID, offset, offsetEnd)
req, err := http.NewRequest("GET", b.object.DownloadURL, nil)
if nil != err {
return nil, err
}
req.Header.Add("Range", fmt.Sprintf("bytes=%v-%v", offset, offsetEnd))
Log.Tracef("Sending HTTP Request %v", req)
res, err := b.client.Do(req)
if nil != err {
return nil, err
}
if res.StatusCode != 206 {
return nil, fmt.Errorf("Wrong status code %v", res)
}
bytes, err := ioutil.ReadAll(res.Body)
if nil != err {
return nil, err
}
f, err := os.Create(filename)
if nil != err {
return nil, err
}
defer f.Close()
_, err = f.Write(bytes)
if nil != err {
return nil, err
}
if !isPreload && b.preload && uint64(offsetEnd) < b.object.Size {
go func() {
b.ReadBytes(offsetEnd+1, size, true)
}()
}
return bytes[fOffset:int64(math.Min(float64(fOffset+size), float64(len(bytes))))], nil
}
// cleanChunkDir checks if the chunk folder is grown to big and clears the oldest file if necessary
func cleanChunkDir(chunkPath string) error {
chunkDirSize, err := dirSize(chunkPath)
if nil != err {
return err
}
if chunkDirSize+chunkSize > chunkDirMaxSize {
if err := deleteOldestFile(chunkPath); nil != err {
return err
}
}
return nil
}
// deleteOldestFile deletes the oldest file in the directory
func deleteOldestFile(path string) error {
var fpath string
lastMod := time.Now()
err := filepath.Walk(path, func(file string, info os.FileInfo, err error) error {
if !info.IsDir() {
modTime := info.ModTime()
if modTime.Before(lastMod) {
lastMod = modTime
fpath = file
}
}
return err
})
os.Remove(fpath)
return err
}
// dirSize gets the total directory size
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}