-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathprogress.go
237 lines (196 loc) · 7.02 KB
/
progress.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
// Copyright (c) Liam Stanley <[email protected]>. All rights reserved. Use of
// this source code is governed by the MIT license that can be found in
// the LICENSE file.
package ytdlp
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
)
var progressPrefix = []byte("progress:")
const progressFormat = "%()j"
type progressData struct {
Info *ExtractedInfo `json:"info"`
Progress struct {
Status ProgressStatus `json:"status"`
TotalBytes int `json:"total_bytes,omitempty"`
TotalBytesEstimate float64 `json:"total_bytes_estimate,omitempty"`
DownloadedBytes int `json:"downloaded_bytes"`
Filename string `json:"filename,omitempty"`
TmpFilename string `json:"tmpfilename,omitempty"`
FragmentIndex int `json:"fragment_index,omitempty"`
FragmentCount int `json:"fragment_count,omitempty"`
// There are technically other fields, but these are the important ones.
} `json:"progress"`
AutoNumber int `json:"autonumber,omitempty"`
VideoAutoNumber int `json:"video_autonumber,omitempty"`
}
type progressHandler struct {
fn ProgressCallbackFunc
mu sync.Mutex
started map[string]time.Time // Used to track multiple independent downloads.
finished map[string]time.Time // Used to track multiple independent downloads.
}
func newProgressHandler(fn ProgressCallbackFunc) *progressHandler {
h := &progressHandler{
fn: fn,
started: make(map[string]time.Time),
finished: make(map[string]time.Time),
}
return h
}
func (h *progressHandler) parse(raw json.RawMessage) {
data := &progressData{}
err := json.Unmarshal(raw, data)
if err != nil {
return
}
cleanJSON(data)
update := ProgressUpdate{
Info: data.Info,
Status: data.Progress.Status,
TotalBytes: data.Progress.TotalBytes,
DownloadedBytes: data.Progress.DownloadedBytes,
FragmentIndex: data.Progress.FragmentIndex,
FragmentCount: data.Progress.FragmentCount,
Filename: data.Progress.Filename,
}
if update.TotalBytes == 0 {
update.TotalBytes = int(data.Progress.TotalBytesEstimate)
}
if update.Filename == "" {
if data.Progress.TmpFilename != "" {
update.Filename = data.Progress.TmpFilename
} else if data.Info.Filename != nil && *data.Info.Filename != "" {
update.Filename = *data.Info.Filename
}
}
uuid := update.uuid()
var ok bool
h.mu.Lock()
update.Started, ok = h.started[uuid]
if !ok {
update.Started = time.Now()
h.started[uuid] = update.Started
}
update.Finished, ok = h.finished[uuid]
if !ok && update.Status.IsCompletedType() {
update.Finished = time.Now()
h.finished[uuid] = update.Finished
}
h.mu.Unlock()
h.fn(update)
}
// ProgressStatus is the status of the download progress.
type ProgressStatus string
func (s ProgressStatus) IsCompletedType() bool {
return s == ProgressStatusError || s == ProgressStatusFinished
}
const (
ProgressStatusStarting ProgressStatus = "starting"
ProgressStatusDownloading ProgressStatus = "downloading"
ProgressStatusPostProcessing ProgressStatus = "post_processing"
ProgressStatusError ProgressStatus = "error"
ProgressStatusFinished ProgressStatus = "finished"
)
// ProgressCallbackFunc is a callback function that is called when (if) we receive
// progress updates from yt-dlp.
type ProgressCallbackFunc func(update ProgressUpdate)
// ProgressUpdate is a point-in-time snapshot of the download progress.
type ProgressUpdate struct {
Info *ExtractedInfo `json:"info"`
// Status is the current status of the download.
Status ProgressStatus `json:"status"`
// TotalBytes is the total number of bytes in the download. If yt-dlp is unable
// to determine the total bytes, this will be 0.
TotalBytes int `json:"total_bytes"`
// DownloadedBytes is the number of bytes that have been downloaded so far.
DownloadedBytes int `json:"downloaded_bytes"`
// FragmentIndex is the index of the current fragment being downloaded.
FragmentIndex int `json:"fragment_index,omitempty"`
// FragmentCount is the total number of fragments in the download.
FragmentCount int `json:"fragment_count,omitempty"`
// Filename is the filename of the video being downloaded, if available. Note that
// this is not necessarily the same as the destination file, as post-processing
// may merge multiple files into one.
Filename string `json:"filename"`
// Started is the time the download started.
Started time.Time `json:"started"`
// Finished is the time the download finished. If the download is still in progress,
// this will be zero. You can validate with IsZero().
Finished time.Time `json:"finished,omitempty"`
}
func (p *ProgressUpdate) uuid() string {
unique := []string{
p.Filename,
p.Info.ID,
}
if p.Info.PlaylistID != nil {
unique = append(unique, *p.Info.PlaylistID)
}
if p.Info.PlaylistIndex != nil {
unique = append(unique, strconv.Itoa(*p.Info.PlaylistIndex))
}
return strings.Join(unique, ":")
}
// Duration returns the duration of the download. If the download is still in progress,
// it will return the time since the download started.
func (p *ProgressUpdate) Duration() time.Duration {
if p.Finished.IsZero() {
return time.Since(p.Started)
}
return p.Finished.Sub(p.Started)
}
// ETA returns the estimated time until the download is complete. If the download is
// complete, or hasn't started yet, it will return 0.
func (p *ProgressUpdate) ETA() time.Duration {
perc := p.Percent()
if perc == 0 || perc == 100 {
return 0
}
return time.Duration(float64(p.Duration().Nanoseconds()) / perc * (100 - perc))
}
// Percent returns the percentage of the download that has been completed. If yt-dlp
// is unable to determine the total bytes, it will return 0.
func (p *ProgressUpdate) Percent() float64 {
if p.Status.IsCompletedType() {
return 100
}
if p.TotalBytes == 0 {
return 0
}
return float64(p.DownloadedBytes) / float64(p.TotalBytes) * 100
}
// PercentString is like Percent, but returns a string representation of the percentage.
func (p *ProgressUpdate) PercentString() string {
return fmt.Sprintf("%.2f%%", p.Percent())
}
// ProgressFunc can be used to register a callback function that will be called when
// yt-dlp sends progress updates. The callback function will be called with any information
// that yt-dlp is able to provide, including sending separate updates for each file, playlist,
// etc that may be downloaded.
// - See [Command.UnsetProgressFunc], for unsetting the progress function.
func (c *Command) ProgressFunc(frequency time.Duration, fn ProgressCallbackFunc) *Command {
if frequency < 100*time.Millisecond {
frequency = 100 * time.Millisecond
}
c.Progress().
ProgressDelta(frequency.Seconds()).
ProgressTemplate(string(progressPrefix) + progressFormat).
Newline()
c.mu.Lock()
c.progress = newProgressHandler(fn)
c.mu.Unlock()
return c
}
// UnsetProgressFunc can be used to unset the progress function that was previously set
// with [Command.ProgressFunc].
func (c *Command) UnsetProgressFunc() *Command {
c.mu.Lock()
c.progress = nil
c.mu.Unlock()
return c
}