-
Notifications
You must be signed in to change notification settings - Fork 97
/
Info.go
1489 lines (1263 loc) · 38 KB
/
Info.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/dannav/hhmmss"
"github.com/xhit/go-str2duration/v2"
)
const (
DtypeAudio = "audio"
DtypeVideo = "video"
AudioItag = 140
AudioOnlyQuality = 0
BufferSize = 8192
DefaultFilenameFormat = "%(title)s-%(id)s"
// 5 days in seconds
LiveMaximumSeekable = 432000
)
type VideoItag struct {
H264 int
VP9 int
}
// https://gist.github.com/AgentOak/34d47c65b1d28829bb17c24c04a0096f
var (
FilenameFormatBlacklist = []string{
"description",
}
VideoLabelItags = map[string]VideoItag{
"audio_only": {H264: 0, VP9: 0},
"144p": {H264: 160, VP9: 278},
"240p": {H264: 133, VP9: 242},
"360p": {H264: 134, VP9: 243},
"480p": {H264: 135, VP9: 244},
"720p": {H264: 136, VP9: 247},
"720p60": {H264: 298, VP9: 302},
"1080p": {H264: 137, VP9: 248},
"1080p60": {H264: 299, VP9: 303},
"1440p": {H264: 264, VP9: 271},
"1440p60": {H264: 304, VP9: 308},
"2160p": {H264: 266, VP9: 313},
"2160p60": {H264: 305, VP9: 315},
}
VideoQualities = []string{
"audio_only",
"144p",
"240p",
"360p",
"480p",
"720p",
"720p60",
"1080p",
"1080p60",
"1440p",
"1440p60",
"2160p",
"2160p60",
}
)
/*
Simple class to more easily keep track of what fields are available for
file name formatting
*/
type FormatInfo map[string]string
/*
Metadata for the final file
*/
type MetaInfo map[string]string
/*
Info to be sent through the progress queue
*/
type ProgressInfo struct {
Itag int
ByteCount int
MaxSeq int
StartFrag int
}
/*
Fragment information/data
*/
type Fragment struct {
Seq int
FileName string
XHeadSeqNum int
Data *bytes.Buffer
Slow bool
MimeType string
}
type seqChanInfo struct {
CurSequence int
MaxSequence int
}
/*
For sharing state between some functions used for downloading threads
*/
type fragThreadState struct {
Name string
BaseFilePath string
DataType string
SeqNum int
MaxSeq int
Tries int
FullRetries int
Is403 bool
ToFile bool
SleepTime time.Duration
}
type MediaDLInfo struct {
sync.RWMutex
ActiveJobs int
DownloadURL string
BasePath string
DataType string
Finished bool
URLHost string
}
/*
State for resumable downloading
*/
type DownloadState struct {
StartFrag int
Fragments int
Size int64
TempDir string
File string `json:"-"`
}
/*
Miscellaneous information
*/
type DownloadInfo struct {
sync.RWMutex
FormatInfo FormatInfo
Metadata MetaInfo
CookiesURL *url.URL
Ytcfg *YTCFG
PoToken string
Stopping bool
InProgress bool
Live bool
VP9 bool
H264 bool
Unavailable bool
GVideoDDL bool
FragFiles bool
LiveURL bool
AudioOnly bool
VideoOnly bool
MembersOnly bool
InfoPrinted bool
DisableSaveState bool
LiveFromVal string
LiveFromSq int
Thumbnail string
VideoID string
URL string
SelectedQuality string
Status string
CaptureDurationSecs int
StartDelaySecs int
FragMaxTries uint
Wait int
Quality int
RetrySecs int
Jobs int
TargetDuration int
LastSq int
LastUpdated time.Time
MDLInfo map[string]*MediaDLInfo
DLState map[int]*DownloadState
FileMode os.FileMode
DirMode os.FileMode
}
func NewDownloadInfo() *DownloadInfo {
return &DownloadInfo{
FragFiles: true,
Wait: ActionAsk,
Quality: -1,
Jobs: 1,
TargetDuration: 5,
FormatInfo: NewFormatInfo(),
Metadata: NewMetaInfo(),
MDLInfo: map[string]*MediaDLInfo{
DtypeVideo: {},
DtypeAudio: {},
},
DLState: make(map[int]*DownloadState),
}
}
func NewFragThreadState(name, baseFPath, dataType string, toFile bool, sleepTime time.Duration) *fragThreadState {
return &fragThreadState{
Name: name,
BaseFilePath: baseFPath,
DataType: dataType,
ToFile: toFile,
SleepTime: sleepTime,
}
}
func NewFormatInfo() FormatInfo {
return FormatInfo{
"id": "",
"title": "",
"channel_id": "",
"channel": "",
"upload_date": "",
"start_date": "",
"publish_date": "",
"description": "",
"url": "",
}
}
func NewMetaInfo() MetaInfo {
return MetaInfo{
"title": "%(title)s",
"artist": "%(channel)s",
"date": "%(upload_date)s",
"comment": "%(url)s\n\n%(description)s",
}
}
func (di *DownloadInfo) IsStopping() bool {
di.RLock()
defer di.RUnlock()
return di.Stopping
}
func (di *DownloadInfo) Stop() {
di.Lock()
defer di.Unlock()
di.Stopping = true
di.SetFinished(DtypeAudio)
di.SetFinished(DtypeVideo)
}
func (di *DownloadInfo) IsLive() bool {
di.RLock()
defer di.RUnlock()
return di.Live
}
func (di *DownloadInfo) IsUnavailable() bool {
di.RLock()
defer di.RUnlock()
return di.Unavailable
}
func (di *DownloadInfo) IsGVideoDDL() bool {
di.RLock()
defer di.RUnlock()
return di.GVideoDDL
}
func (di *DownloadInfo) GetActiveJobCount(dataType string) int {
di.MDLInfo[dataType].RLock()
defer di.MDLInfo[dataType].RUnlock()
return di.MDLInfo[dataType].ActiveJobs
}
func (di *DownloadInfo) IncrementJobs(dataType string) {
di.MDLInfo[dataType].Lock()
defer di.MDLInfo[dataType].Unlock()
di.MDLInfo[dataType].ActiveJobs += 1
}
func (di *DownloadInfo) DecrementJobs(dataType string) {
di.MDLInfo[dataType].Lock()
defer di.MDLInfo[dataType].Unlock()
di.MDLInfo[dataType].ActiveJobs -= 1
}
func (di *DownloadInfo) GetDownloadUrl(dataType string) string {
di.MDLInfo[dataType].RLock()
defer di.MDLInfo[dataType].RUnlock()
return di.MDLInfo[dataType].DownloadURL
}
func (di *DownloadInfo) SetDownloadUrl(dataType, dlURL string) {
di.MDLInfo[dataType].Lock()
defer di.MDLInfo[dataType].Unlock()
purl, err := url.Parse(dlURL)
if err == nil {
di.MDLInfo[dataType].URLHost = purl.Host
}
di.MDLInfo[dataType].DownloadURL = dlURL
}
func (di *DownloadInfo) GetDownloadUrlHost(dataType string) string {
di.MDLInfo[dataType].RLock()
defer di.MDLInfo[dataType].RUnlock()
return di.MDLInfo[dataType].URLHost
}
func (di *DownloadInfo) GetBaseFilePath(dataType string) string {
di.MDLInfo[dataType].RLock()
defer di.MDLInfo[dataType].RUnlock()
return di.MDLInfo[dataType].BasePath
}
func (di *DownloadInfo) SetBaseFilePath(dataType, fpath string) {
di.MDLInfo[dataType].Lock()
defer di.MDLInfo[dataType].Unlock()
di.MDLInfo[dataType].BasePath = fpath
}
func (di *DownloadInfo) SetFinished(dataType string) {
di.MDLInfo[dataType].Lock()
defer di.MDLInfo[dataType].Unlock()
di.MDLInfo[dataType].Finished = true
}
func (di *DownloadInfo) IsFinished(dataType string) bool {
di.MDLInfo[dataType].RLock()
defer di.MDLInfo[dataType].RUnlock()
return di.MDLInfo[dataType].Finished
}
func (di *DownloadInfo) GetTimeSinceUpdated() time.Duration {
di.RLock()
defer di.RUnlock()
return time.Since(di.LastUpdated)
}
func (fi FormatInfo) SetInfo(player_response *PlayerResponse) {
pmfr := player_response.Microformat.PlayerMicroformatRenderer
vid := player_response.VideoDetails.VideoID
startDate := strings.ReplaceAll(pmfr.LiveBroadcastDetails.StartTimestamp, "-", "")
publishDate := strings.ReplaceAll(pmfr.PublishDate, "-", "")
url := fmt.Sprintf("https://www.youtube.com/watch?v=%s", vid)
if len(startDate) > 0 {
startDate = startDate[:8]
}
fi["id"] = vid
fi["url"] = url
fi["title"] = strings.TrimSpace(player_response.VideoDetails.Title)
fi["channel_id"] = player_response.VideoDetails.ChannelID
fi["channel"] = player_response.VideoDetails.Author
fi["upload_date"] = startDate
fi["start_date"] = startDate
fi["publish_date"] = publishDate
fi["description"] = strings.TrimSpace(player_response.VideoDetails.ShortDescription)
}
func (mi MetaInfo) SetInfo(fi FormatInfo) {
for k, v := range mi {
val, err := FormatPythonMapString(v, fi)
if err != nil {
// ignore and just leave unformatted
continue
}
mi[k] = val
}
}
func (di *DownloadInfo) printChannelAndTitle(pr *PlayerResponse) {
if di.InfoPrinted {
return
}
if len(pr.VideoDetails.Title) == 0 || len(pr.VideoDetails.Author) == 0 {
return
}
LogGeneral("Channel: %s\n", pr.VideoDetails.Author)
LogGeneral("Video Title: %s\n", pr.VideoDetails.Title)
di.InfoPrinted = true
}
func (di *DownloadInfo) printStatusWithoutLock() {
if loglevel >= LoglevelError {
fmt.Print(di.Status)
}
}
func (di *DownloadInfo) SetStatus(status string) {
di.Lock()
defer di.Unlock()
di.Status = status
di.printStatusWithoutLock()
}
func (di *DownloadInfo) PrintStatus() {
di.RLock()
defer di.RUnlock()
di.printStatusWithoutLock()
}
func (di *DownloadInfo) SaveState(itag int) {
if di.DisableSaveState || len(di.DLState[itag].File) == 0 {
return
}
data, err := json.Marshal(di.DLState[itag])
if err != nil {
LogWarn("Error when saving state: %s", err)
return
}
err = os.WriteFile(di.DLState[itag].File, data, di.FileMode)
if err != nil {
LogWarn("Error when saving state: %s", err)
return
}
}
// Ask if the user wants to wait for a scheduled stream to start and then record it
func (di *DownloadInfo) AskWaitForStream() bool {
LogGeneral("%s\n%s\n",
fmt.Sprintf("%s is likely a future scheduled livestream.", di.URL),
"Would you like to wait for the scheduled start time, poll until it starts, or not wait?",
)
choice := strings.ToLower(GetUserInput("wait/poll/[no]: "))
if strings.HasPrefix(choice, "wait") {
return true
} else if strings.HasPrefix(choice, "poll") {
secs := GetUserInput("Input poll interval in seconds (minimum 15): ")
s, err := strconv.Atoi(secs)
if err != nil || s < DefaultPollTime {
s = DefaultPollTime
}
di.RetrySecs = s
return true
}
return false
}
func (di *DownloadInfo) GetGvideoUrl(dataType string) {
for {
gvUrl := GetUserInput(fmt.Sprintf("Please enter the %s url, or nothing to skip: ", dataType))
if len(gvUrl) == 0 {
return
}
newUrl, itag := ParseGvideoUrl(gvUrl, dataType)
if len(newUrl) == 0 {
continue
}
if dataType == DtypeVideo {
di.Quality = itag
}
if (dataType == DtypeAudio && itag == AudioItag) ||
(dataType == DtypeVideo && itag != AudioItag) {
di.SetDownloadUrl(dataType, newUrl)
break
} else {
LogGeneral("URL given does not appear to be appropriate for the data type needed.")
}
}
}
func (di *DownloadInfo) ParseLiveFromStrVal() error {
if di.LiveFromVal == "" {
return nil
}
if strings.ToLower(di.LiveFromVal) == "now" {
// --live-from now
// Seek to current sequence number
di.LiveFromSq = di.LastSq
LogGeneral("Starting download from current time")
} else {
durationVal := strings.TrimPrefix(di.LiveFromVal, "-") // Removes negative symbol from start of duration string
// Try to parse the value as a duration string
duration, err := str2duration.ParseDuration(durationVal)
if err != nil {
// Try to parse the value as a HH:MM:SS string
duration, err = hhmmss.Parse(durationVal)
if err != nil {
LogError("Unable to parse value as either a duration or a time string: %v", err)
return err
}
}
secondsTotal := duration.Seconds()
fragDur := float64(di.TargetDuration)
secondsRoundedToFragLength := int(math.Ceil(secondsTotal/fragDur) * fragDur) // Rounds up to next frag interval time
noOfFragsToJump := secondsRoundedToFragLength / di.TargetDuration
if strings.HasPrefix(di.LiveFromVal, "-") {
// --live-from negative value
// Seek to a sequence number in the past
// Invalid time specification (too short or too long)
if secondsTotal < 0 || secondsTotal > LiveMaximumSeekable {
LogError("Invalid duration specified '%s'. (Maximum video seek time is %d days)", di.LiveFromVal, (LiveMaximumSeekable / 60 / 60 / 24))
return errors.New("invalid duration specified")
}
// If the stream hasn't been live long enough for the specified duration
if noOfFragsToJump > di.LastSq {
streamLength := di.LastSq * di.TargetDuration
curStreamDuration := SecondsToDurationAndTimeStr(streamLength)
LogError("Invalid duration specified. The stream has not been live for that long [Live for %s].", curStreamDuration)
return errors.New("invalid duration specified")
}
di.LiveFromSq = di.LastSq - noOfFragsToJump
LogGeneral("Jumping back %d seconds from now, and starting to download from that time.", secondsRoundedToFragLength)
LogDebug("Jumping back %d frags. Will start from sequence %d [current is %d].", noOfFragsToJump, di.LiveFromSq, di.LastSq)
} else {
// --live-from positive value
// Calculate the sequence number of the specified stream time to start from.
maxSq := di.LastSq
targetStartFrag := noOfFragsToJump
// Stream hasn't been live long enough
if di.LastSq < targetStartFrag {
streamLength := di.LastSq * di.TargetDuration
curStreamDuration := SecondsToDurationAndTimeStr(streamLength)
errStr := fmt.Errorf("invalid duration specified. the stream has not been live for that long [live for %s]", curStreamDuration)
return errors.New(errStr.Error())
} else {
// Make sure the Start Frag is within the 5 day limit.
if targetStartFrag < (di.LastSq - LiveMaximumSeekable) {
LogError("YT only retains the livestream 5 days past for seeking, your --live-from value of '%s' is not valid.", di.LiveFromVal)
// Calculate how long the stream has been live for
streamLiveTime := di.LastSq * di.TargetDuration
minSeekTime := streamLiveTime - LiveMaximumSeekable
LogError("You must specify a --live-from value between: %s and %s", SecondsToDurationAndTimeStr(minSeekTime), SecondsToDurationAndTimeStr(streamLiveTime))
return errors.New("value is not valid for stream duration")
}
di.LiveFromSq = targetStartFrag
startTimeStr := SecondsToDurationAndTimeStr(di.LiveFromSq * di.TargetDuration)
totalTimeToGrabStr := SecondsToDurationAndTimeStr((maxSq - di.LiveFromSq) * di.TargetDuration)
LogGeneral("Starting from stream time '%s' and grabbing '%s' of content (and counting).", startTimeStr, totalTimeToGrabStr)
LogDebug("Starting from sequence %d [max right now is %d]", di.LiveFromSq, maxSq)
}
}
}
return nil
}
func (di *DownloadInfo) ParseInputUrl() error {
parsedUrl, err := url.Parse(di.URL)
if err != nil {
return err
}
lowerHost := strings.ToLower(parsedUrl.Host)
lowerHost = strings.TrimPrefix(lowerHost, "www.")
lowerPath := strings.ToLower(parsedUrl.EscapedPath())
parsedQuery := parsedUrl.Query()
if lowerHost == "youtube.com" {
if strings.HasPrefix(lowerPath, "/watch") {
if _, ok := parsedQuery["v"]; !ok {
return errors.New("youtube URL missing video ID")
}
di.VideoID = parsedQuery.Get("v")
return nil
} else if strings.HasPrefix(lowerPath, "/channel/") ||
strings.HasPrefix(lowerPath, "/c/") ||
strings.HasPrefix(lowerPath, "/user/") ||
strings.HasPrefix(lowerPath, "/@") {
// The URL can be polled and the stream can change depending on what
// the channel schedules. Useful for set-and-forget
chanSlashIdx := strings.Index(lowerPath[1:], "/") + 1
noChanPath := lowerPath[chanSlashIdx:]
// Check if we were given the channel url on a sub page
// Remove that part from the URL so we can append /live to it after
if strings.LastIndex(noChanPath, "/") > 0 {
lastSlash := strings.LastIndex(di.URL, "/")
di.URL = di.URL[:lastSlash]
}
di.URL = fmt.Sprintf("%s/live", di.URL)
di.LiveURL = true
return nil
} else if strings.HasPrefix(lowerPath, "/live/") {
di.VideoID = strings.TrimPrefix(parsedUrl.EscapedPath(), "/live/")
return nil
} else if strings.HasPrefix(lowerPath, "/shorts/") {
di.VideoID = strings.TrimPrefix(parsedUrl.EscapedPath(), "/shorts/")
return nil
}
} else if lowerHost == "youtu.be" {
di.VideoID = strings.TrimLeft(parsedUrl.EscapedPath(), "/")
return nil
} else if strings.HasSuffix(lowerHost, ".googlevideo.com") {
if _, ok := parsedQuery["noclen"]; !ok {
return errors.New("given Google Video URL is not for a fragmented stream")
}
di.GVideoDDL = true
id := parsedQuery.Get("id")
dotIdx := strings.LastIndex(id, ".")
id = id[:dotIdx]
di.VideoID = id
di.FormatInfo["id"] = di.VideoID
sqIdx := strings.Index(di.URL, "&sq=")
itag, err := strconv.Atoi(parsedQuery.Get("itag"))
if err != nil {
return fmt.Errorf("error parsing itag parameter of Google Video URL: %s", err)
}
if sqIdx < 0 {
return errors.New("could not find 'sq' parameter in given Google Video URL")
}
if itag == AudioItag {
if len(di.GetDownloadUrl(DtypeAudio)) == 0 {
di.SetDownloadUrl(DtypeAudio, di.URL[:sqIdx]+"&sq=%d")
}
if len(di.GetDownloadUrl(DtypeVideo)) == 0 && !di.AudioOnly {
di.GetGvideoUrl(DtypeVideo)
}
} else {
if len(di.GetDownloadUrl(DtypeVideo)) == 0 {
di.SetDownloadUrl(DtypeVideo, di.URL[:sqIdx]+"&sq=%d")
}
if len(di.GetDownloadUrl(DtypeAudio)) == 0 && !di.VideoOnly {
di.GetGvideoUrl(DtypeAudio)
}
}
di.Quality = itag
return nil
}
return fmt.Errorf("%s is not a known valid youtube URL", di.URL)
}
/*
Get download URLs either from the DASH manifest or from the adaptiveFormats.
Prioritize DASH manifest if it is available.
Attempts to grab from the Web API player response as well as desktop,
favouring Web API. Any formats not found in the Web API are looked for in the
desktop player response.
*/
func (di *DownloadInfo) GetDownloadUrls(pr *PlayerResponse) map[int]string {
urls := make(map[int]string)
WebPlayerResponse, err := di.DownloadWebPlayerResponse()
if err != nil {
LogDebug("Error getting Web API player response: %s", err.Error())
} else {
if len(WebPlayerResponse.StreamingData.DashManifestURL) > 0 {
LogDebug("Retrieving URLs from Web API DASH manifest")
manifest := DownloadData(WebPlayerResponse.StreamingData.DashManifestURL)
if len(manifest) > 0 {
// we store the LastSq to calculate 5 days past
urls, di.LastSq = GetUrlsFromManifest(manifest, di.PoToken)
}
for itag := range urls {
LogTrace("Setting itag %d from Web API DASH manifest", itag)
}
}
if len(WebPlayerResponse.StreamingData.AdaptiveFormats) > 0 {
LogDebug("Retrieving URLs from Web API adaptive formats")
for _, fmt := range WebPlayerResponse.StreamingData.AdaptiveFormats {
if len(fmt.URL) == 0 {
continue
}
if _, ok := urls[fmt.Itag]; ok { // format exists already
continue
}
urls[fmt.Itag] = strings.ReplaceAll(fmt.URL, "%", "%%") + "&sq=%d"
LogTrace("Setting itag %d from Web API adaptive formats", fmt.Itag)
}
}
}
if len(pr.StreamingData.DashManifestURL) > 0 {
LogDebug("Retrieving URLs from web DASH manifest")
manifest := DownloadData(pr.StreamingData.DashManifestURL)
if len(manifest) > 0 {
// we store the LastSq to calculate 5 days past
dashUrls, lastSq := GetUrlsFromManifest(manifest, di.PoToken)
if lastSq > di.LastSq {
di.LastSq = lastSq
}
for itag, url := range dashUrls {
if _, ok := urls[itag]; ok { // format exists already
continue
}
urls[itag] = url
LogTrace("Setting itag %d from web adaptive formats", itag)
}
}
}
if len(pr.StreamingData.AdaptiveFormats) > 0 {
LogDebug("Retrieving URLs from web adaptive formats")
for _, fmt := range pr.StreamingData.AdaptiveFormats {
if len(fmt.URL) == 0 {
continue
}
if _, ok := urls[fmt.Itag]; ok { // format exists already
continue
}
urls[fmt.Itag] = strings.ReplaceAll(fmt.URL, "%", "%%") + "&sq=%d"
LogTrace("Setting itag %d from web adaptive formats", fmt.Itag)
}
}
return urls
}
func (di *DownloadInfo) ParseCaptureDurationStrVal(durationVal string) error {
if durationVal == "" {
return nil
}
// Try to parse the value as a duration string
duration, err := str2duration.ParseDuration(durationVal)
if err != nil {
// Try to parse the value as a HH:MM:SS string
duration, err = hhmmss.Parse(durationVal)
if err != nil {
LogError("Unable to parse value as either a Duration or a Time String: %v", err)
return errors.New("invalid duration string")
}
}
di.CaptureDurationSecs = int(duration.Seconds())
return nil
}
func (di *DownloadInfo) ParseStartDelayStrVal(durationVal string) error {
if durationVal == "" {
return nil
}
// Try to parse the value as a duration string
duration, err := str2duration.ParseDuration(durationVal)
if err != nil {
// Try to parse the value as a HH:MM:SS string
duration, err = hhmmss.Parse(durationVal)
if err != nil {
LogError("Unable to parse value as either a Duration or a Time String: %v", err)
return errors.New("invalid duration string")
}
}
di.StartDelaySecs = int(duration.Seconds())
return nil
}
// Get necessary video info such as video/audio URLs
func (di *DownloadInfo) GetVideoInfo() bool {
di.Lock()
defer di.Unlock()
/*
No point retrieving information if we know it's not available, or there
is nothing useful to be gotten
*/
if di.GVideoDDL || di.Stopping || di.Unavailable {
return false
}
// Almost nothing we care about is likely to change in 15 seconds
delta := time.Since(di.LastUpdated)
if delta < (DefaultPollTime * time.Second) {
return false
}
retrieved, pr, selQaulities := di.GetPlayablePlayerResponse()
di.LastUpdated = time.Now()
if retrieved == PlayerResponseNotFound {
di.Live = false
di.Unavailable = true
return false
} else if retrieved == PlayerResponseNotUsable {
return false
}
streamData := pr.StreamingData
pmfr := pr.Microformat.PlayerMicroformatRenderer
isLive := pmfr.LiveBroadcastDetails.IsLiveNow
targetDur := int(streamData.AdaptiveFormats[0].TargetDurationSec)
if targetDur > 0 {
di.TargetDuration = targetDur
}
dlUrls := di.GetDownloadUrls(pr)
if len(dlUrls) == 0 {
LogError("No download URLs found")
return false
}
if di.Quality < 0 {
var qualities []string
qualities = append(qualities, "audio_only")
found := false
for _, qlabel := range VideoQualities {
videoItag := VideoLabelItags[qlabel]
_, vp9Ok := dlUrls[videoItag.VP9]
_, h264Ok := dlUrls[videoItag.H264]
if Contains(qualities, qlabel) || (!vp9Ok && !h264Ok) {
continue
}
qualities = append(qualities, qlabel)
}
for !found {
if len(selQaulities) == 0 {
selQaulities = GetQualityFromUser(qualities, false)
}
for _, q := range selQaulities {
q = strings.TrimSpace(q)
if q == "best" {
q = qualities[len(qualities)-1]
} else if q == "audio" {
q = "audio_only"
}
videoItag := VideoLabelItags[q]
aonly := videoItag.VP9 == AudioOnlyQuality
if !di.VideoOnly {
di.SetDownloadUrl(DtypeAudio, dlUrls[AudioItag])
}
if aonly {
di.Quality = AudioOnlyQuality
di.SetDownloadUrl(DtypeVideo, "")
found = true
break
}
_, vp9Ok := dlUrls[videoItag.VP9]
_, h264Ok := dlUrls[videoItag.H264]
if vp9Ok && (di.VP9 || !h264Ok) && !di.H264 { // Sometimes a quality is VP9 only apparently
di.SetDownloadUrl(DtypeVideo, dlUrls[videoItag.VP9])
di.Quality = videoItag.VP9
found = true
LogGeneral("Selected quality: %s (VP9)\n", q)
break
} else if h264Ok {
di.SetDownloadUrl(DtypeVideo, dlUrls[videoItag.H264])
di.Quality = videoItag.H264
found = true
LogGeneral("Selected quality: %s (h264)\n", q)
break
}
}
/*
None of the qualities the user gave were available
Should only be possible if they chose to wait for a stream
and chose only qualities that the streamer ended up not using
i.e. 1080p60/720p60 when the stream is only available in 30 FPS
*/
if !found {
LogGeneral("The qualities you selected ended up unavailable for this stream")
LogGeneral("You will now have the option to select from the available qualities")
selQaulities = selQaulities[len(selQaulities):]
}
}
} else {
aonly := di.Quality == AudioOnlyQuality
_, audioOk := dlUrls[AudioItag]
if !di.VideoOnly && audioOk && IsFragmented(dlUrls[AudioItag]) {
di.SetDownloadUrl(DtypeAudio, dlUrls[AudioItag])
}
if !aonly {
_, vidOk := dlUrls[di.Quality]
if vidOk && IsFragmented(dlUrls[di.Quality]) {
di.SetDownloadUrl(DtypeVideo, dlUrls[di.Quality])
}
}
}
if !di.InProgress {
LogGeneral("Stream started at time %s", pmfr.LiveBroadcastDetails.StartTimestamp)
di.FormatInfo.SetInfo(pr)
di.Metadata.SetInfo(di.FormatInfo)
if len(pmfr.Thumbnail.Thumbnails) > 0 {
di.Thumbnail = pmfr.Thumbnail.Thumbnails[0].URL
}
di.InProgress = true
}
di.Live = isLive
return true
}
func (di *DownloadInfo) WaitForStartDelay() bool {
if di.Live && di.StartDelaySecs > 0 {
fragDur := float64(di.TargetDuration)
secondsRoundedToFragLength := int(math.Ceil(float64(di.StartDelaySecs)/fragDur) * fragDur) // Rounds up to next frag interval time
noOfFragsToSkip := secondsRoundedToFragLength / di.TargetDuration
di.LiveFromSq = di.LastSq + noOfFragsToSkip
LogGeneral("Waiting %s before starting to download...", SecondsToDurationAndTimeStr(secondsRoundedToFragLength))
LogDebug("Will start from sequence %d [current is %d]", di.LiveFromSq, di.LastSq)
time.Sleep(time.Duration(secondsRoundedToFragLength) * time.Second) // Waits for the specified length of time.
if secondsRoundedToFragLength > DefaultPollTime {
return di.GetVideoInfo() // Re-grab video information.
}
}
return true
}
func (di *DownloadInfo) downloadFragment(state *fragThreadState, dataChan chan<- *Fragment) {
state.Tries = 0
state.FullRetries = 3
state.Is403 = false
fname := fmt.Sprintf("%s.frag%d.ts", state.BaseFilePath, state.SeqNum)
for state.Tries < int(di.FragMaxTries) || di.FragMaxTries == 0 {
if di.IsStopping() {
return
}
if di.FragMaxTries == 0 {
state.Tries = 0 // just in case someone actually somehow lets something run long enough to cause an overflow
}
baseUrl := di.GetDownloadUrl(state.DataType)
seqUrl := fmt.Sprintf(baseUrl, state.SeqNum)
req, err := http.NewRequest("GET", seqUrl, nil)
if err != nil {
LogDebug("%s: error creating request: %s", state.Name, err.Error())
}
var resp *http.Response
dlStart := time.Now()
if req != nil {
host := di.GetDownloadUrlHost(state.DataType)
if len(host) > 0 {
req.Header.Add("Host", host)
req.Header.Add("Referer", fmt.Sprintf("https://%s/", host))
}
req.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0")
req.Header.Add("Origin", "https://www.youtube.com")