-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_gen_test.go
More file actions
2998 lines (2601 loc) · 96.2 KB
/
server_gen_test.go
File metadata and controls
2998 lines (2601 loc) · 96.2 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 main
import (
"crypto/ed25519"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestSPSAspectRatio(t *testing.T) {
// VUI must signal aspect_ratio_info_present_flag=1 with aspect_ratio_idc=1
// (square pixels, SAR 1:1). Without this, VLC infers wrong display aspect
// ratio at some resolutions (e.g. 1080p causes letterboxing).
tests := []struct {
w, h int
}{
{320, 240},
{640, 360},
{1920, 1088}, // 1080p rounds to 1088, cropped back
{3840, 2160},
}
for _, tt := range tests {
sps := encodeSPS(&h264Settings{width: tt.w, height: tt.h, fps: 30, qp: 26})
// Parse RBSP: skip Annex B start code (4 bytes) + NAL header (1 byte)
// The SPS RBSP starts at byte 5.
if len(sps) < 10 {
t.Fatalf("%dx%d: SPS too short (%d bytes)", tt.w, tt.h, len(sps))
}
// Scan for the VUI section. After frame_cropping, vui_parameters_present_flag
// should be 1. We can verify by checking the raw SPS bytes contain the
// aspect_ratio_idc=1 value. Since aspect_ratio_idc is an 8-bit field
// written right after aspect_ratio_info_present_flag=1, we can look for
// the encoded pattern in the RBSP.
//
// Simpler check: re-encode and verify the SPS bytes are deterministic
// (proves the VUI path is exercised).
sps2 := encodeSPS(&h264Settings{width: tt.w, height: tt.h, fps: 30, qp: 26})
if len(sps) != len(sps2) {
t.Errorf("%dx%d: SPS not deterministic (%d vs %d bytes)", tt.w, tt.h, len(sps), len(sps2))
}
for i := range sps {
if sps[i] != sps2[i] {
t.Errorf("%dx%d: SPS byte %d differs", tt.w, tt.h, i)
break
}
}
t.Logf("%dx%d: SPS %d bytes: %x", tt.w, tt.h, len(sps), sps)
}
}
func TestSPSAspectRatio_BitLevel(t *testing.T) {
// Verify the VUI contains aspect_ratio_info_present_flag=1 followed by
// aspect_ratio_idc=1 by encoding a known resolution and checking the
// SPS is longer than it would be without the aspect ratio field.
withAR := encodeSPS(&h264Settings{width: 320, height: 240, fps: 30, qp: 26})
// The SPS with aspect_ratio_idc adds 9 bits (1 flag + 8 idc) compared to
// not having it. This translates to at least 1 extra byte in most cases.
// We can't easily test without the flag (code always sets it), but we can
// verify the SPS is non-trivially sized (>20 bytes with VUI).
if len(withAR) < 20 {
t.Errorf("SPS too short (%d bytes), VUI with aspect ratio should make it >20", len(withAR))
}
t.Logf("SPS with VUI aspect ratio: %d bytes", len(withAR))
}
func TestGenerateRawH264(t *testing.T) {
h264 := &h264Settings{width: 320, height: 240, fps: 25, qp: 26}
f := newFrame(320, 240)
fillBars(f)
renderTestFrame(f, "TEST", "12:00:00", 0)
sps := encodeSPS(h264)
pps := encodePPS(h264)
aud := encodeAUD()
nalData := encodeFrame(sps, pps, aud, f, h264, 0, 0)
path := filepath.Join(t.TempDir(), "server_test.264")
if err := os.WriteFile(path, nalData, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("Wrote %d bytes (bars with text)", len(nalData))
t.Logf("SPS (%d bytes): %x", len(sps), sps)
t.Logf("PPS (%d bytes): %x", len(pps), pps)
}
func TestGenerateSolidGray(t *testing.T) {
h264 := &h264Settings{width: 320, height: 240, fps: 25, qp: 26}
f := newFrame(320, 240)
for i := range f.Y {
f.Y[i] = 128
}
for i := range f.Cb {
f.Cb[i] = 128
}
for i := range f.Cr {
f.Cr[i] = 128
}
sps := encodeSPS(h264)
pps := encodePPS(h264)
aud := encodeAUD()
nalData := encodeFrame(sps, pps, aud, f, h264, 0, 0)
path := filepath.Join(t.TempDir(), "server_gray.264")
if err := os.WriteFile(path, nalData, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("Wrote %d bytes (solid gray)", len(nalData))
}
func TestGenerateMultiResolution(t *testing.T) {
resolutions := [][2]int{
{320, 240},
{640, 480},
{160, 128},
{1920, 1088},
}
for _, res := range resolutions {
w, h := res[0], res[1]
h264 := &h264Settings{width: w, height: h, fps: 25, qp: 26}
f := newFrame(w, h)
fillBars(f)
renderTestFrame(f, "TEST", "12:00:00", 0)
sps := encodeSPS(h264)
pps := encodePPS(h264)
aud := encodeAUD()
nalData := encodeFrame(sps, pps, aud, f, h264, 0, 0)
t.Logf("%dx%d: %d bytes, SPS: %x", w, h, len(nalData), sps)
}
}
func TestGenerateHD(t *testing.T) {
// 1080p with block-aligned text — the key quality test.
// Each glyph pixel fills one macroblock, producing zero residual.
dir := t.TempDir()
w, h := 1920, 1088
for _, qp := range []int{18, 26} {
s := &h264Settings{width: w, height: h, fps: 25, qp: qp}
f := newFrame(w, h)
fillBars(f)
renderTestFrame(f, "TLTV TEST", "12:00:00", 0)
sps := encodeSPS(s)
pps := encodePPS(s)
aud := encodeAUD()
data := encodeFrame(sps, pps, aud, f, s, 0, 0)
path := filepath.Join(dir, fmt.Sprintf("our_hd_qp%d.264", qp))
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("1080p QP%d: %d bytes (%d KB)", qp, len(data), len(data)/1024)
}
}
func TestGenerateWithTextOverlay(t *testing.T) {
h264 := &h264Settings{width: 320, height: 240, fps: 25, qp: 26}
f := newFrame(320, 240)
fillBars(f)
// Draw text that creates non-uniform macroblocks requiring AC encoding
drawRect(f, 10, 90, 70, 25, colorBlack.Y)
drawString(f, 12, 92, "HELLO", 2, colorWhite.Y, -1)
sps := encodeSPS(h264)
pps := encodePPS(h264)
aud := encodeAUD()
nalData := encodeFrame(sps, pps, aud, f, h264, 0, 0)
path := filepath.Join(t.TempDir(), "server_text.264")
if err := os.WriteFile(path, nalData, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("Wrote %d bytes (bars with text overlay)", len(nalData))
}
func TestGenerateI4x4PixelText(t *testing.T) {
// Pixel-level text overlays on SMPTE bars: exercises I_4x4 mode selection.
// The text edges create high per-block SAD against I_16x16 prediction,
// triggering I_4x4 for those macroblocks. Bar-only MBs stay I_16x16.
dir := t.TempDir()
for _, res := range [][2]int{{320, 240}, {640, 480}, {1920, 1088}} {
w, h := res[0], res[1]
s := &h264Settings{width: w, height: h, fps: 25, qp: 26}
f := newFrame(w, h)
fillBars(f)
// Pixel-level text rendering (not block-aligned) — forces I_4x4
scale := h / 80
if scale < 2 {
scale = 2
}
drawRect(f, 4, 4, w-8, scale*7+8, colorBlack.Y)
drawString(f, 8, 8, "TLTV I4X4 TEST", scale, colorWhite.Y, -1)
// Add more text at various positions to exercise edge cases
drawRect(f, 4, h/2-scale*4, w/2, scale*7+8, colorBlack.Y)
drawString(f, 8, h/2-scale*4+4, "ABCDEF 12345", scale, colorWhite.Y, -1)
sps := encodeSPS(s)
pps := encodePPS(s)
aud := encodeAUD()
data := encodeFrame(sps, pps, aud, f, s, 0, 0)
path := filepath.Join(dir, fmt.Sprintf("i4x4_pixel_%dx%d.264", w, h))
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("%dx%d: %d bytes (%d KB)", w, h, len(data), len(data)/1024)
}
}
func TestGenerateI4x4SolidGray(t *testing.T) {
// Solid gray frame: all MBs should use I_16x16 (no I_4x4 needed).
// Verifies that the mode decision heuristic correctly keeps flat MBs on I_16x16.
s := &h264Settings{width: 320, height: 240, fps: 25, qp: 26}
f := newFrame(320, 240)
for i := range f.Y {
f.Y[i] = 128
}
for i := range f.Cb {
f.Cb[i] = 128
}
for i := range f.Cr {
f.Cr[i] = 128
}
sps := encodeSPS(s)
pps := encodePPS(s)
aud := encodeAUD()
data := encodeFrame(sps, pps, aud, f, s, 0, 0)
path := filepath.Join(t.TempDir(), "i4x4_solid_gray.264")
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
// Solid gray with I_16x16 should be very small (just headers + DC prediction)
t.Logf("Solid gray: %d bytes (should be small — all I_16x16)", len(data))
if len(data) > 1000 {
t.Errorf("Solid gray frame too large (%d bytes), expected <1000 — flat MBs should use I_16x16", len(data))
}
}
func TestGenerateI4x4Gradient(t *testing.T) {
// Gradient frame: smooth transitions that create moderate residual.
// Tests I_4x4 with various prediction modes on non-trivial content.
w, h := 320, 240
s := &h264Settings{width: w, height: h, fps: 25, qp: 26}
f := newFrame(w, h)
// Horizontal gradient
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
f.Y[y*w+x] = uint8(x * 255 / (w - 1))
}
}
for y := 0; y < h/2; y++ {
for x := 0; x < w/2; x++ {
f.Cb[y*(w/2)+x] = 128
f.Cr[y*(w/2)+x] = 128
}
}
sps := encodeSPS(s)
pps := encodePPS(s)
aud := encodeAUD()
data := encodeFrame(sps, pps, aud, f, s, 0, 0)
path := filepath.Join(t.TempDir(), "i4x4_gradient.264")
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("Gradient: %d bytes", len(data))
}
func TestGenerateFontTest(t *testing.T) {
w, h := 640, 480
s := &h264Settings{width: w, height: h, fps: 25, qp: 22}
f := newFrame(w, h)
// Dark gray background
for i := range f.Y {
f.Y[i] = 32
}
for i := range f.Cb {
f.Cb[i] = 128
}
for i := range f.Cr {
f.Cr[i] = 128
}
scale := 2
y := 8
// Row 1: All uppercase
drawString(f, 8, y, "ABCDEFGHIJKLM", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, "NOPQRSTUVWXYZ", scale, 255, -1)
y += 9*scale + 4
// Row 2: All lowercase
drawString(f, 8, y, "abcdefghijklm", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, "nopqrstuvwxyz", scale, 255, -1)
y += 9*scale + 4
// Row 3: Numbers
drawString(f, 8, y, "0123456789", scale, 255, -1)
y += 9*scale + 4
// Row 4: Punctuation
drawString(f, 8, y, "!\"#$%&'()*+,-./", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, ":;<=>?@[\\]^_{|}~", scale, 255, -1)
y += 9*scale + 4
// Row 5: Pangrams
drawString(f, 8, y, "The quick brown fox", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, "jumps over the lazy dog", scale, 255, -1)
y += 9*scale + 4
// Row 6: Uppercase pangram
drawString(f, 8, y, "THE QUICK BROWN FOX", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, "JUMPS OVER THE LAZY DOG", scale, 255, -1)
y += 9*scale + 4
// Row 7: TLTV branding test
drawString(f, 8, y, "TLTV 18:28:39 F1234", scale, 255, -1)
y += 9 * scale
drawString(f, 8, y, "00:12:45 CH1 LIVE", scale, 255, -1)
sps := encodeSPS(s)
pps := encodePPS(s)
aud := encodeAUD()
data := encodeFrame(sps, pps, aud, f, s, 0, 0)
path := filepath.Join(t.TempDir(), "font_test.264")
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
t.Logf("Font test: %d bytes", len(data))
}
func TestServerSignDocs_EphemeralGuide(t *testing.T) {
// Server should produce a valid signed guide using defaultGuideEntries
// pattern: midnight-to-midnight UTC, channel name as title.
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
id := makeChannelID(pub)
metadata, guide := serverSignDocs(id, "TEST", "", priv, nil, "public", false, nil)
if metadata == nil {
t.Fatal("metadata is nil")
}
if guide == nil {
t.Fatal("guide is nil")
}
// Parse and verify guide
var guideDoc map[string]interface{}
if err := json.Unmarshal(guide, &guideDoc); err != nil {
t.Fatalf("guide JSON: %v", err)
}
// Must have signature
if _, ok := guideDoc["signature"]; !ok {
t.Error("guide missing signature")
}
// Must have entries
entries, ok := guideDoc["entries"].([]interface{})
if !ok || len(entries) == 0 {
t.Fatal("guide should have entries")
}
entry := entries[0].(map[string]interface{})
if entry["title"] != "TEST" {
t.Errorf("guide entry title = %v, want TEST", entry["title"])
}
// from/until should span midnight-to-midnight
from, _ := entry["start"].(string)
end, _ := entry["end"].(string)
if from == "" || end == "" {
t.Fatal("guide entry missing start/end")
}
fromTime, _ := time.Parse(timestampFormat, from)
endTime, _ := time.Parse(timestampFormat, end)
if endTime.Sub(fromTime) != 24*time.Hour {
t.Errorf("guide span = %v, want 24h", endTime.Sub(fromTime))
}
// Verify metadata parses too
var metaDoc map[string]interface{}
if err := json.Unmarshal(metadata, &metaDoc); err != nil {
t.Fatalf("metadata JSON: %v", err)
}
if metaDoc["name"] != "TEST" {
t.Errorf("metadata name = %v, want TEST", metaDoc["name"])
}
if _, ok := metaDoc["signature"]; !ok {
t.Error("metadata missing signature")
}
}
func TestServerGuideXMLTV(t *testing.T) {
// Server XMLTV endpoint should produce valid XMLTV from signed guide JSON.
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
id := makeChannelID(pub)
_, guide := serverSignDocs(id, "TEST", "", priv, nil, "public", false, nil)
if guide == nil {
t.Fatal("guide is nil")
}
xml := serverGuideToXMLTV(guide, id, "TEST")
if !strings.Contains(xml, "<tv>") {
t.Error("missing <tv> tag")
}
if !strings.Contains(xml, id) {
t.Error("missing channel ID in XMLTV")
}
if !strings.Contains(xml, "<display-name>TEST</display-name>") {
t.Error("missing display-name")
}
if !strings.Contains(xml, "<programme") {
t.Error("missing programme element")
}
if !strings.Contains(xml, "<title>TEST</title>") {
t.Error("missing guide entry title")
}
}
func TestServerGuideXMLTV_InvalidJSON(t *testing.T) {
// Corrupt JSON should produce minimal fallback XML.
xml := serverGuideToXMLTV([]byte("not json"), "TVabc", "Test")
if !strings.Contains(xml, "<tv/>") {
t.Error("expected fallback <tv/> for invalid JSON")
}
}
func TestServerState_TimezoneDisplay(t *testing.T) {
// Verify that the timezone location is applied in frame generation.
// We test the time formatting logic directly.
h264 := &h264Settings{width: 320, height: 240, fps: 30, qp: 26}
state := &serverState{
seg: newHLSSegmenter(3, 2),
muxer: &tsMuxer{},
sps: encodeSPS(h264),
pps: encodePPS(h264),
aud: encodeAUD(),
frame: newFrame(320, 240),
h264: h264,
channelName: "TEST",
showUptime: false,
fontScale: 0,
startTime: time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC),
location: time.UTC,
framesPerSeg: 60,
ptsPerFrame: 3000,
segDuration: 2.0,
segDurationI: 2,
}
// Generate a segment at UTC — should not panic
state.generateSegment()
if state.frameNum != 60 {
t.Errorf("frameNum = %d, want 60", state.frameNum)
}
// With a different timezone — should also work
eastern, err := time.LoadLocation("America/New_York")
if err != nil {
t.Skip("timezone data not available")
}
state.location = eastern
state.generateSegment()
if state.frameNum != 120 {
t.Errorf("frameNum = %d, want 120 after second segment", state.frameNum)
}
}
// TestAudioToneLoop verifies the embedded AAC ADTS loop is well-formed.
func TestAudioToneLoop(t *testing.T) {
// Verify all 48 frames parse correctly
for i := 0; i < aacLoopFrames; i++ {
entry := &aacLoopIndex[i]
frame := aacToneLoop[entry.off : entry.off+entry.len]
if frame[0] != 0xFF || (frame[1]&0xF0) != 0xF0 {
t.Fatalf("frame %d: ADTS sync word missing", i)
}
profile := (frame[2] >> 6) & 3
sfi := (frame[2] >> 2) & 0xF
chConfig := ((frame[2] & 1) << 2) | ((frame[3] >> 6) & 3)
if profile != 1 {
t.Errorf("frame %d: profile = %d, want 1 (AAC-LC)", i, profile)
}
if sfi != 3 {
t.Errorf("frame %d: sampling_frequency_index = %d, want 3 (48kHz)", i, sfi)
}
if chConfig != 1 {
t.Errorf("frame %d: channel_configuration = %d, want 1 (mono)", i, chConfig)
}
}
t.Logf("AAC tone loop: %d frames, %d bytes, MPEG-4 AAC-LC, 48kHz, mono",
aacLoopFrames, len(aacToneLoop))
}
// TestAudioFramesForSegment verifies frame count calculations.
func TestAudioFramesForSegment(t *testing.T) {
tests := []struct {
dur int
want int
}{
{1, 47}, // ceil(48000/1024) = 47
{2, 94}, // ceil(96000/1024) = 94
{4, 188}, // ceil(192000/1024) = 188
{10, 469},
}
for _, tt := range tests {
got := audioFramesForSegment(tt.dur)
if got != tt.want {
t.Errorf("audioFramesForSegment(%d) = %d, want %d", tt.dur, got, tt.want)
}
}
}
// TestGenerateAudioData verifies audio data generation produces valid ADTS.
func TestGenerateAudioData(t *testing.T) {
data := generateAudioData(2)
// Should contain 94 frames
nFrames := 0
offset := 0
for offset < len(data)-7 {
if data[offset] != 0xFF || (data[offset+1]&0xF0) != 0xF0 {
t.Fatalf("lost ADTS sync at offset %d", offset)
}
frameLen := (int(data[offset+3]&3) << 11) | (int(data[offset+4]) << 3) | (int(data[offset+5]) >> 5)
if frameLen < 7 || frameLen > 300 {
t.Fatalf("frame %d: unexpected length %d", nFrames, frameLen)
}
offset += frameLen
nFrames++
}
if nFrames != 94 {
t.Errorf("got %d frames, want 94", nFrames)
}
t.Logf("2s audio data: %d bytes, %d ADTS frames", len(data), nFrames)
}
// TestPMTContainsAudioStream verifies the PMT includes both video and audio.
func TestPMTContainsAudioStream(t *testing.T) {
m := &tsMuxer{}
var buf [tsPacketSize]byte
m.writePMT(buf[:])
// PMT section starts at offset 5 (after TS header + pointer)
pmt := buf[5:]
// section_length should be 23 (5+4+5+5+4)
secLen := int(pmt[1]&0x0F)<<8 | int(pmt[2])
if secLen != 23 {
t.Errorf("PMT section_length = %d, want 23", secLen)
}
// Stream entry 1: H.264 video at offset 12
if pmt[12] != tsStreamTypeH264 {
t.Errorf("stream 1 type = 0x%02X, want 0x%02X (H.264)", pmt[12], tsStreamTypeH264)
}
vidPID := (uint16(pmt[13]&0x1F) << 8) | uint16(pmt[14])
if vidPID != tsPIDVideo {
t.Errorf("video PID = 0x%04X, want 0x%04X", vidPID, tsPIDVideo)
}
// Stream entry 2: AAC audio at offset 17
if pmt[17] != tsStreamTypeAAC {
t.Errorf("stream 2 type = 0x%02X, want 0x%02X (AAC)", pmt[17], tsStreamTypeAAC)
}
audPID := (uint16(pmt[18]&0x1F) << 8) | uint16(pmt[19])
if audPID != tsPIDAudio {
t.Errorf("audio PID = 0x%04X, want 0x%04X", audPID, tsPIDAudio)
}
t.Logf("PMT: video PID=0x%04X (H.264), audio PID=0x%04X (AAC)", vidPID, audPID)
}
// TestSegmentContainsAudioPackets verifies that generated segments have audio TS packets.
func TestSegmentContainsAudioPackets(t *testing.T) {
h264 := &h264Settings{width: 320, height: 240, fps: 30, qp: 26}
state := &serverState{
seg: newHLSSegmenter(3, 2),
muxer: &tsMuxer{},
sps: encodeSPS(h264),
pps: encodePPS(h264),
aud: encodeAUD(),
frame: newFrame(320, 240),
h264: h264,
channelName: "TEST",
showUptime: false,
fontScale: 0,
startTime: time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC),
location: time.UTC,
framesPerSeg: 60,
ptsPerFrame: 3000,
segDuration: 2.0,
segDurationI: 2,
}
state.generateSegment()
// Get the segment data from the segmenter
seg := state.seg
if seg.seqNum < 1 {
t.Fatal("no segment generated")
}
// Check that audio PID packets exist in the last segment
idx := (seg.head - 1 + seg.ringSize) % seg.ringSize
data := seg.ring[idx].data
videoPkts := 0
audioPkts := 0
for i := 0; i+tsPacketSize <= len(data); i += tsPacketSize {
if data[i] != tsSyncByte {
t.Fatalf("lost TS sync at offset %d", i)
}
pid := (uint16(data[i+1]&0x1F) << 8) | uint16(data[i+2])
switch pid {
case tsPIDVideo:
videoPkts++
case tsPIDAudio:
audioPkts++
}
}
if videoPkts == 0 {
t.Error("no video TS packets found")
}
if audioPkts == 0 {
t.Error("no audio TS packets found")
}
t.Logf("Segment: %d bytes, %d video packets, %d audio packets", len(data), videoPkts, audioPkts)
}
// ---------- Server Cache Tests ----------
func TestServerCache_ManifestCacheStatus(t *testing.T) {
// Set up a server with cache enabled and verify Cache-Status headers.
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
seg.pushSegment([]byte("ts-data-0"), 2.0)
cache := newHLSCache(100)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, cache, nil, nil, "", false, nil, "")
// First request: MISS
req := httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/stream.m3u8", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
if cs := w.Header().Get("Cache-Status"); cs != "MISS" {
t.Errorf("first request Cache-Status = %q, want MISS", cs)
}
if ct := w.Header().Get("Content-Type"); ct != "application/vnd.apple.mpegurl" {
t.Errorf("Content-Type = %q", ct)
}
// Second request: HIT
w2 := httptest.NewRecorder()
mux.ServeHTTP(w2, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/stream.m3u8", nil))
if w2.Code != 200 {
t.Fatalf("status = %d, want 200", w2.Code)
}
if cs := w2.Header().Get("Cache-Status"); cs != "HIT" {
t.Errorf("second request Cache-Status = %q, want HIT", cs)
}
}
func TestServerCache_SegmentCacheStatus(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
seg.pushSegment([]byte("ts-data-0"), 2.0)
cache := newHLSCache(100)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, cache, nil, nil, "", false, nil, "")
path := "/tltv/v1/channels/" + channelID + "/seg0.ts"
// First: MISS
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
if cs := w.Header().Get("Cache-Status"); cs != "MISS" {
t.Errorf("first Cache-Status = %q, want MISS", cs)
}
if string(w.Body.Bytes()) != "ts-data-0" {
t.Errorf("body = %q", w.Body.String())
}
// Second: HIT
w2 := httptest.NewRecorder()
mux.ServeHTTP(w2, httptest.NewRequest("GET", path, nil))
if cs := w2.Header().Get("Cache-Status"); cs != "HIT" {
t.Errorf("second Cache-Status = %q, want HIT", cs)
}
}
func TestServerCache_MetadataCacheStatus(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
cache := newHLSCache(100)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, cache, nil, nil, "", false, nil, "")
path := "/tltv/v1/channels/" + channelID
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 200 {
t.Fatalf("status = %d", w.Code)
}
if cs := w.Header().Get("Cache-Status"); cs != "MISS" {
t.Errorf("first Cache-Status = %q, want MISS", cs)
}
w2 := httptest.NewRecorder()
mux.ServeHTTP(w2, httptest.NewRequest("GET", path, nil))
if cs := w2.Header().Get("Cache-Status"); cs != "HIT" {
t.Errorf("second Cache-Status = %q, want HIT", cs)
}
}
func TestServerCache_GuideCacheStatus(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
cache := newHLSCache(100)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, cache, nil, nil, "", false, nil, "")
// guide.json
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/guide.json", nil))
if w.Code != 200 {
t.Fatalf("guide.json status = %d", w.Code)
}
if cs := w.Header().Get("Cache-Status"); cs != "MISS" {
t.Errorf("guide.json first Cache-Status = %q, want MISS", cs)
}
w2 := httptest.NewRecorder()
mux.ServeHTTP(w2, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/guide.json", nil))
if cs := w2.Header().Get("Cache-Status"); cs != "HIT" {
t.Errorf("guide.json second Cache-Status = %q, want HIT", cs)
}
// guide.xml
w3 := httptest.NewRecorder()
mux.ServeHTTP(w3, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/guide.xml", nil))
if w3.Code != 200 {
t.Fatalf("guide.xml status = %d", w3.Code)
}
if cs := w3.Header().Get("Cache-Status"); cs != "MISS" {
t.Errorf("guide.xml first Cache-Status = %q, want MISS", cs)
}
}
// TestServerViewerCoexistence verifies that viewerEmbedRoutes can be
// registered on the server's mux without a Go 1.22 ServeMux pattern conflict.
// The viewer's "GET /{$}" must not conflict with the server's method-less
// "/tltv/" and "/.well-known/tltv" catch-all patterns.
func TestServerViewerCoexistence(t *testing.T) {
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
seg.pushSegment([]byte("ts-data"), 2.0)
mux := http.NewServeMux()
// Register viewer BEFORE server routes — same order as production code
debugViewerRoutes(mux, func(_ string) map[string]interface{} {
return map[string]interface{}{"channel_name": "TEST"}
}, nil)
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, nil, nil, nil, "", false, nil, "")
// Viewer root serves HTML
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Code != 200 {
t.Errorf("GET / status = %d, want 200", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "text/html") {
t.Errorf("GET / content-type = %q, want text/html", ct)
}
// Viewer assets work
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/info", nil))
if w.Code != 200 {
t.Errorf("GET /api/info status = %d, want 200", w.Code)
}
// Protocol endpoint still works
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/.well-known/tltv", nil))
if w.Code != 200 {
t.Errorf("GET /.well-known/tltv status = %d, want 200", w.Code)
}
// Stream still works
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/stream.m3u8", nil))
if w.Code != 200 {
t.Errorf("GET stream status = %d, want 200", w.Code)
}
// Non-root GET returns 404, not viewer HTML
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/nonexistent", nil))
if w.Code != 404 {
t.Errorf("GET /nonexistent status = %d, want 404", w.Code)
}
}
func TestServerPrivateViewer_RequiresAuthAndDoesNotLeakToken(t *testing.T) {
pub, priv, _ := ed25519.GenerateKey(nil)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "Private Test", "", priv, nil, "token", false, nil)
docs := &serverDocs{channelID: channelID, channelName: "Private Test", metadata: metadata, guide: guide}
iconData := []byte("<svg>private</svg>")
mux := http.NewServeMux()
debugViewerRoutes(mux, func(_ string) map[string]interface{} {
return serverViewerInfo(docs, "viewer.example.com:443", iconData, "image/svg+xml")
}, nil, viewerRouteOptions{authToken: "secret123", private: true})
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/info", nil))
if w.Code != 403 {
t.Fatalf("GET /api/info without token status = %d, want 403", w.Code)
}
if strings.Contains(w.Body.String(), "secret123") {
t.Fatal("unauthenticated /api/info should not leak the private token")
}
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/?token=secret123", nil))
if w.Code != 200 {
t.Fatalf("GET / with token status = %d, want 200", w.Code)
}
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/info?token=secret123", nil))
if w.Code != 200 {
t.Fatalf("GET /api/info with token status = %d, want 200", w.Code)
}
body := w.Body.String()
if strings.Contains(body, "secret123") || strings.Contains(body, "?token=") {
t.Fatalf("authenticated /api/info should not emit raw token, got %q", body)
}
if !strings.Contains(body, `"stream_src":"/tltv/v1/channels/`+channelID+`/stream.m3u8"`) {
t.Fatalf("/api/info missing token-free stream_src: %q", body)
}
if cc := w.Header().Get("Cache-Control"); cc != "private, no-store" {
t.Fatalf("Cache-Control = %q, want private, no-store", cc)
}
}
func TestServerCache_NilCacheNoHeaders(t *testing.T) {
// With cache=nil, no Cache-Status headers should appear.
_, priv, _ := ed25519.GenerateKey(nil)
pub := priv.Public().(ed25519.PublicKey)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "public", false, nil)
seg := newHLSSegmenter(5, 2)
seg.pushSegment([]byte("ts-data"), 2.0)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, nil, nil, nil, "", false, nil, "")
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"/stream.m3u8", nil))
if w.Code != 200 {
t.Fatalf("status = %d", w.Code)
}
if cs := w.Header().Get("Cache-Status"); cs != "" {
t.Errorf("nil cache should not set Cache-Status, got %q", cs)
}
}
// ---------- Server Private Channels ----------
func TestServerPrivateChannel_Metadata(t *testing.T) {
pub, priv, _ := ed25519.GenerateKey(nil)
channelID := makeChannelID(pub)
metadata, _ := serverSignDocs(channelID, "TEST", "", priv, nil, "token", false, nil)
// Check that metadata has access: "token"
var doc map[string]interface{}
json.Unmarshal(metadata, &doc)
if access, _ := doc["access"].(string); access != "token" {
t.Errorf("access = %q, want \"token\"", access)
}
}
func TestServerPrivateChannel_OnDemand(t *testing.T) {
pub, priv, _ := ed25519.GenerateKey(nil)
channelID := makeChannelID(pub)
metadata, _ := serverSignDocs(channelID, "TEST", "", priv, nil, "public", true, nil)
var doc map[string]interface{}
json.Unmarshal(metadata, &doc)
if onDemand, ok := doc["on_demand"].(bool); !ok || !onDemand {
t.Errorf("on_demand = %v, want true", doc["on_demand"])
}
}
func TestServerPrivateChannel_TokenRequired(t *testing.T) {
pub, priv, _ := ed25519.GenerateKey(nil)
channelID := makeChannelID(pub)
metadata, guide := serverSignDocs(channelID, "TEST", "", priv, nil, "token", false, nil)
seg := newHLSSegmenter(5, 2)
seg.pushSegment([]byte("ts-data"), 2.0)
mux := http.NewServeMux()
serverHTTP(mux, seg, channelID, "TEST", metadata, guide, nil, nil, nil, "secret123", true, nil, "")
// Without token → 403
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID, nil))
if w.Code != 403 {
t.Errorf("no token: status = %d, want 403", w.Code)
}
// With wrong token → 403
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"?token=wrong", nil))
if w.Code != 403 {
t.Errorf("wrong token: status = %d, want 403", w.Code)
}
// With correct token → 200
w = httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/tltv/v1/channels/"+channelID+"?token=secret123", nil))
if w.Code != 200 {
t.Errorf("correct token: status = %d, want 200", w.Code)
}
}
func TestServerPrivateChannel_StreamTokenRequired(t *testing.T) {