-
Notifications
You must be signed in to change notification settings - Fork 14
/
convert.go
370 lines (309 loc) · 8.63 KB
/
convert.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
package main
import (
"encoding/json"
"errors"
"fmt"
tgbotapi "github.com/krol44/telegram-bot-api"
log "github.com/sirupsen/logrus"
"image"
"image/jpeg"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
)
type Convert struct {
Task *Task
IsTorrent bool
}
type FileConverted struct {
Name string
FilePath string
FilePathNative string
CoverPath string
CoverSize image.Point
}
func (c Convert) Run() FileConverted {
fileConvertPath := c.Task.File
c.Task.File = ""
infoVideo := c.GetInfoVideo(fileConvertPath)
bitrate, _ := strconv.Atoi(infoVideo.Format.BitRate)
fileName := strings.TrimSuffix(path.Base(fileConvertPath), path.Ext(path.Base(fileConvertPath)))
c.Task.App.SendLogToChannel(c.Task.Message.From, "mess", "start convert")
_, _ = c.Task.App.Bot.Send(tgbotapi.NewEditMessageText(c.Task.Message.Chat.ID, c.Task.MessageEditID,
fmt.Sprintf("🌪 %s \n\n🔥 "+c.Task.Lang("Convert is starting")+"...", fileName)))
// create folder
folderConvert, errCreat := c.CreateFolderConvert(fileName)
if errCreat != nil {
log.Warning(errCreat)
}
pathwayNewFile := folderConvert + "/" + fileName
fileCoverPath := pathwayNewFile + ".jpg"
fileConvertPathOut := pathwayNewFile + ".mp4"
timeTotal := c.TimeTotalRaw(fileConvertPath)
var err error
var forceLowBConvert bool
if strings.Contains(c.Task.Message.Text, "+fixing-video") {
forceLowBConvert = true
}
_, isSlice := c.Task.GetTimeSlice()
// check for mp4
if path.Ext(fileConvertPath) == ".mp4" && forceLowBConvert == false && isSlice == false {
c.Task.App.SendLogToChannel(c.Task.Message.From, "mess", "ext .mp4 - skip convert")
fileConvertPathOut = fileConvertPath
} else {
if forceLowBConvert {
bitrate = 1500
}
err := c.execConvert(bitrate, timeTotal, fileName, fileConvertPath, fileConvertPathOut)
if err != nil {
if _, bo := c.Task.App.ChatsWork.StopTasks.Load(c.Task.Message.Chat.ID); bo {
return FileConverted{}
}
c.Task.Send(tgbotapi.NewMessage(
c.Task.Message.Chat.ID, "❗️ "+c.Task.Lang("Video is bad")+" - "+fileName))
log.Error(err)
return FileConverted{}
}
}
timeTotalAfter := c.TimeTotalRaw(fileConvertPathOut)
if timeTotal.Format("15:04") != timeTotalAfter.Format("15:04") {
mess := fmt.Sprintf("‼️ different time (h:m) after convert, before %s - after %s",
timeTotal.Format("15:04"), timeTotalAfter.Format("15:04"))
log.Warn(mess)
c.Task.App.SendLogToChannel(c.Task.Message.From, "mess", mess)
}
// create cover
err = c.CreateCover(fileConvertPathOut, fileCoverPath, timeTotalAfter)
if err != nil {
log.Error(err)
}
// set permit
err = os.Chmod(fileConvertPathOut, os.ModePerm)
if err != nil {
log.Error(err)
}
err = os.Chmod(fileCoverPath, os.ModePerm)
if err != nil {
log.Error(err)
}
// get size
sizeCover, err := c.GetSizeCover(fileCoverPath)
if err != nil {
log.Error(err)
return FileConverted{}
}
return FileConverted{fileName, fileConvertPathOut, fileConvertPath,
fileCoverPath, sizeCover}
}
func (c Convert) execConvert(bitrate int, timeTotal time.Time, fileName string, fileConvertPath string,
fileConvertPathOut string) error {
ffmpegPath := "./ffmpeg"
if config.IsDev {
ffmpegPath = "ffmpeg"
}
cv := "h264_nvenc"
if !c.healthNvenc() {
c.Task.App.SendLogToChannel(&tgbotapi.User{UserName: "debug"},
"mess", "nvenc in container - error")
cv = "h264"
}
slice, isSlice := c.Task.GetTimeSlice()
prepareArgs := []string{
"-protocol_whitelist", "file",
"-v", "quiet",
"-hide_banner", "-stats",
"-i", fileConvertPath,
"-acodec", "aac",
"-c:v", cv,
"-filter_complex", "scale=w='min(1920\\, iw*3/2):h=-2'",
"-preset", "medium",
"-fs", "1990M",
"-pix_fmt", "yuv420p",
"-b:v", fmt.Sprintf("%d", bitrate),
"-b:a", "192k",
"-y",
"-f", "mp4",
fileConvertPathOut}
var args []string
for _, pa := range prepareArgs {
if pa == "-preset" && isSlice {
args = append(args, []string{"-ss", slice[0], "-to", slice[1]}...)
}
args = append(args, pa)
}
log.Info(args)
tmpLast := ""
cmd := exec.Command(ffmpegPath, args...)
defer func(c *exec.Cmd, t string) {
c.Process.Kill()
if err := c.Wait(); err != nil {
log.Info(t)
log.Info(err)
}
c.Process.Release()
}(cmd, tmpLast)
stdout, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout
if err != nil {
return err
}
if err = cmd.Start(); err != nil {
return err
}
for {
if _, bo := c.Task.App.ChatsWork.StopTasks.Load(c.Task.Message.Chat.ID); bo {
return errors.New("force stop")
}
tmp := make([]byte, 1024)
_, err := stdout.Read(tmp)
if err != nil {
break
}
tmpLast = string(tmp)
regx := regexp.MustCompile(`time=(.*?) `)
matches := regx.FindStringSubmatch(string(tmp))
var timeLeft time.Time
if len(matches) == 2 {
timeLeft, _ = time.Parse("15:04:05,00", strings.Trim(matches[1], " "))
} else {
break
}
timeNull, _ := time.Parse("15:04:05", "00:00:00")
percentConvert, _ := strconv.ParseFloat(fmt.Sprintf("%.2f",
100-(timeTotal.Sub(timeLeft).Seconds()/timeTotal.Sub(timeNull).Seconds())*100), 64)
_, errEdit := c.Task.App.Bot.Send(tgbotapi.NewEditMessageText(c.Task.Message.Chat.ID, c.Task.MessageEditID,
fmt.Sprintf("🌪 %s \n\n🔥 "+c.Task.Lang("Convert progress")+": %.2f%%",
fileName, percentConvert)))
if errEdit != nil {
log.Warning(errEdit)
}
time.Sleep(2 * time.Second)
}
return nil
}
func (c Convert) CreateFolderConvert(fileName string) (string, error) {
folderConvert := config.DirBot + "/storage/" + c.Task.UniqueId("files-convert-"+
fileName+"-"+strconv.FormatInt(c.Task.Message.From.ID, 10))
err := os.Mkdir(folderConvert, os.ModePerm)
if err != nil {
return "", err
}
return folderConvert, nil
}
func (c Convert) CreateCover(videoFile string, fileCoverPath string, timeTotal time.Time) error {
timeCut := "00:00:30"
if timeTotal.
Sub(time.Date(0000, 01, 01, 00, 00, 00, 0, time.UTC)).Seconds() <= 40 {
timeCut = "00:00:01"
}
_, err := exec.Command("ffmpeg",
"-protocol_whitelist", "file",
"-i", videoFile,
"-ss", timeCut,
"-vframes", "1",
"-y",
fileCoverPath).Output()
os.Chmod(fileCoverPath, os.ModePerm)
return err
}
func (c Convert) GetSizeCover(fileCoverPath string) (image.Point, error) {
existingImageFile, err := os.Open(fileCoverPath)
if err != nil {
return image.Point{X: 0, Y: 0}, err
}
defer existingImageFile.Close()
_, _, err = image.Decode(existingImageFile)
if err != nil {
return image.Point{X: 0, Y: 0}, err
}
_, err = existingImageFile.Seek(0, 0)
if err != nil {
return image.Point{}, err
}
loadedImage, err := jpeg.Decode(existingImageFile)
if err != nil {
return image.Point{X: 0, Y: 0}, err
}
return loadedImage.Bounds().Size(), nil
}
func (c Convert) TimeTotalRaw(pathway string) time.Time {
timeTotalRaw, err := exec.Command("ffprobe",
"-protocol_whitelist", "file",
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
"-sexagesimal",
pathway).Output()
if err != nil {
log.Error(err)
}
parse, err := time.Parse("15:04:05,000000", strings.Trim(string(timeTotalRaw), "\n"))
if err != nil {
log.Error(err)
}
return parse
}
type InfoVideo struct {
Format struct {
Duration string `json:"duration"`
StartTime string `json:"start_time"`
BitRate string `json:"bit_rate"`
Filename string `json:"filename"`
Size string `json:"size"`
ProbeScore int `json:"probe_score"`
NbPrograms int `json:"nb_programs"`
FormatLongName string `json:"format_long_name"`
NbStreams int `json:"nb_streams"`
FormatName string `json:"format_name"`
Tags struct {
CreationTime string `json:"creation_time"`
Title string `json:"title"`
Encoder string `json:"encoder"`
} `json:"tags"`
} `json:"format"`
}
func (c Convert) GetInfoVideo(pathway string) InfoVideo {
var infoVideo InfoVideo
info, err := exec.Command("ffprobe",
"-v", "quiet",
"-print_format", "json",
"-show_format", pathway).Output()
if err != nil {
log.Error(err)
}
errUn := json.Unmarshal(info, &infoVideo)
if errUn != nil {
log.Error(err)
return InfoVideo{}
}
return infoVideo
}
func (c Convert) healthNvenc() bool {
infoSmi, err := exec.Command("/usr/bin/nvidia-smi").Output()
if err != nil {
log.Warn(err)
return false
}
if strings.Contains(string(infoSmi), "Failed to initialize NVML") {
return false
}
ffmpegPath := "./ffmpeg"
if config.IsDev {
ffmpegPath = "ffmpeg"
}
info, err := exec.Command(ffmpegPath,
"-v", "quiet",
"-h", "encoder=h264_nvenc").Output()
if err != nil {
log.Warn(err)
return false
}
if strings.Contains(string(info), "Encoder h264_nvenc []:") {
return true
}
return false
}