-
Notifications
You must be signed in to change notification settings - Fork 4
/
markut.go
1523 lines (1358 loc) · 44.1 KB
/
markut.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 (
"flag"
"fmt"
"os"
"os/exec"
"path"
"strings"
"errors"
"time"
"io/ioutil"
"strconv"
"sort"
"regexp"
)
func decomposeMillis(millis Millis) (hh int64, mm int64, ss int64, ms int64, sign string) {
sign = ""
if millis < 0 {
sign = "-"
millis = -millis
}
hh = int64(millis / 1000 / 60 / 60)
mm = int64(millis / 1000 / 60 % 60)
ss = int64(millis / 1000 % 60)
ms = int64(millis % 1000)
return
}
// Timestamp format used by Markut Language
func millisToTs(millis Millis) string {
hh, mm, ss, ms, sign := decomposeMillis(millis)
return fmt.Sprintf("%s%02d:%02d:%02d.%03d", sign, hh, mm, ss, ms)
}
// Timestamp format used on YouTube
func millisToYouTubeTs(millis Millis) string {
hh, mm, ss, _, sign := decomposeMillis(millis)
return fmt.Sprintf("%s%02d:%02d:%02d", sign, hh, mm, ss)
}
// Timestamp format used by SubRip https://en.wikipedia.org/wiki/SubRip that we
// use for generating the chat in subtitles on YouTube
func millisToSubRipTs(millis Millis) string {
hh, mm, ss, ms, sign := decomposeMillis(millis)
return fmt.Sprintf("%s%02d:%02d:%02d,%03d", sign, hh, mm, ss, ms)
}
type ChatMessage struct {
TimeOffset Millis
Text string
}
type Chunk struct {
Start Millis
End Millis
Loc Loc
InputPath string
ChatLog []ChatMessage
Blur bool
Unfinished bool
}
const ChunksFolder = "chunks"
func (chunk Chunk) Name() string {
inputPath := strings.ReplaceAll(chunk.InputPath, "/", "_")
sb := strings.Builder{}
fmt.Fprintf(&sb, "%s/%s-%09d-%09d", ChunksFolder, inputPath, chunk.Start, chunk.End)
if chunk.Blur {
sb.WriteString("-blur")
}
sb.WriteString(".mp4")
return sb.String()
}
func (chunk Chunk) Duration() Millis {
return chunk.End - chunk.Start
}
func (chunk Chunk) Rendered() (bool, error) {
_, err := os.Stat(chunk.Name())
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
type Chapter struct {
Loc Loc
Timestamp Millis
Label string
}
const MinYouTubeChapterDuration Millis = 10*1000;
func (context *EvalContext) typeCheckArgs(loc Loc, signature ...TokenKind) (args []Token, err error) {
if len(context.argsStack) < len(signature) {
err = &DiagErr{
Loc: loc,
Err: fmt.Errorf("Expected %d arguments but got %d", len(signature), len(context.argsStack)),
}
return
}
for _, kind := range signature {
n := len(context.argsStack)
arg := context.argsStack[n-1]
context.argsStack = context.argsStack[:n-1]
if kind != arg.Kind {
err = &DiagErr{
Loc: arg.Loc,
Err: fmt.Errorf("Expected %s but got %s", TokenKindName[kind], TokenKindName[arg.Kind]),
}
return
}
args = append(args, arg)
}
return
}
type Cut struct {
chunk int
pad Millis
}
type EvalContext struct {
inputPath string
inputPathLog []Token
outputPath string
chatLog []ChatMessage
chunks []Chunk
chapters []Chapter
cuts []Cut
argsStack []Token
chapStack []Chapter
chapOffset Millis
VideoCodec *Token
VideoBitrate *Token
AudioCodec *Token
AudioBitrate *Token
ExtraOutFlags []string
ExtraInFlags []string
}
const (
DefaultVideoCodec = "libx264"
DefaultVideoBitrate = "4000k"
DefaultAudioCodec = "aac"
DefaultAudioBitrate = "300k"
)
func defaultContext() (EvalContext, bool) {
context := EvalContext{
outputPath: "output.mp4",
}
if home, ok := os.LookupEnv("HOME"); ok {
path := path.Join(home, ".markut");
content, err := ioutil.ReadFile(path);
if err != nil {
if os.IsNotExist(err) {
return context, true;
}
fmt.Printf("ERROR: Could not open %s to read as a config: %s\n", path, err);
return context, false;
}
if !context.evalMarkutContent(string(content), path) {
return context, false
}
}
return context, true;
}
func (context EvalContext) PrintSummary() error {
// TODO: Print Extra Input and Output parameters and where they were defined
fmt.Printf(">>> Main Output Parameters:\n")
if context.VideoCodec != nil {
fmt.Printf("Video Codec: %s (Defined at %s)\n", string(context.VideoCodec.Text), context.VideoCodec.Loc);
} else {
fmt.Printf("Video Codec: %s (Default)\n", DefaultVideoCodec);
}
if context.VideoBitrate != nil {
fmt.Printf("Video Bitrate: %s (Defined at %s)\n", string(context.VideoBitrate.Text), context.VideoBitrate.Loc);
} else {
fmt.Printf("Video Bitrate: %s (Default)\n", DefaultVideoBitrate);
}
if context.AudioCodec != nil {
fmt.Printf("Audio Codec: %s (Defined at %s)\n", string(context.AudioCodec.Text), context.AudioCodec.Loc);
} else {
fmt.Printf("Audio Codec: %s (Default)\n", DefaultAudioCodec);
}
if context.AudioBitrate != nil {
fmt.Printf("Audio Bitrate: %s (Defined at %s)\n", string(context.AudioBitrate.Text), context.AudioBitrate.Loc);
} else {
fmt.Printf("Audio Bitrate: %s (Default)\n", DefaultAudioBitrate);
}
fmt.Println()
TwitchVodFileRegexp := "([0-9]+)-[0-9a-f\\-]+\\.mp4"
re := regexp.MustCompile(TwitchVodFileRegexp)
fmt.Printf(">>> Twitch Chat Logs (Detected by regex `%s`)\n", TwitchVodFileRegexp)
for _, inputPath := range context.inputPathLog {
match := re.FindStringSubmatch(string(inputPath.Text))
if len(match) > 0 {
fmt.Printf("%s: https://www.twitchchatdownloader.com/video/%s\n", inputPath.Loc, match[1])
} else {
fmt.Printf("%s: NO MATCH\n", inputPath.Loc)
}
}
fmt.Println()
fmt.Printf(">>> Cuts (%d):\n", max(len(context.chunks) - 1, 0))
var fullLength Millis = 0
var finishedLength Millis = 0
var renderedLength Millis = 0
for i, chunk := range context.chunks {
if i < len(context.chunks) - 1 {
fmt.Printf("%s: Cut %d - %s\n", chunk.Loc, i, millisToTs(fullLength + chunk.Duration()))
}
fullLength += chunk.Duration()
if !chunk.Unfinished {
finishedLength += chunk.Duration()
}
if _, err := os.Stat(chunk.Name()); err == nil {
renderedLength += chunk.Duration()
}
}
fmt.Println()
fmt.Printf(">>> Chunks (%d):\n", len(context.chunks))
for index, chunk := range context.chunks {
rendered, err := chunk.Rendered();
if err != nil {
return nil
}
checkMark := "[ ]"
if rendered {
checkMark = "[x]"
}
fmt.Printf("%s: %s Chunk %d - %s -> %s (Duration: %s)\n", chunk.Loc, checkMark, index, millisToTs(chunk.Start), millisToTs(chunk.End), millisToTs(chunk.Duration()))
}
fmt.Println()
fmt.Printf(">>> YouTube Chapters (%d):\n", len(context.chapters))
for _, chapter := range context.chapters {
fmt.Printf("- %s - %s\n", millisToYouTubeTs(chapter.Timestamp), chapter.Label)
}
fmt.Println()
fmt.Printf(">>> Length:\n")
fmt.Printf("Rendered Length: %s\n", millisToTs(renderedLength))
fmt.Printf("Finished Length: %s\n", millisToTs(finishedLength))
fmt.Printf("Full Length: %s\n", millisToTs(fullLength))
return nil
}
func (context EvalContext) containsChunkWithName(filePath string) bool {
for _, chunk := range(context.chunks) {
if chunk.Name() == filePath {
return true
}
}
return false
}
// IMPORTANT! chatLog is assumed to be sorted by TimeOffset.
func sliceChatLog(chatLog []ChatMessage, start, end Millis) []ChatMessage {
// TODO: use Binary Search for a speed up on big chat logs
lower := 0
for lower < len(chatLog) && chatLog[lower].TimeOffset < start {
lower += 1
}
upper := lower;
for upper < len(chatLog) && chatLog[upper].TimeOffset <= end {
upper += 1
}
if lower < len(chatLog) {
return chatLog[lower:upper]
}
return []ChatMessage{}
}
// IMPORTANT! chatLog is assumed to be sorted by TimeOffset.
func compressChatLog(chatLog []ChatMessage) []ChatMessage {
result := []ChatMessage{}
for i := range chatLog {
if len(result) > 0 && result[len(result)-1].TimeOffset == chatLog[i].TimeOffset {
result[len(result)-1].Text = result[len(result)-1].Text + "\n" + chatLog[i].Text
} else {
result = append(result, chatLog[i])
}
}
return result
}
type Func struct {
Description string
Signature string
Category string
Run func(context *EvalContext, command string, token Token) bool
}
var funcs map[string]Func;
// This function is compatible with the format https://www.twitchchatdownloader.com/ generates.
// It does not use encoding/csv because that website somehow generates unparsable garbage.
func loadTwitchChatDownloaderCSVButParseManually(path string) ([]ChatMessage, error) {
chatLog := []ChatMessage{}
f, err := os.Open(path);
if err != nil {
return chatLog, err
}
bytes, err := ioutil.ReadAll(f)
if err != nil {
return chatLog, err
}
content := string(bytes)
for i, line := range strings.Split(content, "\n") {
if len(line) == 0 {
break
}
pair := strings.SplitN(line, ",", 2)
secs, err := strconv.Atoi(pair[0])
if err != nil {
return chatLog, fmt.Errorf("%s:%d: invalid timestamp: %w", path, i, err)
}
pair = strings.SplitN(pair[1], ",", 2)
nickname := pair[0]
pair = strings.SplitN(pair[1], ",", 2)
text := pair[1]
if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' {
text = text[1:len(text)-1]
}
chatLog = append(chatLog, ChatMessage{
TimeOffset: Millis(secs*1000),
Text: fmt.Sprintf("[%s] %s", nickname, text),
})
}
sort.Slice(chatLog, func(i, j int) bool {
return chatLog[i].TimeOffset < chatLog[j].TimeOffset
})
return compressChatLog(chatLog), nil
}
func (context *EvalContext) evalMarkutContent(content string, path string) bool {
lexer := NewLexer(content, path)
token := Token{}
var err error
for {
token, err = lexer.Next()
if err != nil {
fmt.Printf("%s\n", err)
return false
}
if token.Kind == TokenEOF {
break
}
var args []Token
switch token.Kind {
case TokenDash:
args, err = context.typeCheckArgs(token.Loc, TokenTimestamp, TokenTimestamp)
if err != nil {
fmt.Printf("%s: ERROR: type check failed for subtraction\n", token.Loc)
fmt.Printf("%s\n", err);
return false
}
context.argsStack = append(context.argsStack, Token{
Loc: token.Loc,
Kind: TokenTimestamp,
Timestamp: args[1].Timestamp - args[0].Timestamp,
})
case TokenPlus:
args, err = context.typeCheckArgs(token.Loc, TokenTimestamp, TokenTimestamp)
if err != nil {
fmt.Printf("%s: ERROR: type check failed for addition\n", token.Loc)
fmt.Printf("%s\n", err);
return false
}
context.argsStack = append(context.argsStack, Token{
Loc: token.Loc,
Kind: TokenTimestamp,
Timestamp: args[1].Timestamp + args[0].Timestamp,
})
case TokenString:
fallthrough
case TokenTimestamp:
context.argsStack = append(context.argsStack, token)
case TokenSymbol:
command := string(token.Text)
f, ok := funcs[command];
if !ok {
fmt.Printf("%s: ERROR: Unknown command %s\n", token.Loc, command)
return false
}
if !f.Run(context, command, token) {
return false
}
default:
fmt.Printf("%s: ERROR: Unexpected token %s\n", token.Loc, TokenKindName[token.Kind]);
return false
}
}
return true
}
func (context *EvalContext) evalMarkutFile(path string) bool {
content, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("ERROR: could not read file %s: %s\n", path, err)
return false
}
return context.evalMarkutContent(string(content), path)
}
func (context *EvalContext) finishEval() bool {
for i := 0; i + 1 < len(context.chapters); i += 1 {
duration := context.chapters[i + 1].Timestamp - context.chapters[i].Timestamp;
// TODO: angled brackets are not allowed on YouTube. Let's make `chapters` check for that too.
if duration < MinYouTubeChapterDuration {
fmt.Printf("%s: ERROR: the chapter \"%s\" has duration %s which is shorter than the minimal allowed YouTube chapter duration which is %s (See https://support.google.com/youtube/answer/9884579)\n", context.chapters[i].Loc, context.chapters[i].Label, millisToTs(duration), millisToTs(MinYouTubeChapterDuration));
fmt.Printf("%s: NOTE: the chapter ends here\n", context.chapters[i + 1].Loc);
return false;
}
}
if len(context.argsStack) > 0 || len(context.chapStack) > 0 {
for i := range context.argsStack {
fmt.Printf("%s: ERROR: unused argument\n", context.argsStack[i].Loc)
}
for i := range context.chapStack {
fmt.Printf("%s: ERROR: unused chapter\n", context.chapStack[i].Loc)
}
return false
}
return true
}
func ffmpegPathToBin() (ffmpegPath string) {
ffmpegPath = "ffmpeg"
// TODO: replace FFMPEG_PREFIX envar in favor of a func `ffmpeg_prefix` that you have to call in $HOME/.markut
ffmpegPrefix, ok := os.LookupEnv("FFMPEG_PREFIX")
if ok {
ffmpegPath = path.Join(ffmpegPrefix, "bin", "ffmpeg")
}
return
}
func logCmd(name string, args ...string) {
chunks := []string{}
chunks = append(chunks, name)
for _, arg := range args {
if strings.Contains(arg, " ") {
// TODO: use proper shell escaping instead of just wrapping with double quotes
chunks = append(chunks, "\""+arg+"\"")
} else {
chunks = append(chunks, arg)
}
}
fmt.Printf("[CMD] %s\n", strings.Join(chunks, " "))
}
func millisToSecsForFFmpeg(millis Millis) string {
return fmt.Sprintf("%d.%03d", millis/1000, millis%1000)
}
func ffmpegCutChunk(context EvalContext, chunk Chunk) error {
rendered, err := chunk.Rendered();
if err != nil {
return err;
}
if rendered {
fmt.Printf("INFO: %s is already rendered\n", chunk.Name());
return nil;
}
err = os.MkdirAll(ChunksFolder, 0755)
if err != nil {
return err
}
ffmpeg := ffmpegPathToBin()
args := []string{}
// We always rerender unfinished-chunk.mp4, because it might still
// exist due to the rendering erroring out or canceling. It's a
// temporary file that is copied and renamed to the chunks/ folder
// after the rendering has finished successfully. The successfully
// rendered chunks are not being rerendered due to the check at
// the beginning of the function.
args = append(args, "-y");
args = append(args, "-ss", millisToSecsForFFmpeg(chunk.Start))
for _, inFlag := range context.ExtraInFlags {
args = append(args, inFlag)
}
args = append(args, "-i", chunk.InputPath)
if context.VideoCodec != nil {
args = append(args, "-c:v", string(context.VideoCodec.Text))
} else {
args = append(args, "-c:v", DefaultVideoCodec)
}
if context.VideoBitrate != nil {
args = append(args, "-vb", string(context.VideoBitrate.Text))
} else {
args = append(args, "-vb", DefaultVideoBitrate)
}
if context.AudioCodec != nil {
args = append(args, "-c:a", string(context.AudioCodec.Text))
} else {
args = append(args, "-c:a", DefaultAudioCodec)
}
if context.AudioBitrate != nil {
args = append(args, "-ab", string(context.AudioBitrate.Text))
} else {
args = append(args, "-ab", DefaultAudioBitrate)
}
args = append(args, "-t", millisToSecsForFFmpeg(chunk.Duration()))
if chunk.Blur {
args = append(args, "-vf", "boxblur=50:5")
}
for _, outFlag := range context.ExtraOutFlags {
args = append(args, outFlag)
}
unfinishedChunkName := "unfinished-chunk.mp4"
args = append(args, unfinishedChunkName)
logCmd(ffmpeg, args...)
cmd := exec.Command(ffmpeg, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return err
}
fmt.Printf("INFO: Rename %s -> %s\n", unfinishedChunkName, chunk.Name());
return os.Rename(unfinishedChunkName, chunk.Name())
}
func ffmpegConcatChunks(listPath string, outputPath string) error {
ffmpeg := ffmpegPathToBin()
args := []string{}
// Unlike ffmpegCutChunk(), concatinating chunks is really
// cheap. So we can just allow ourselves to always do that no
// matter what.
args = append(args, "-y")
args = append(args, "-f", "concat")
args = append(args, "-safe", "0")
args = append(args, "-i", listPath)
args = append(args, "-c", "copy")
args = append(args, outputPath)
logCmd(ffmpeg, args...)
cmd := exec.Command(ffmpeg, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func ffmpegFixupInput(inputPath, outputPath string, y bool) error {
ffmpeg := ffmpegPathToBin()
args := []string{}
if y {
args = append(args, "-y")
}
// ffmpeg -y -i {{ morning_input }} -codec copy -bsf:v h264_mp4toannexb {{ morning_input }}.fixed.ts
args = append(args, "-i", inputPath)
args = append(args, "-codec", "copy")
args = append(args, "-bsf:v", "h264_mp4toannexb")
args = append(args, outputPath)
logCmd(ffmpeg, args...)
cmd := exec.Command(ffmpeg, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func ffmpegGenerateConcatList(chunks []Chunk, outputPath string) error {
f, err := os.Create(outputPath)
if err != nil {
return err
}
defer f.Close()
for _, chunk := range chunks {
fmt.Fprintf(f, "file '%s'\n", chunk.Name())
}
return nil
}
func captionsRingPush(ring []ChatMessage, message ChatMessage, capacity int) []ChatMessage {
if len(ring) < capacity {
return append(ring, message)
}
return append(ring[1:], message)
}
type Subcommand struct {
Run func(name string, args []string) bool
Description string
}
var Subcommands = map[string]Subcommand{
"fixup": {
Description: "Fixup the initial footage",
Run: func(name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ExitOnError)
inputPtr := subFlag.String("input", "", "Path to the input video file (mandatory)")
outputPtr := subFlag.String("output", "input.ts", "Path to the output video file")
yPtr := subFlag.Bool("y", false, "Pass -y to ffmpeg")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
if *inputPtr == "" {
subFlag.Usage()
fmt.Printf("ERROR: No -input file is provided\n")
return false
}
err = ffmpegFixupInput(*inputPtr, *outputPtr, *yPtr)
if err != nil {
fmt.Printf("ERROR: Could not fixup input file %s: %s\n", *inputPtr, err)
return false
}
fmt.Printf("Generated %s\n", *outputPtr)
return true
},
},
"cut": {
Description: "Render specific cut of the final video",
Run: func (name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := subFlag.String("markut", "MARKUT", "Path to the MARKUT file")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext()
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
if len(context.cuts) == 0 {
fmt.Printf("ERROR: No cuts are provided. Use `cut` command after a `chunk` command to define a cut\n");
return false;
}
for _, cut := range context.cuts {
if cut.chunk+1 >= len(context.chunks) {
fmt.Printf("ERROR: %d is an invalid cut number. There is only %d of them.\n", cut.chunk, len(context.chunks)-1)
return false
}
cutChunks := []Chunk{
{
Start: context.chunks[cut.chunk].End - cut.pad,
End: context.chunks[cut.chunk].End,
InputPath: context.chunks[cut.chunk].InputPath,
},
{
Start: context.chunks[cut.chunk+1].Start,
End: context.chunks[cut.chunk+1].Start + cut.pad,
InputPath: context.chunks[cut.chunk+1].InputPath,
},
}
for _, chunk := range cutChunks {
err := ffmpegCutChunk(context, chunk)
if err != nil {
fmt.Printf("WARNING: Failed to cut chunk %s: %s\n", chunk.Name(), err)
}
}
cutListPath := "cut-%02d-list.txt"
listPath := fmt.Sprintf(cutListPath, cut.chunk)
err = ffmpegGenerateConcatList(cutChunks, listPath)
if err != nil {
fmt.Printf("ERROR: Could not generate not generate cut concat list %s: %s\n", cutListPath, err)
return false
}
cutOutputPath := fmt.Sprintf("cut-%02d.mp4", cut.chunk)
err = ffmpegConcatChunks(listPath, cutOutputPath)
if err != nil {
fmt.Printf("ERROR: Could not generate cut output file %s: %s\n", cutOutputPath, err)
return false
}
fmt.Printf("Generated %s\n", cutOutputPath);
fmt.Printf("%s: NOTE: cut is defined in here\n", context.chunks[cut.chunk].Loc);
}
return true
},
},
"chunk": {
Description: "Render specific chunk of the final video",
Run: func (name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := subFlag.String("markut", "MARKUT", "Path to the MARKUT file")
chunkPtr := subFlag.Int("chunk", 0, "Chunk number to render")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext();
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
if *chunkPtr > len(context.chunks) {
fmt.Printf("ERROR: %d is an incorrect chunk number. There is only %d of them.\n", *chunkPtr, len(context.chunks))
return false
}
chunk := context.chunks[*chunkPtr]
err = ffmpegCutChunk(context, chunk)
if err != nil {
fmt.Printf("ERROR: Could not cut the chunk %s: %s\n", chunk.Name(), err)
return false
}
fmt.Printf("%s is rendered!\n", chunk.Name())
return true
},
},
"final": {
Description: "Render the final video",
Run: func (name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := subFlag.String("markut", "MARKUT", "Path to the MARKUT file")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext()
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
for _, chunk := range context.chunks {
err := ffmpegCutChunk(context, chunk)
if err != nil {
fmt.Printf("WARNING: Failed to cut chunk %s: %s\n", chunk.Name(), err)
}
}
listPath := "final-list.txt"
err = ffmpegGenerateConcatList(context.chunks, listPath)
if err != nil {
fmt.Printf("ERROR: Could not generate final concat list %s: %s\n", listPath, err)
return false;
}
err = ffmpegConcatChunks(listPath, context.outputPath)
if err != nil {
fmt.Printf("ERROR: Could not generated final output %s: %s\n", context.outputPath, err)
return false
}
err = context.PrintSummary()
if err != nil {
fmt.Printf("ERROR: Could not print summary: %s\n", err);
return false
}
return true
},
},
"summary": {
Description: "Print the summary of the video",
Run: func (name string, args []string) bool {
summFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := summFlag.String("markut", "MARKUT", "Path to the MARKUT file")
err := summFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext();
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
err = context.PrintSummary()
if err != nil {
fmt.Printf("ERROR: Could not print summary: %s\n", err)
return false
}
return true
},
},
"chat": {
Description: "Generate chat captions",
Run: func (name string, args []string) bool {
chatFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := chatFlag.String("markut", "MARKUT", "Path to the MARKUT file")
err := chatFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext()
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
capacity := 1
ring := []ChatMessage{}
timeCursor := Millis(0)
subRipCounter := 0;
for _, chunk := range context.chunks {
prevTime := chunk.Start
for _, message := range chunk.ChatLog {
deltaTime := message.TimeOffset - prevTime
prevTime = message.TimeOffset
if len(ring) > 0 {
subRipCounter += 1
fmt.Printf("%d\n", subRipCounter);
fmt.Printf("%s --> %s\n", millisToSubRipTs(timeCursor), millisToSubRipTs(timeCursor + deltaTime));
for _, ringMessage := range ring {
fmt.Printf("%s\n", ringMessage.Text);
}
fmt.Printf("\n")
}
timeCursor += deltaTime
ring = captionsRingPush(ring, message, capacity);
}
timeCursor += chunk.End - prevTime
}
return true
},
},
"prune": {
Description: "Prune unused chunks",
Run: func (name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := subFlag.String("markut", "MARKUT", "Path to the MARKUT file")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
context, ok := defaultContext();
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
files, err := ioutil.ReadDir(ChunksFolder)
if err != nil {
fmt.Printf("ERROR: could not read %s folder: %s\n", ChunksFolder, err);
return false;
}
for _, file := range files {
if !file.IsDir() {
filePath := fmt.Sprintf("%s/%s", ChunksFolder, file.Name());
if !context.containsChunkWithName(filePath) {
fmt.Printf("INFO: deleting chunk file %s\n", filePath);
err = os.Remove(filePath)
if err != nil {
fmt.Printf("ERROR: could not remove file %s: %s\n", filePath, err)
return false;
}
}
}
}
fmt.Printf("DONE\n");
return true
},
},
// TODO: Maybe watch mode should just be a flag for the `final` subcommand
"watch": {
Description: "Render finished chunks in watch mode every time MARKUT file is modified",
Run: func (name string, args []string) bool {
subFlag := flag.NewFlagSet(name, flag.ContinueOnError)
markutPtr := subFlag.String("markut", "MARKUT", "Path to the MARKUT file")
skipcatPtr := subFlag.Bool("skipcat", false, "Skip concatenation step")
err := subFlag.Parse(args)
if err == flag.ErrHelp {
return true
}
if err != nil {
fmt.Printf("ERROR: Could not parse command line arguments: %s\n", err);
return false
}
fmt.Printf("INFO: Waiting for updates to %s\n", *markutPtr)
for {
// NOTE: always use rsync(1) for updating the MARKUT file remotely.
// This kind of crappy modification checking needs at least some sort of atomicity.
// rsync(1) is as atomic as rename(2). So it's alright for majority of the cases.
context, ok := defaultContext();
ok = ok && context.evalMarkutFile(*markutPtr) && context.finishEval()
if !ok {
return false
}
done := true
for _, chunk := range(context.chunks) {
if chunk.Unfinished {
done = false
continue
}