-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathffmpeg_test.go
More file actions
2703 lines (2421 loc) · 86 KB
/
Copy pathffmpeg_test.go
File metadata and controls
2703 lines (2421 loc) · 86 KB
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 ffmpeg
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func setupTest(t *testing.T) (func(cmd string) bool, string) {
dir, err := ioutil.TempDir("", t.Name())
if err != nil {
t.Fatal(err)
}
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
InitFFmpeg() // hide some log noise
// Executes the given bash script and checks the results.
// The script is passed two arguments:
// a tempdir and the current working directory.
cmdFunc := func(cmd string) bool {
cmd = "cd $0 && set -eux;\n" + cmd
out, err := exec.Command("bash", "-c", cmd, dir, wd).CombinedOutput()
if err != nil {
t.Error(string(out[:]))
return false
}
return true
}
return cmdFunc, dir
}
func TestSegmenter_DeleteSegments(t *testing.T) {
// Ensure that old segments are deleted as they fall off the playlist
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// sanity check that segmented outputs > playlist length
cmd := `
# default test.ts is a bit short so make it a bit longer
cp "$1/../transcoder/test.ts" test.ts
ffmpeg -loglevel warning -i "concat:test.ts|test.ts|test.ts" -c copy long.ts
ffmpeg -loglevel warning -i long.ts -c copy -f hls -hls_time 1 long.m3u8
# ensure we have more segments than playlist length
[ $(ls long*.ts | wc -l) -ge 6 ]
`
run(cmd)
// actually do the segmentation
err := RTMPToHLS(dir+"/long.ts", dir+"/out.m3u8", dir+"/out_%d.ts", "1", 0)
if err != nil {
t.Error(err)
}
// check that segments have been deleted by counting output ts files
cmd = `
[ $(ls out_*.ts | wc -l) -eq 6 ]
`
run(cmd)
}
func TestSegmenter_StreamOrdering(t *testing.T) {
// Ensure segmented output contains [video, audio] streams in that order
// regardless of stream ordering in the input
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Craft an input that has a subtitle, audio and video stream, in that order
cmd := `
# generate subtitle file
cat <<- EOF > inp.srt
1
00:00:00,000 --> 00:00:01,000
hi
EOF
# borrow the test.ts from the transcoder dir, output with 3 streams
ffmpeg -loglevel warning -i inp.srt -i "$1/../transcoder/test.ts" -c:a copy -c:v copy -c:s mov_text -t 1 -map 0:s -map 1:a -map 1:v test.mp4
# some sanity checks. these will exit early on a nonzero code
# check stream count, then indexes of subtitle, audio and video
[ $(ffprobe -loglevel warning -i test.mp4 -show_streams | grep index | wc -l) -eq 3 ]
ffprobe -loglevel warning -i test.mp4 -show_streams -select_streams s | grep index=0
ffprobe -loglevel warning -i test.mp4 -show_streams -select_streams a | grep index=1
ffprobe -loglevel warning -i test.mp4 -show_streams -select_streams v | grep index=2
`
run(cmd)
// actually do the segmentation
err := RTMPToHLS(dir+"/test.mp4", dir+"/out.m3u8", dir+"/out_%d.ts", "1", 0)
if err != nil {
t.Error(err)
}
// check stream ordering in output file. Should be video, then audio
cmd = `
[ $(ffprobe -loglevel warning -i out_0.ts -show_streams | grep index | wc -l) -eq 2 ]
ffprobe -loglevel warning -i out_0.ts -show_streams -select_streams v | grep index=0
ffprobe -loglevel warning -i out_0.ts -show_streams -select_streams a | grep index=1
`
run(cmd)
}
func TestSegmenter_DropLatePackets(t *testing.T) {
// Certain sources sometimes send packets with out-of-order FLV timestamps
// (eg, ManyCam on Android when the phone can't keep up)
// Ensure we drop these packets
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Craft an input with an out-of-order timestamp
cmd := `
# borrow segmenter test file, rewrite a timestamp
cp "$1/../segmenter/test.flv" test.flv
# Sanity check the last few timestamps are monotonic : 18867,18900,18933
ffprobe -loglevel quiet -show_packets -select_streams v test.flv | grep dts= | tail -3 | tr '\n' ',' | grep dts=18867,dts=18900,dts=18933,
# replace ts 18900 at position 2052736 with ts 18833 (0x4991 hex)
printf '\x49\x91' | dd of=test.flv bs=1 seek=2052736 count=2 conv=notrunc
# sanity check timestamps are now 18867,18833,18933
ffprobe -loglevel quiet -show_packets -select_streams v test.flv | grep dts= | tail -3 | tr '\n' ',' | grep dts=18867,dts=18833,dts=18933,
# sanity check number of frames
ffprobe -loglevel quiet -count_packets -show_streams -select_streams v test.flv | grep nb_read_packets=569
`
run(cmd)
err := RTMPToHLS(dir+"/test.flv", dir+"/out.m3u8", dir+"/out_%d.ts", "100", 0)
if err != nil {
t.Error(err)
}
// Now ensure things are as expected
cmd = `
# check monotonic timestamps (rescaled for the 90khz mpegts timebase)
ffprobe -loglevel quiet -show_packets -select_streams v out_0.ts | grep dts= | tail -3 | tr '\n' ',' | grep dts=1694970,dts=1698030,dts=1703970,
# check that we dropped the packet
ffprobe -loglevel quiet -count_packets -show_streams -select_streams v out_0.ts | grep nb_read_packets=568
`
run(cmd)
}
func TestTranscoder_Resolution(t *testing.T) {
runResolutionTests_H264(t, Software)
// TODO test HEVC clamping
}
func runResolutionTests_H264(t *testing.T, accel Acceleration) {
// Test clamping behavior of rescaler
// and that aspect ratio is still maintained
// TODO make it possible to run setupTest within sub-tests
run, dir := setupTest(t)
defer os.RemoveAll(dir)
tests := []struct {
name string
// input width and height
input string
// target resolution
target string
// expected width and height
expected string
}{{
name: "h > w",
input: "150x200",
target: "0x250",
expected: "188x250",
}, {
name: "h > w, rounded height",
input: "200x300",
target: "0x427",
expected: "284x426",
}, {
name: "h > w, target swapped",
input: "200x300",
target: "426x0",
expected: "284x426",
}, {
name: "h > w, w < min",
input: "123x456",
target: "0x426",
expected: "146x542",
}, {
name: "h > w, rounded width",
input: "200x300",
target: "0x428",
expected: "286x428",
}, {
name: "h > w, w < min and h < min",
input: "400x456",
target: "0x40",
expected: "146x166", // will always hit min width here
}, {
name: "w > h",
input: "456x123",
target: "426x0",
expected: "426x114",
}, {
name: "w > h, target swapped and rounded width",
input: "456x123",
target: "0x301",
expected: "300x80",
}, {
name: "w > h, w < min",
input: "456x400",
target: "100x0",
expected: "146x128",
}, {
name: "w > h, target swapped and h < min",
input: "500x100",
target: "0x200",
expected: "250x50",
}, {
name: "w > h, target swapped",
input: "456x120",
target: "0x400",
expected: "400x106",
}, {
name: "square",
input: "123x123",
target: "426x0",
expected: "426x426",
}}
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// TODO optimize by reusing inputs if possible
cmd := fmt.Sprintf(`
echo '%s'
ffmpeg -loglevel warning -i "$1/../transcoder/test.ts" -c:a copy -c:v mpeg4 -s %s -t 1 test-%d.mp4
ffprobe -hide_banner -show_entries stream=width,height -of csv=p=0:s=x test-%d.mp4 | grep %s
`, tt.name, tt.input, i, i, tt.input)
run(cmd)
_, err := Transcode3(&TranscodeOptionsIn{
Fname: fmt.Sprintf("%s/test-%d.mp4", dir, i),
}, []TranscodeOptions{{
Oname: fmt.Sprintf("%s/out-test-%d.mp4", dir, i),
Profile: VideoProfile{Resolution: tt.target, Bitrate: "50k"},
Accel: accel,
}})
assert.Nil(t, err)
cmd = fmt.Sprintf(`
echo '%s'
ffprobe -hide_banner -show_entries stream=width,height -of csv=p=0:s=x out-test-%d.mp4 | grep %s`, tt.name, i, tt.expected)
run(cmd)
})
}
// TODO set / check sar/dar values?
}
func TestTranscoder_SampleRate(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Craft an input with 48khz audio
cmd := `
# borrow the test.ts from the transcoder dir, output with 48khz audio
ffmpeg -loglevel warning -i "$1/../transcoder/test.ts" -c:v copy -af 'aformat=sample_fmts=fltp:channel_layouts=stereo:sample_rates=48000' -c:a aac -t 1.1 test.ts
# sanity check results to ensure preconditions
ffprobe -loglevel warning -show_streams -select_streams a test.ts | grep sample_rate=48000
# output timestamp check as a script to reuse for post-transcoding check
cat <<- 'EOF' > check_ts
set -eux
# ensure 1 second of timestamps add up to within 2.1% of 90khz (mpegts timebase)
# 2.1% is the margin of error, 1024 / 48000 (% increase per frame)
# 1024 = samples per frame, 48000 = samples per second
# select last frame pts, subtract from first frame pts, check diff
ffprobe -loglevel warning -show_frames -select_streams a "$2" | grep pts= | head -"$1" | awk 'BEGIN{FS="="} ; NR==1 { fst = $2 } ; END{ diff=(($2-fst)/90000); exit diff <= 0.979 || diff >= 1.021 }'
EOF
chmod +x check_ts
# check timestamps at the given frame offsets. 47 = ceil(48000/1024)
./check_ts 47 test.ts
# check failing cases; use +2 since we may be +/- the margin of error
[ $(./check_ts 45 test.ts || echo "shouldfail") = "shouldfail" ]
[ $(./check_ts 49 test.ts || echo "shouldfail") = "shouldfail" ]
`
run(cmd)
err := Transcode(dir+"/test.ts", dir, []VideoProfile{P240p30fps16x9})
if err != nil {
t.Error(err)
}
// Ensure transcoded sample rate is 44k.1hz and check timestamps
cmd = `
ffprobe -loglevel warning -show_streams -select_streams a out0test.ts | grep sample_rate=44100
# Sample rate = 44.1khz, samples per frame = 1024
# Frames per second = ceil(44100/1024) = 44
# Technically check_ts margin of error is 2.1% due to 48khz rate
# At 44.1khz, error is 2.3% so we'll just accept the tighter bounds
# check timestamps at the given frame offsets. 44 = ceil(48000/1024)
./check_ts 44 out0test.ts
# check failing cases; use +2 since we may be +/- the margin of error
[ $(./check_ts 46 out0test.ts || echo "shouldfail") = "shouldfail" ]
[ $(./check_ts 42 out0test.ts || echo "shouldfail") = "shouldfail" ]
`
run(cmd)
}
func TestTranscoder_Timestamp(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
cmd := `
# prepare the input and sanity check 60fps
cp "$1/../transcoder/test.ts" inp.ts
ffprobe -loglevel warning -select_streams v -show_streams -count_frames inp.ts > inp.out
grep avg_frame_rate=60 inp.out
grep r_frame_rate=60 inp.out
# reduce 60fps original to 30fps indicated but 15fps real
ffmpeg -loglevel warning -i inp.ts -an -vf 'fps=30,select=not(mod(n\,2))' -c:v libx264 -t 1 -fps_mode vfr test.ts
ffprobe -loglevel warning -select_streams v -show_streams -count_frames test.ts > test.out
# sanity check some properties. hard code numbers for now.
grep avg_frame_rate=30 test.out
grep r_frame_rate=15 test.out
grep nb_read_frames=15 test.out
grep duration_ts=90000 test.out
grep start_pts=138000 test.out
`
run(cmd)
err := Transcode(dir+"/test.ts", dir, []VideoProfile{P240p30fps16x9})
if err != nil {
t.Error(err)
}
cmd = `
# hardcode some checks for now. TODO make relative to source.
ffprobe -loglevel warning -select_streams v -show_streams -count_frames out0test.ts > test.out
grep avg_frame_rate=30 test.out
grep r_frame_rate=30 test.out
grep nb_read_frames=29 test.out
grep duration_ts=87000 test.out
grep start_pts=138000 test.out
`
run(cmd)
}
func TestTranscoderStatistics_Decoded(t *testing.T) {
// Checks the decoded stats returned after transcoding
var (
totalPixels int64
totalFrames int
)
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// segment using our muxer. This should produce 4 segments.
err := RTMPToHLS("../transcoder/test.ts", dir+"/test.m3u8", dir+"/test_%d.ts", "1", 0)
if err != nil {
t.Error(err)
}
// Use various resolutions to test input
// Quickcheck style tests would be nice here one day?
profiles := []VideoProfile{P144p30fps16x9, P240p30fps16x9, P360p30fps16x9, P576p30fps16x9}
// Transcode some data, save encoded statistics, then attempt to re-transcode
// Ensure decoded re-transcode stats match original transcoded statistics
for i, p := range profiles {
oname := fmt.Sprintf("%s/out_%d.ts", dir, i)
out := []TranscodeOptions{{Profile: p, Oname: oname}}
in := &TranscodeOptionsIn{Fname: fmt.Sprintf("%s/test_%d.ts", dir, i)}
res, err := Transcode3(in, out)
if err != nil {
t.Error(err)
}
info := res.Encoded[0]
// Now attempt to re-encode the transcoded data
// Pass in an empty output to achieve a decode-only flow
// and check decoded results from *that*
in = &TranscodeOptionsIn{Fname: oname}
res, err = Transcode3(in, nil)
if err != nil {
t.Error(err)
}
w, h, err := VideoProfileResolution(p)
if err != nil {
t.Error(err)
}
// Check pixel counts
if info.Pixels != res.Decoded.Pixels {
t.Error("Mismatched pixel counts")
}
if info.Pixels != int64(w*h*res.Decoded.Frames) {
t.Error("Mismatched pixel counts")
}
// Check frame counts
if info.Frames != res.Decoded.Frames {
t.Error("Mismatched frame counts")
}
if info.Frames != int(res.Decoded.Pixels/int64(w*h)) {
t.Error("Mismatched frame counts")
}
totalPixels += info.Pixels
totalFrames += info.Frames
}
// Now for something fun. Concatenate our segments of various resolutions
// Run them through the transcoder, and check the sum of pixels / frames match
// Ensures we can properly accommodate mid-stream resolution changes.
cmd := `
cat out_0.ts out_1.ts out_2.ts out_3.ts > combined.ts
`
run(cmd)
in := &TranscodeOptionsIn{Fname: dir + "/combined.ts"}
res, err := Transcode3(in, nil)
if err != nil {
t.Error(err)
}
if totalPixels != res.Decoded.Pixels {
t.Error("Mismatched total pixel counts")
}
if totalFrames != res.Decoded.Frames {
t.Errorf("Mismatched total frame counts - %d vs %d", totalFrames, res.Decoded.Frames)
}
}
func TestTranscoder_Statistics_Encoded(t *testing.T) {
// Checks the encoded stats returned after transcoding
run, dir := setupTest(t)
defer os.RemoveAll(dir)
cmd := `
# prepare 1-second input
cp "$1/../transcoder/test.ts" inp.ts
ffmpeg -loglevel warning -i inp.ts -c:a copy -c:v copy -t 1 test.ts
`
run(cmd)
// set a 60fps input at a small resolution (to help runtime)
p144p60fps := P144p30fps16x9
p144p60fps.Framerate = 60
// odd / nonstandard input just to sanity check.
podd123fps := VideoProfile{Resolution: "146x82", Framerate: 123, Bitrate: "100k"}
// Construct output parameters.
// Quickcheck style tests would be nice here one day?
profiles := []VideoProfile{P240p30fps16x9, P144p30fps16x9, p144p60fps, podd123fps}
out := make([]TranscodeOptions, len(profiles))
for i, p := range profiles {
out[i] = TranscodeOptions{Profile: p, Oname: fmt.Sprintf("%s/out%d.ts", dir, i)}
}
res, err := Transcode3(&TranscodeOptionsIn{Fname: dir + "/test.ts"}, out)
if err != nil {
t.Error(err)
}
for i, r := range res.Encoded {
w, h, err := VideoProfileResolution(out[i].Profile)
if err != nil {
t.Error(err)
}
// Check pixel counts
if r.Pixels != int64(w*h*r.Frames) {
t.Error("Mismatched pixel counts")
}
// Since this is a 1-second input we should ideally have count of frames
if r.Frames != int(out[i].Profile.Framerate+1) {
// Some "special" cases (already have test cases covering these)
if p144p60fps == out[i].Profile {
if r.Frames != int(out[i].Profile.Framerate)+1 {
t.Error("Mismatched frame counts for 60fps; expected 61 frames but got ", r.Frames)
}
} else if podd123fps == out[i].Profile {
if r.Frames != 124 {
t.Error("Mismatched frame counts for 123fps; expected 124 frames but got ", r.Frames)
}
} else {
t.Error("Mismatched frame counts ", r.Frames, out[i].Profile.Framerate)
}
}
// Check frame counts against ffprobe-reported output
// First, generate stats file
f, err := os.Create(fmt.Sprintf("%s/out%d.res.stats", dir, i))
if err != nil {
t.Error(err)
}
b := bufio.NewWriter(f)
fmt.Fprintf(b, `width=%d
height=%d
nb_read_frames=%d
`, w, h, r.Frames)
b.Flush()
f.Close()
cmd = fmt.Sprintf(`
fname=out%d
ffprobe -loglevel warning -hide_banner -count_frames -count_packets -select_streams v -show_streams 2>&1 $fname.ts | grep '^width=\|^height=\|nb_read_frames=' > $fname.stats
diff -u $fname.stats $fname.res.stats
`, i)
run(cmd)
}
}
func TestTranscoder_StatisticsAspectRatio(t *testing.T) {
// Check that we correctly account for aspect ratio adjustments
// Eg, the transcoded resolution we receive may be smaller than
// what we initially requested
run, dir := setupTest(t)
defer os.RemoveAll(dir)
cmd := `
# prepare 1-second input
cp "$1/../transcoder/test.ts" inp.ts
ffmpeg -loglevel warning -i inp.ts -c:a copy -c:v copy -t 1 test.ts
`
run(cmd)
// This will be adjusted to 146x82 by the rescaler (since source is 16:9)
pAdj := VideoProfile{Resolution: "0x123", Framerate: 16, Bitrate: "100k"}
out := []TranscodeOptions{{Profile: pAdj, Oname: dir + "/adj.mp4"}}
res, err := Transcode3(&TranscodeOptionsIn{Fname: dir + "/test.ts"}, out)
if err != nil || len(res.Encoded) <= 0 {
t.Error(err)
}
r := res.Encoded[0]
if r.Frames != int(pAdj.Framerate+1) || r.Pixels != int64(r.Frames*146*82) {
t.Error(fmt.Errorf("Results did not match: %v ", r))
}
}
func TestTranscoder_MuxerOpts(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Prepare test environment : truncate input file
cmd := `
cp "$1/../transcoder/test.ts" inp.ts
ffmpeg -i inp.ts -c:a copy -c:v copy -t 1 inp-short.ts
`
run(cmd)
prof := P240p30fps16x9
// Set the muxer itself given a different extension
_, err := Transcode3(&TranscodeOptionsIn{
Fname: dir + "/inp-short.ts",
}, []TranscodeOptions{{
Oname: dir + "/out-mkv.mp4",
Profile: prof,
Muxer: ComponentOptions{Name: "matroska"},
}})
if err != nil {
t.Error(err)
}
// Pass in some options to muxer
_, err = Transcode3(&TranscodeOptionsIn{
Fname: dir + "/inp.ts",
}, []TranscodeOptions{{
Oname: dir + "/out.mpd",
Profile: prof,
Muxer: ComponentOptions{
Name: "dash",
Opts: map[string]string{
"media_seg_name": "lpms-test-$RepresentationID$-$Number%05d$.m4s",
"init_seg_name": "lpms-init-$RepresentationID$.m4s",
},
},
}})
if err != nil {
t.Error(err)
}
cmd = `
# check formats and that options were used
ffprobe -loglevel warning -show_format out-mkv.mp4 | grep format_name=matroska
# ffprobe -loglevel warning -show_format out.mpd | grep format_name=dash # this fails so skip for now
# concat headers. mp4 chunks are annoying
cat lpms-init-0.m4s lpms-test-0-00001.m4s > video.m4s
cat lpms-init-1.m4s lpms-test-1-00001.m4s > audio.m4s
ffprobe -show_format video.m4s | grep nb_streams=1
ffprobe -show_format audio.m4s | grep nb_streams=1
ffprobe -show_streams -select_streams v video.m4s | grep codec_name=h264
ffprobe -show_streams -select_streams a audio.m4s | grep codec_name=aac
`
run(cmd)
}
type TranscodeOptionsTest struct {
InputCodec VideoCodec
OutputCodec VideoCodec
InputAccel Acceleration
OutputAccel Acceleration
Profile VideoProfile
}
func TestSW_Transcoding(t *testing.T) {
codecsComboTest(t, supportedCodecsCombinations([]Acceleration{Software}))
}
func supportedCodecsCombinations(accels []Acceleration) []TranscodeOptionsTest {
prof := P240p30fps16x9
var opts []TranscodeOptionsTest
inCodecs := []VideoCodec{H264, H265, VP8, VP9}
outCodecs := []VideoCodec{H264, H265, VP8, VP9}
for _, inAccel := range accels {
for _, outAccel := range accels {
for _, inCodec := range inCodecs {
for _, outCodec := range outCodecs {
// skip unsupported combinations
switch outAccel {
case Nvidia:
switch outCodec {
case VP8, VP9:
continue
}
}
opts = append(opts, TranscodeOptionsTest{
InputCodec: inCodec,
OutputCodec: outCodec,
InputAccel: inAccel,
OutputAccel: outAccel,
Profile: prof,
})
}
}
}
}
return opts
}
func codecsComboTest(t *testing.T, options []TranscodeOptionsTest) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
sampleName := dir + "/test.ts"
var inName, outName, qName string
cmd := `
# set up initial input; truncate test.ts file
ffmpeg -loglevel warning -i "$1"/../transcoder/test.ts -c:a copy -c:v copy -t 1 test.ts
`
run(cmd)
var err error
for i := range options {
curOptions := options[i]
switch curOptions.InputCodec {
case VP8, VP9:
inName = dir + "/test_in.mkv"
case H264, H265:
inName = dir + "/test_in.ts"
}
switch curOptions.OutputCodec {
case VP8, VP9:
outName = dir + "/out.mkv"
qName = dir + "/sw.mkv"
case H264, H265:
outName = dir + "/out.ts"
qName = dir + "/sw.ts"
}
// if non-h264 test requested, transcode to target input codec first
prepare := true
if curOptions.InputCodec != H264 {
profile := P720p60fps16x9
profile.Encoder = curOptions.InputCodec
err = Transcode2(&TranscodeOptionsIn{
Fname: sampleName,
Accel: Software,
}, []TranscodeOptions{
{
Oname: inName,
Profile: profile,
Accel: Software,
},
})
if err != nil {
t.Error(err)
prepare = false
}
} else {
inName = sampleName
}
targetProfile := curOptions.Profile
targetProfile.Encoder = curOptions.OutputCodec
transcode := prepare
if prepare {
err = Transcode2(&TranscodeOptionsIn{
Fname: inName,
Accel: curOptions.InputAccel,
}, []TranscodeOptions{
{
Oname: outName,
Profile: targetProfile,
Accel: curOptions.OutputAccel,
},
})
if err != nil {
t.Error(err)
transcode = false
}
}
quality := transcode
if transcode {
// software transcode for image quality check
err = Transcode2(&TranscodeOptionsIn{
Fname: inName,
Accel: Software,
}, []TranscodeOptions{
{
Oname: qName,
Profile: targetProfile,
Accel: Software,
},
})
if err != nil {
t.Error(err)
quality = false
}
cmd = fmt.Sprintf(`
# compare using ssim and generate stats file
ffmpeg -loglevel warning -i %s -i %s -lavfi '[0:v][1:v]ssim=stats.log' -f null -
# check image quality; ensure that no more than 5 frames have ssim < 0.95
grep -Po 'All:\K\d+.\d+' stats.log | awk '{ if ($1 < 0.95) count=count+1 } END{ exit count > 5 }'
`, outName, qName)
if quality {
quality = run(cmd)
}
}
t.Logf("Transcode %s (Accel: %d) -> %s (Accel: %d) Prepare: %t Transcode: %t Quality: %t\n",
VideoCodecName[curOptions.InputCodec],
curOptions.InputAccel,
VideoCodecName[curOptions.OutputCodec],
curOptions.OutputAccel,
prepare, transcode, quality)
}
}
func TestTranscoder_EncoderOpts(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Prepare test environment : truncate input file
cmd := `
# truncate input
ffmpeg -i "$1/../transcoder/test.ts" -c:a copy -c:v copy -t 1 test.ts
# we will sanity check image quality with ssim
# since ssim needs res and framecount to match, sanity check those
ffprobe -show_streams -select_streams v test.ts | grep width=1280
ffprobe -show_streams -select_streams v test.ts | grep height=720
ffprobe -count_frames -show_streams -select_streams v test.ts | grep nb_read_frames=60
`
run(cmd)
prof := P720p60fps16x9
in := &TranscodeOptionsIn{Fname: dir + "/test.ts"}
out := []TranscodeOptions{{
Oname: dir + "/out.nut",
Profile: prof,
VideoEncoder: ComponentOptions{Name: "snow"},
AudioEncoder: ComponentOptions{
Name: "vorbis",
// required since vorbis implementation is marked experimental
// also, gives us an opportunity to test the audio opts
Opts: map[string]string{"strict": "experimental"}},
}}
_, err := Transcode3(in, out)
if err != nil {
t.Error(err)
}
cmd = `
# Check codecs are what we expect them to be
ffprobe -show_streams -select_streams v out.nut | grep codec_name=snow
ffprobe -show_streams -select_streams a out.nut | grep codec_name=vorbis
# sanity check image quality : compare using ssim
ffmpeg -loglevel warning -i out.nut -i test.ts -lavfi '[0:v][1:v]ssim=stats.log' -f null -
# ensure that no more than 5 frames have ssim < 0.95
grep -Po 'All:\K\d+.\d+' stats.log | awk '{ if ($1 < 0.95) count=count+1 } END{ exit count > 5 }'
`
run(cmd)
}
func TestTranscoder_StreamCopy(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Set up inputs, truncate test file
cmd := `
cp "$1"/../transcoder/test.ts .
ffmpeg -i test.ts -c:a copy -c:v copy -t 1 test-short.ts
# sanity check some assumptions here for the following set of tests
ffprobe -count_frames -show_streams -select_streams v test-short.ts | grep nb_read_frames=60
`
run(cmd)
// Test normal stream-copy case
in := &TranscodeOptionsIn{Fname: dir + "/test-short.ts"}
out := []TranscodeOptions{
{
Oname: dir + "/audiocopy.ts",
Profile: P144p30fps16x9,
AudioEncoder: ComponentOptions{Name: "copy"},
},
{
Oname: dir + "/videocopy.ts",
VideoEncoder: ComponentOptions{Name: "copy", Opts: map[string]string{
"mpegts_flags": "resend_headers,initial_discontinuity",
}},
},
}
res, err := Transcode3(in, out)
if err != nil {
t.Error(err)
}
if res.Decoded.Frames != 60 || res.Encoded[0].Frames != 31 ||
res.Encoded[1].Frames != 0 {
t.Error("Unexpected frame counts from stream copy")
t.Error(res)
}
cmd = `
# extract video track only, compare md5sums
ffmpeg -i test-short.ts -an -c:v copy -f md5 test-video.md5
ffmpeg -i videocopy.ts -an -c:v copy -f md5 videocopy.md5
diff -u test-video.md5 videocopy.md5
# extract audio track only, compare md5sums
ffmpeg -i test-short.ts -vn -c:a copy -f md5 test-audio.md5
ffmpeg -i audiocopy.ts -vn -c:a copy -f md5 audiocopy.md5
diff -u test-audio.md5 audiocopy.md5
`
run(cmd)
// Test stream copy when no stream exists in file
cmd = `
ffmpeg -i test-short.ts -an -c:v copy videoonly.ts
ffmpeg -i test-short.ts -vn -c:a copy audioonly.ts
`
run(cmd)
in = &TranscodeOptionsIn{Fname: dir + "/videoonly.ts"}
out = []TranscodeOptions{
{
Oname: dir + "/novideo.ts",
VideoEncoder: ComponentOptions{Name: "copy"},
},
}
res, err = Transcode3(in, out)
if err != nil {
t.Error(err)
}
if res.Decoded.Frames != 0 || res.Encoded[0].Frames != 0 {
t.Error("Unexpected count of decoded/encoded frames")
}
in = &TranscodeOptionsIn{Fname: dir + "/audioonly.ts"}
out = []TranscodeOptions{
{
Oname: dir + "/noaudio.ts",
Profile: P144p30fps16x9,
AudioEncoder: ComponentOptions{Name: "copy"},
},
}
// Audio only segments are not supported
_, err = Transcode3(in, out)
assert.EqualError(t, err, "TranscoderInvalidVideo")
}
func TestTranscoder_StreamCopy_Validate_B_Frames(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
// Set up inputs, truncate test file
cmd := `
ffmpeg -i "$1"/../transcoder/test.ts -c:a copy -c:v copy -t 1 test-short.ts
# sanity check some assumptions here for the following set of tests
ffprobe -count_frames -show_streams -select_streams v test-short.ts | grep nb_read_frames=60
# Sanity check that we have B-frames in this sample
ffprobe -show_frames test-short.ts | grep pict_type=B
`
run(cmd)
// Test normal stream-copy case
in := &TranscodeOptionsIn{Fname: dir + "/test-short.ts"}
out := []TranscodeOptions{
{
Oname: dir + "/videocopy.ts",
VideoEncoder: ComponentOptions{Name: "copy"},
},
}
res, err := Transcode3(in, out)
if err != nil {
t.Error(err)
}
if res.Decoded.Frames != 0 || res.Encoded[0].Frames != 0 {
t.Error("Unexpected frame counts from stream copy")
t.Error(res)
}
cmd = `
# extract video track only, compare md5sums
ffmpeg -i test-short.ts -an -c:v copy -f md5 test-video.md5
ffmpeg -i videocopy.ts -an -c:v copy -f md5 videocopy.md5
diff -u test-video.md5 videocopy.md5
# ensure output has equal no of B-Frames as input
ffprobe -loglevel warning -show_frames -select_streams v -show_entries frame=pict_type videocopy.ts | grep pict_type=B | wc -l > read_pict_type.out
ffprobe -loglevel warning -show_frames -select_streams v -show_entries frame=pict_type test-short.ts | grep pict_type=B | wc -l > ffmpeg_read_pict_type.out
diff -u ffmpeg_read_pict_type.out read_pict_type.out
`
run(cmd)
}
func TestTranscoder_Drop(t *testing.T) {
run, dir := setupTest(t)
defer os.RemoveAll(dir)
cmd := `
cp "$1"/../transcoder/test.ts .
ffmpeg -i test.ts -c:a copy -c:v copy -t 1 test-short.ts
# sanity check some assumptions here for the following set of tests
ffprobe -count_frames -show_streams -select_streams v test-short.ts | grep nb_read_frames=60
`
run(cmd)
// Normal case : drop only video
in := &TranscodeOptionsIn{Fname: dir + "/test-short.ts"}
out := []TranscodeOptions{
{
Oname: dir + "/novideo.ts",
VideoEncoder: ComponentOptions{Name: "drop"},
},
}
res, err := Transcode3(in, out)
if err != nil {
t.Error(err)
}
if res.Decoded.Frames != 0 || res.Encoded[0].Frames != 0 {
t.Error("Unexpected count of decoded frames ", res.Decoded.Frames, res.Decoded.Pixels)
}
// Normal case: drop only audio
out = []TranscodeOptions{
{
Oname: dir + "/noaudio.ts",
AudioEncoder: ComponentOptions{Name: "drop"},
Profile: P144p30fps16x9,
},
}
res, err = Transcode3(in, out)
if err != nil {
t.Error(err)
}
if res.Decoded.Frames != 60 || res.Encoded[0].Frames != 31 {
t.Error("Unexpected count of decoded frames ", res.Decoded.Frames, res.Decoded.Pixels)