-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
257 lines (226 loc) · 7.27 KB
/
main.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
package main
import (
"flag"
"github.com/google/uuid"
"github.com/vladaad/discordcompressor/build"
"github.com/vladaad/discordcompressor/encoder"
"github.com/vladaad/discordcompressor/encoder/audio"
"github.com/vladaad/discordcompressor/metadata"
"github.com/vladaad/discordcompressor/settings"
"github.com/vladaad/discordcompressor/uploader"
"github.com/vladaad/discordcompressor/utils"
"io"
"log"
"math"
"os"
"path"
"runtime"
"strconv"
"strings"
"sync"
)
var targetSize int
var targetStartingTime float64
var lastSeconds float64
var targetTotalTime float64
var customOutputFile string
var input string
var forceEncoder string
var forceAEncoder string
var forceContainer string
func init() {
// Update checker
utils.CheckForUpdates()
// Settings dir creation
err := os.MkdirAll(utils.SettingsDir(), 0755)
if err != nil {
panic("Failed to create settings directory")
}
// Log setup
logFileName := utils.SettingsDir()
logFileName += "/dcomp.log"
file, err := os.Create(logFileName)
if err != nil {
panic(err)
}
log.SetOutput(io.MultiWriter(os.Stdout, file))
// Version print
log.Println("Starting DiscordCompressor version " + build.VERSION)
// Check for FFmpeg and FFprobe
checkForFF()
// Parsing flags
settingsFile := flag.String("settings", "", "Selects the settings file to be used")
startTime := flag.Float64("ss", float64(0), "Sets the starting time")
targetTime := flag.Float64("t", float64(0), "Sets the time to encode")
lastXSeconds := flag.Float64("last", float64(0), "Sets the time from the end to encode")
targetSizeMB := flag.Float64("size", float64(-1), "Sets the target size in MB")
debug := flag.Bool("debug", false, "Prints extra info")
customOutput := flag.String("o", "", "Outputs to a specific filename")
forceEncode := flag.String("c:v", "", "Uses a specific encoder")
forceAEncode := flag.String("c:a", "", "Uses a specific audio encoder")
forceContaine := flag.String("f", "", "Uses a specific container") // don't mind the cut off letters thanks
mixAudio := flag.Bool("mixaudio", false, "Mix together all audio tracks")
normAudio := flag.Bool("normaudio", false, "Normalize the audio volume")
upload := flag.Bool("upload", false, "Upload the video to the service defined in settings.json")
flag.Parse()
if len(flag.Args()) == 0 {
log.Println("No input file specified")
os.Exit(0)
}
// Forcing
forceEncoder = *forceEncode
forceAEncoder = *forceAEncode
forceContainer = *forceContaine
input = flag.Args()[0]
targetStartingTime = *startTime
targetTotalTime = *targetTime
lastSeconds = *lastXSeconds
customOutputFile = *customOutput
settings.Debug = *debug
settings.MixAudio = *mixAudio
settings.NormAudio = *normAudio
// Settings loading
settings.LoadSettings(*settingsFile)
// Load defaults
if *targetSizeMB == float64(-1) {
if *upload { // This is only set when the flag is used to ensure that TargetSizeMB in settings can still be used to compensate for overhead in some configs
*targetSizeMB = settings.General.UploadMaxMB
}
*targetSizeMB = settings.General.TargetSizeMB
}
targetSize = int(*targetSizeMB * 8388608) // 1024*1024*8 - in bits
if *upload {
settings.General.AutoUpload = *upload
}
}
func main() {
outVideo := compress(input)
log.Println("Done!")
// Optional video upload
if settings.General.AutoUpload {
URL := uploader.Upload(outVideo)
if URL != "" {
if settings.General.UploadEmbedLink {
URL = "https://embeds.video/" + URL
}
log.Println("Uploaded to: " + URL)
log.Println("The link is also in your clipboard")
utils.PasteIntoClipboard(URL)
}
}
}
func compress(inVideo string) string {
var wg sync.WaitGroup
// Initialize variables
video := initVideo()
video.InFile = inVideo
// Check if file exists
if _, err := os.Stat(video.InFile); err != nil {
panic(video.InFile + " doesn't exist")
}
// Video analysis, time calculation
log.Println("Analyzing video...")
video.Input = metadata.GetStats(video.InFile, false)
video = metadata.CalculateTime(video, lastSeconds, targetStartingTime, targetTotalTime)
// Bitrate calculation
// min(target bps/time, max bps)
video.Output.Bitrate.Total = int(math.Min(float64(targetSize)/video.Time.Duration, float64(settings.Encoding.MaxBitrate*1024)))
// Cap for uploading
// min(target bps, max bps)
if settings.General.AutoUpload {
video.Output.Bitrate.Total = int(math.Min(float64(video.Output.Bitrate.Total), float64(settings.General.UploadMaxBitrate*1024)))
}
// Encoder selection
video.Output.Force.Video, video.Output.Force.Audio, video.Output.Force.Container = forceEncoder, forceAEncoder, forceContainer
video = metadata.SelectEncoder(video)
video = metadata.CalcOverhead(video)
// Force fast mode with 1-pass
if video.Output.Encoder.Passes == 1 {
settings.Encoding.FastMode = true
}
// Audio bitrate calculation and encoding
if video.Input.ATracks > 0 {
video = metadata.CalcAudioBitrate(video)
}
video = metadata.PassthroughCheck(video)
if !video.Output.APassthrough || forceAEncoder != "" {
if video.Input.ATracks > 0 {
video.Output.AudioFile = audio.GenFilename(video)
wg.Add(1)
if settings.Encoding.FastMode {
go audio.EncodeAudio(video, &wg)
} else {
log.Println("Encoding audio...")
audio.EncodeAudio(video, &wg)
}
} else {
video.Output.Bitrate.Video = video.Output.Bitrate.Total
}
}
if settings.Debug {
log.Println("Video bitrate:", video.Output.Bitrate.Video/1024)
log.Println("Audio bitrate:", video.Output.Bitrate.Audio/1024)
}
// Resolution analysis
if !settings.Encoding.FastMode && settings.Encoding.AutoRes {
log.Println("Automatically choosing resolution, this may take a while...")
video = encoder.CalculateResolution(video)
if settings.Debug {
log.Println("Chosen vertical resolution:", video.Output.Settings.MaxVRes)
}
}
// Output filename
suffix := strings.ReplaceAll(settings.General.OutputSuffix, "%s", strconv.FormatFloat(float64(targetSize)/8388608, 'f', 1, 64))
video.OutFile = strings.TrimSuffix(video.InFile, path.Ext(video.InFile)) + suffix + "." + video.Output.Settings.Container
if customOutputFile != "" {
video.OutFile = customOutputFile + "." + video.Output.Settings.Container
}
// Encoding
if video.Output.Encoder.Passes == 1 {
wg.Wait()
log.Println("Encoding")
encoder.EncodeVideo(video, 0)
} else {
log.Println("Encoding, pass 1/2")
encoder.EncodeVideo(video, 1)
wg.Wait()
log.Println("Encoding, pass 2/2")
encoder.EncodeVideo(video, 2)
}
// Cleanup
os.Remove(video.UUID + "-0.log")
os.Remove(video.UUID + "-0.log.mbtree")
os.Remove(video.Output.AudioFile)
return video.OutFile
}
func checkForFF() {
exit := false
check := []string{"ffmpeg", "ffprobe"}
for i := range check {
if !utils.CheckIfPresent(check[i]) {
message := check[i] + " not installed or not added to PATH"
if runtime.GOOS == "windows" {
message = message + ", you can download it here: https://github.com/BtbN/FFmpeg-Builds/releases"
}
log.Println(message)
exit = true
}
}
if exit {
os.Exit(1)
}
}
func initVideo() *settings.Vid {
// god fucking dammit
video := new(settings.Vid)
time := new(settings.Time)
bitrates := new(settings.Bitrates)
output := new(settings.Out)
force := new(settings.Force)
output.Bitrate = bitrates
video.Output = output
video.Output.Force = force
video.Time = time
video.UUID = uuid.New().String()
return video
}