forked from lithdew/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formats.go
119 lines (95 loc) · 2.17 KB
/
formats.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
package youtube
import (
"sort"
)
var AudioQuality = map[string]int{
"AUDIO_QUALITY_LOW": 0,
"AUDIO_QUALITY_MEDIUM": 1,
"AUDIO_QUALITY_HIGH": 2,
}
var VideoQuality = map[string]int{
"tiny": 0,
"low": 1,
"medium": 2,
"large": 3,
"hd1440": 4,
"hd2160": 5,
}
type Formats []Format
func (f Formats) VideoOnly() Formats {
return FilterVideoStreams(f)
}
func (f Formats) AudioOnly() Formats {
return FilterAudioStreams(f)
}
func (f Formats) SortByVideoQuality() Formats {
return SortByVideoQuality(f)
}
func (f Formats) SortByAudioQuality() Formats {
return SortByAudioQuality(f)
}
func (f Formats) BestVideo() (Format, bool) {
return SearchForBestVideoQuality(f)
}
func (f Formats) BestAudio() (Format, bool) {
return SearchForBestAudioQuality(f)
}
func SearchForBestVideoQuality(formats Formats) (Format, bool) {
formats = SortByVideoQuality(formats)
if len(formats) == 0 {
return Format{}, false
}
return formats[0], true
}
func SearchForBestAudioQuality(formats Formats) (Format, bool) {
formats = SortByAudioQuality(formats)
if len(formats) == 0 {
return Format{}, false
}
return formats[0], true
}
func FilterAudioStreams(formats Formats) Formats {
filtered := formats[:0]
for _, format := range formats {
if format.AudioQuality == nil {
continue
}
filtered = append(filtered, format)
}
return filtered
}
func FilterVideoStreams(formats Formats) Formats {
filtered := formats[:0]
for _, format := range formats {
if format.FPS == nil {
continue
}
filtered = append(filtered, format)
}
return filtered
}
func SortByVideoQuality(formats Formats) Formats {
sort.Slice(formats, func(i, j int) bool {
if formats[i].Bitrate > formats[j].Bitrate {
return true
}
return VideoQuality[formats[i].Quality] > VideoQuality[formats[j].Quality]
})
return formats
}
func SortByAudioQuality(formats Formats) Formats {
sort.Slice(formats, func(i, j int) bool {
if formats[i].Bitrate > formats[j].Bitrate {
return true
}
a, b := 0, 0
if ap := formats[i].AudioQuality; ap != nil {
a = AudioQuality[*ap]
}
if bp := formats[j].AudioQuality; bp != nil {
b = AudioQuality[*bp]
}
return a > b
})
return formats
}