-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_h264.go
More file actions
2332 lines (2096 loc) · 63.9 KB
/
server_h264.go
File metadata and controls
2332 lines (2096 loc) · 63.9 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 (
"math/bits"
)
// H.264 Baseline profile encoder with adaptive macroblock type selection.
// Uses Intra_16x16 prediction for flat regions (DC/Vertical/Horizontal modes)
// and Intra_4x4 prediction for detailed regions (9 directional modes per block).
// CAVLC entropy coding. Designed for test signal rendering: SMPTE bars with
// text overlays, but handles arbitrary source content.
//
// Reference: ITU-T H.264 (02/2014), sections 7.3, 7.4, 8.5, 9.2.
// i4x4SADThreshold is the SAD threshold per 4×4 block for I_4x4 mode decision.
// If any block's SAD against I_16x16 prediction exceeds this value (12 average
// per pixel × 16 pixels), the entire macroblock switches to I_4x4.
const i4x4SADThreshold = 192
// chromaQPTable maps luma QP ≥ 30 to chroma QP (H.264 Table 8-15).
var chromaQPTable = [...]int{29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39}
// h264Settings holds configurable encoder parameters.
// width/height are the encoded dimensions (aligned to multiples of 16).
// cropRight/cropBottom tell the decoder how many pixels to crop for
// non-16-aligned source dimensions (stored in SPS frame_cropping).
type h264Settings struct {
width int
height int
cropRight int
cropBottom int
fps int
qp int
}
// H.264 level table: select level based on resolution and frame rate.
// Each entry: maxMBs/sec threshold, level_idc.
var levelTable = [][2]int{
{1485, 10}, // 1.0: 176x144 @ 15
{3000, 11}, // 1.1: 320x240 @ 10
{6000, 12}, // 1.2: 320x240 @ 20
{11880, 13}, // 1.3: 352x288 @ 30
{11880, 20}, // 2.0: 352x288 @ 30
{19800, 21}, // 2.1: 352x576 @ 25
{20250, 22}, // 2.2: 720x480 @ 15
{40500, 30}, // 3.0: 720x480 @ 30
{108000, 31}, // 3.1: 1280x720 @ 30
{216000, 32}, // 3.2: 1280x720 @ 60
{245760, 40}, // 4.0: 2048x1024 @ 30
{245760, 41}, // 4.1: 2048x1024 @ 30
{522240, 42}, // 4.2: 2048x1080 @ 60
{589824, 50}, // 5.0: 3672x1536 @ 26
{983040, 51}, // 5.1: 4096x2160 @ 30
{2073600, 52}, // 5.2: 4096x2160 @ 60
}
// selectLevel returns the H.264 level_idc for the given resolution and fps.
func selectLevel(width, height, fps int) int {
mbsPerSec := (width / 16) * (height / 16) * fps
for _, entry := range levelTable {
if mbsPerSec <= entry[0] {
return entry[1]
}
}
return 52 // max
}
// bitWriter accumulates bits MSB-first for H.264 bitstream generation.
type bitWriter struct {
buf []byte
curBit uint // bits written into current byte (0-7)
}
func newBitWriter(capacity int) *bitWriter {
return &bitWriter{buf: make([]byte, 0, capacity)}
}
func (w *bitWriter) writeBit(b uint8) {
if w.curBit == 0 {
w.buf = append(w.buf, 0)
}
if b != 0 {
w.buf[len(w.buf)-1] |= 1 << (7 - w.curBit)
}
w.curBit++
if w.curBit == 8 {
w.curBit = 0
}
}
func (w *bitWriter) writeBits(val uint32, n int) {
for i := n - 1; i >= 0; i-- {
w.writeBit(uint8((val >> i) & 1))
}
}
func (w *bitWriter) writeUE(val uint32) {
// Exp-Golomb unsigned: write (bits-1) leading zeros, then val+1
vp1 := val + 1
numBits := bits.Len32(vp1)
for i := 0; i < numBits-1; i++ {
w.writeBit(0)
}
w.writeBits(vp1, numBits)
}
func (w *bitWriter) writeSE(val int32) {
// Signed Exp-Golomb: map to unsigned
var uval uint32
if val > 0 {
uval = uint32(2*val - 1)
} else if val < 0 {
uval = uint32(-2 * val)
}
w.writeUE(uval)
}
func (w *bitWriter) alignToByte() {
if w.curBit > 0 {
for w.curBit != 0 {
w.writeBit(0)
}
}
}
// rbspTrailingBits writes a 1 followed by zeros to byte-align.
func (w *bitWriter) rbspTrailingBits() {
w.writeBit(1)
w.alignToByte()
}
func (w *bitWriter) bytes() []byte {
return w.buf
}
// insertEBSP applies Annex B emulation prevention: after 0x00 0x00,
// if the next byte is 0x00, 0x01, 0x02, or 0x03, insert 0x03 before it.
func insertEBSP(rbsp []byte) []byte {
out := make([]byte, 0, len(rbsp)+len(rbsp)/100)
count := 0
for _, b := range rbsp {
if count >= 2 && b <= 3 {
out = append(out, 0x03)
count = 0
}
out = append(out, b)
if b == 0 {
count++
} else {
count = 0
}
}
return out
}
// annexBNALU wraps RBSP data in Annex B framing: start code + NAL header + EBSP data.
func annexBNALU(naluType, refIDC uint8, rbsp []byte) []byte {
header := (refIDC << 5) | (naluType & 0x1F)
ebsp := insertEBSP(rbsp)
out := make([]byte, 0, 4+1+len(ebsp))
out = append(out, 0x00, 0x00, 0x00, 0x01) // 4-byte start code
out = append(out, header)
out = append(out, ebsp...)
return out
}
// --- SPS (Sequence Parameter Set) ---
// encodeSPS generates an SPS for Baseline profile with the given settings.
func encodeSPS(s *h264Settings) []byte {
mbCols := s.width / 16
mbRows := s.height / 16
level := selectLevel(s.width, s.height, s.fps)
w := newBitWriter(32)
w.writeBits(66, 8) // profile_idc = Baseline
w.writeBit(1) // constraint_set0_flag
w.writeBit(1) // constraint_set1_flag
w.writeBit(0) // constraint_set2_flag
w.writeBit(0) // constraint_set3_flag
w.writeBit(0) // constraint_set4_flag
w.writeBit(0) // constraint_set5_flag
w.writeBits(0, 2) // reserved_zero_2bits
w.writeBits(uint32(level), 8) // level_idc
w.writeUE(0) // seq_parameter_set_id
w.writeUE(0) // log2_max_frame_num_minus4 → frame_num is u(4)
w.writeUE(0) // pic_order_cnt_type = 0
w.writeUE(0) // log2_max_pic_order_cnt_lsb_minus4 → POC is u(4)
w.writeUE(0) // max_num_ref_frames = 0 (I-only)
w.writeBit(0) // gaps_in_frame_num_value_allowed_flag
w.writeUE(uint32(mbCols - 1)) // pic_width_in_mbs_minus1
w.writeUE(uint32(mbRows - 1)) // pic_height_in_map_units_minus1
w.writeBit(1) // frame_mbs_only_flag
// mb_adaptive_frame_field_flag: absent (frame_mbs_only=1)
w.writeBit(0) // direct_8x8_inference_flag
// Frame cropping for non-16-aligned source dimensions.
// Luma crop units are 2 pixels for 4:2:0 frame_mbs_only (§7.4.2.1.1).
cropRight := s.cropRight / 2
cropBottom := s.cropBottom / 2
if cropRight > 0 || cropBottom > 0 {
w.writeBit(1) // frame_cropping_flag
w.writeUE(0) // frame_crop_left_offset
w.writeUE(uint32(cropRight)) // frame_crop_right_offset
w.writeUE(0) // frame_crop_top_offset
w.writeUE(uint32(cropBottom)) // frame_crop_bottom_offset
} else {
w.writeBit(0) // frame_cropping_flag
}
w.writeBit(1) // vui_parameters_present_flag = 1
// Minimal VUI: timing info with EBSP-safe values.
// Use num_units_in_tick=1001 to avoid 00 00 00 sequences in the RBSP
// that trigger EBSP emulation prevention byte insertion.
w.writeBit(1) // aspect_ratio_info_present_flag = 1
w.writeBits(1, 8) // aspect_ratio_idc = 1 (square pixels, SAR 1:1)
w.writeBit(0) // overscan_info_present_flag
w.writeBit(0) // video_signal_type_present_flag
w.writeBit(0) // chroma_loc_info_present_flag
w.writeBit(1) // timing_info_present_flag
// fps = time_scale / (2 * num_units_in_tick) → time_scale = 2 * fps * 1001
w.writeBits(1001, 32) // num_units_in_tick
w.writeBits(uint32(2*s.fps*1001), 32) // time_scale
w.writeBit(1) // fixed_frame_rate_flag
w.writeBit(0) // nal_hrd_parameters_present_flag
w.writeBit(0) // vcl_hrd_parameters_present_flag
// low_delay_hrd_flag: absent (no HRD)
w.writeBit(0) // pic_struct_present_flag
w.writeBit(0) // bitstream_restriction_flag
w.rbspTrailingBits()
return annexBNALU(7, 3, w.bytes()) // SPS: nal_unit_type=7, nal_ref_idc=3
}
// --- PPS (Picture Parameter Set) ---
func encodePPS(s *h264Settings) []byte {
w := newBitWriter(8)
w.writeUE(0) // pic_parameter_set_id
w.writeUE(0) // seq_parameter_set_id
w.writeBit(0) // entropy_coding_mode_flag = CAVLC (Baseline)
w.writeBit(0) // bottom_field_pic_order_in_frame_present_flag
w.writeUE(0) // num_slice_groups_minus1
w.writeUE(0) // num_ref_idx_l0_default_active_minus1
w.writeUE(0) // num_ref_idx_l1_default_active_minus1
w.writeBit(0) // weighted_pred_flag
w.writeBits(0, 2) // weighted_bipred_idc
w.writeSE(int32(s.qp - 26)) // pic_init_qp_minus26
w.writeSE(0) // pic_init_qs_minus26
w.writeSE(0) // chroma_qp_index_offset
w.writeBit(0) // deblocking_filter_control_present_flag
w.writeBit(0) // constrained_intra_pred_flag
w.writeBit(0) // redundant_pic_cnt_present_flag
w.rbspTrailingBits()
return annexBNALU(8, 3, w.bytes()) // PPS: nal_unit_type=8, nal_ref_idc=3
}
// --- Access Unit Delimiter ---
func encodeAUD() []byte {
w := newBitWriter(2)
w.writeBits(0, 3) // primary_pic_type = 0 (I-slices)
w.rbspTrailingBits()
return annexBNALU(9, 0, w.bytes()) // AUD: nal_unit_type=9, nal_ref_idc=0
}
// --- Block Scan Order ---
// blk4x4Pos maps luma4x4BlkIdx to (rowOffset, colOffset) within the MB.
// Follows H.264 Table 6-2: Z-scan of 4x4 blocks within 8x8 blocks.
// This is the mandatory block ordering for I_16x16 DC collection and AC transmission.
var blk4x4Pos = [16][2]int{
{0, 0}, {0, 4}, {4, 0}, {4, 4}, // 8x8 block 0 (top-left)
{0, 8}, {0, 12}, {4, 8}, {4, 12}, // 8x8 block 1 (top-right)
{8, 0}, {8, 4}, {12, 0}, {12, 4}, // 8x8 block 2 (bottom-left)
{8, 8}, {8, 12}, {12, 8}, {12, 12}, // 8x8 block 3 (bottom-right)
}
// blk4x4Grid maps luma4x4BlkIdx to (row, col) in 4x4-block units within MB.
var blk4x4Grid = [16][2]int{
{0, 0}, {0, 1}, {1, 0}, {1, 1},
{0, 2}, {0, 3}, {1, 2}, {1, 3},
{2, 0}, {2, 1}, {3, 0}, {3, 1},
{2, 2}, {2, 3}, {3, 2}, {3, 3},
}
// mbGridToBlkIdx maps (row, col) in 4×4-block units within a MB to Z-scan block index.
// Inverse of blk4x4Grid.
var mbGridToBlkIdx = [4][4]int{
{0, 1, 4, 5},
{2, 3, 6, 7},
{8, 9, 12, 13},
{10, 11, 14, 15},
}
// --- I_4x4 CBP Tables ---
// golombToIntraCBP maps Exp-Golomb code index to CBP value for Intra macroblocks.
// H.264 Table 9-4 (forward mapping: codeNum → coded_block_pattern).
var golombToIntraCBP = [48]int{
47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46,
16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4,
8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41,
}
// intraCBPToGolomb is the inverse: CBP value → Exp-Golomb code index.
// Initialized in init().
var intraCBPToGolomb [48]int
func init() {
for i, cbp := range golombToIntraCBP {
intraCBPToGolomb[cbp] = i
}
}
// --- Macroblock Encoder State ---
// mbEncoder holds per-frame state for macroblock encoding.
// Created once per frame in encodeIDRFrame; per-MB methods take only (mbX, mbY).
type mbEncoder struct {
bw *bitWriter
f *Frame
reconY []uint8
reconCb []uint8
reconCr []uint8
tcGrid []int
cbTCGrid []int
crTCGrid []int
mbModeGrid []int8
gridW int
chromaGridW int
width int
height int
chromaW int
qp int
chromaQP int
mbCols int
}
// chromaData holds chroma encoding results shared between the bitstream
// writing and reconstruction phases. Computed once, used twice.
type chromaData struct {
mode int
cbPredArr [64]uint8
crPredArr [64]uint8
cbDCQ [4]int32
crDCQ [4]int32
cbACBlocks [4][15]int32
crACBlocks [4][15]int32
chromaCBP int
}
// --- IDR Slice ---
// encodeIDRFrame encodes one complete IDR frame with I_16x16 and I_4x4 macroblocks.
// Maintains reconstruction buffers, totalCoeff grid, and per-block mode grid.
func encodeIDRFrame(f *Frame, s *h264Settings, frameNum, idrPicID int) []byte {
mbCols := s.width / 16
mbRows := s.height / 16
bw := newBitWriter(64 * 1024)
// Slice header (ITU-T H.264 §7.3.3)
bw.writeUE(0) // first_mb_in_slice
bw.writeUE(2) // slice_type = 2 (I)
bw.writeUE(0) // pic_parameter_set_id
bw.writeBits(0, 4) // frame_num = 0 for IDR
bw.writeUE(uint32(idrPicID & 0xFFFF)) // idr_pic_id
bw.writeBits(0, 4) // pic_order_cnt_lsb
bw.writeBit(0) // no_output_of_prior_pics_flag
bw.writeBit(0) // long_term_reference_flag
bw.writeSE(0) // slice_qp_delta = 0
gridW := s.width / 4
mbModeGrid := make([]int8, (s.height/4)*gridW)
for i := range mbModeGrid {
mbModeGrid[i] = -1
}
enc := &mbEncoder{
bw: bw,
f: f,
reconY: make([]uint8, s.width*s.height),
reconCb: make([]uint8, (s.width/2)*(s.height/2)),
reconCr: make([]uint8, (s.width/2)*(s.height/2)),
tcGrid: make([]int, (s.height/4)*gridW),
cbTCGrid: make([]int, (s.height/8)*(s.width/8)),
crTCGrid: make([]int, (s.height/8)*(s.width/8)),
mbModeGrid: mbModeGrid,
gridW: gridW,
chromaGridW: s.width / 8,
width: s.width,
height: s.height,
chromaW: s.width / 2,
qp: s.qp,
chromaQP: chromaQPFromLuma(s.qp),
mbCols: mbCols,
}
for mbY := 0; mbY < mbRows; mbY++ {
for mbX := 0; mbX < mbCols; mbX++ {
enc.encodeMB(mbX, mbY)
}
}
bw.rbspTrailingBits()
return annexBNALU(5, 3, bw.bytes())
}
// --- Macroblock Encoding ---
// encodeMB dispatches to either I_16x16 or I_4x4 encoding based on a per-block
// residual energy heuristic. Flat/smooth MBs use I_16x16 (fewer mode signaling bits);
// MBs with fine detail (text, edges) use I_4x4 for better prediction quality.
// Computes I_16x16 prediction once and reuses it for both the decision and encoding.
func (e *mbEncoder) encodeMB(mbX, mbY int) {
// Compute I_16x16 prediction once (used for both mode decision and encoding)
lumaMode, lumaPredArr := selectLumaMode(e.f, e.reconY, e.width, e.height, mbX, mbY)
// Check if any 4x4 block has high residual against I_16x16 prediction
useI4x4 := false
for blkIdx := 0; blkIdx < 16; blkIdx++ {
blkRow := blk4x4Pos[blkIdx][0]
blkCol := blk4x4Pos[blkIdx][1]
sad := 0
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
d := int(e.f.Y[(mbY*16+blkRow+r)*e.width+mbX*16+blkCol+c]) - int(lumaPredArr[(blkRow+r)*16+blkCol+c])
if d < 0 {
d = -d
}
sad += d
}
}
if sad > i4x4SADThreshold {
useI4x4 = true
break
}
}
if useI4x4 {
e.encodeMB_I4x4(mbX, mbY)
} else {
e.encodeMB_I16x16(mbX, mbY, lumaMode, lumaPredArr)
}
}
// --- Intra_16x16 Macroblock Encoding ---
// encodeMB_I16x16 encodes one macroblock using Intra_16x16 prediction with CAVLC.
// Selects the best luma prediction mode (DC/Vertical/Horizontal) per MB.
// Uses H.264 Z-scan block ordering, proper nC prediction from the totalCoeff grid,
// and spec-correct inverse Hadamard → scale reconstruction (§8.5.6).
func (e *mbEncoder) encodeMB_I16x16(mbX, mbY, lumaMode int, lumaPredArr [256]uint8) {
bw := e.bw
qp := e.qp
width := e.width
// Compute residuals and DCT for each 4x4 sub-block in Z-scan order.
// dcCoeffs[blkIdx] is indexed by luma4x4BlkIdx for the Hadamard transform.
var dcCoeffs [16]int32
var acBlocks [16][15]int32 // AC coefficients in zigzag scan order per sub-block
hasAC := false
for blkIdx := 0; blkIdx < 16; blkIdx++ {
blkRow := blk4x4Pos[blkIdx][0]
blkCol := blk4x4Pos[blkIdx][1]
var block [16]int32
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
py := mbY*16 + blkRow + r
px := mbX*16 + blkCol + c
block[r*4+c] = int32(e.f.Y[py*width+px]) - int32(lumaPredArr[(blkRow+r)*16+blkCol+c])
}
}
trans := forwardDCT4x4(block)
dcCoeffs[blkIdx] = trans[0]
// Quantize AC coefficients and check if any are non-zero
quantAC := quantize4x4(trans, qp)
for i := 1; i < 16; i++ {
acBlocks[blkIdx][i-1] = quantAC[zigzag4x4[i]]
if quantAC[zigzag4x4[i]] != 0 {
hasAC = true
}
}
}
// Forward Hadamard + quantize DC
hadDC := forwardHadamard4x4(dcCoeffs)
quantDC := quantizeDC4x4(hadDC, qp)
// Chroma: residual computation, prediction, DCT, quantize
cd := e.encodeChromaResidual(mbX, mbY)
// Determine coded block pattern
lumaCBP := 0
if hasAC {
lumaCBP = 15
}
// mb_type for I_16x16: 1 + predMode + chromaCBP*4 + lumaCBPFlag*12
// predMode: 0=Vertical, 1=Horizontal, 2=DC (H.264 Table 7-11)
lumaCBPFlag := 0
if lumaCBP == 15 {
lumaCBPFlag = 1
}
mbType := 1 + lumaMode + cd.chromaCBP*4 + lumaCBPFlag*12
bw.writeUE(uint32(mbType))
bw.writeUE(uint32(cd.mode)) // intra_chroma_pred_mode
bw.writeSE(0) // mb_qp_delta = 0
// Encode luma DC block (always present for I_16x16).
// nC for DC block: hi264 uses AC nC grid at MB's top-left 4x4 block position.
// The DC block's own totalCoeff is NOT stored back into the grid.
dcNC := computeNC(e.tcGrid, e.gridW, width, e.height, mbX, mbY, 0, 0)
var dcScan [16]int32
for i := 0; i < 16; i++ {
dcScan[i] = quantDC[zigzag4x4[i]]
}
encodeCAVLCBlock(bw, dcScan[:], dcNC, 16)
// Encode luma AC blocks in Z-scan order with proper nC prediction
if lumaCBP == 15 {
for blkIdx := 0; blkIdx < 16; blkIdx++ {
nC := computeNC(e.tcGrid, e.gridW, width, e.height, mbX, mbY, blk4x4Grid[blkIdx][0], blk4x4Grid[blkIdx][1])
tc := encodeCAVLCBlock(bw, acBlocks[blkIdx][:], nC, 15)
frameRow := mbY*4 + blk4x4Grid[blkIdx][0]
frameCol := mbX*4 + blk4x4Grid[blkIdx][1]
e.tcGrid[frameRow*e.gridW+frameCol] = tc
}
} else {
for blkIdx := 0; blkIdx < 16; blkIdx++ {
frameRow := mbY*4 + blk4x4Grid[blkIdx][0]
frameCol := mbX*4 + blk4x4Grid[blkIdx][1]
e.tcGrid[frameRow*e.gridW+frameCol] = 0
}
}
// Encode chroma bitstream (DC/AC coefficients)
e.writeChromaBitstream(&cd, mbX, mbY)
// --- Reconstruction: simulate decoder (§8.5.6, §8.5.12) ---
// Luma DC: spec §8.5.6 — inverse Hadamard FIRST, then scale.
invHadDC := invHadamard4x4(quantDC)
reconDCvals := scaleDC4x4(invHadDC, qp)
for blkIdx := 0; blkIdx < 16; blkIdx++ {
blkRow := blk4x4Pos[blkIdx][0]
blkCol := blk4x4Pos[blkIdx][1]
var reconBlock [16]int32
reconBlock[0] = reconDCvals[blkIdx]
if hasAC {
var quantACRaster [16]int32
for j := 1; j < 16; j++ {
quantACRaster[zigzag4x4[j]] = acBlocks[blkIdx][j-1]
}
invAC := invQuantize4x4(quantACRaster, qp)
for i := 1; i < 16; i++ {
reconBlock[i] = invAC[i]
}
}
idctBlock := inverseDCT4x4(reconBlock)
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
val := int32(lumaPredArr[(blkRow+r)*16+blkCol+c]) + idctBlock[r*4+c]
if val < 0 {
val = 0
} else if val > 255 {
val = 255
}
e.reconY[(mbY*16+blkRow+r)*width+mbX*16+blkCol+c] = uint8(val)
}
}
}
// Chroma reconstruction
e.reconstructChroma(&cd, mbX, mbY)
}
// --- Intra_4x4 Macroblock Encoding ---
// encodeMB_I4x4 encodes one macroblock using Intra_4x4 prediction with CAVLC.
// Each 4×4 block gets its own directional prediction mode (9 modes, §8.3.1.2),
// predicted from already-reconstructed neighbors including earlier blocks in
// the same MB. No Hadamard transform — DC is position [0] of regular 4×4 DCT.
// Chroma encoding is shared via encodeChromaResidual / writeChromaBitstream / reconstructChroma.
func (e *mbEncoder) encodeMB_I4x4(mbX, mbY int) {
bw := e.bw
qp := e.qp
width := e.width
// Phase 1: Sequential prediction, residual computation, and reconstruction.
// Each block must be fully reconstructed before the next block's prediction.
var modes [16]int
var quantBlocks [16][16]int32 // full 16-coeff quantized blocks (zigzag-scanned)
var hasNonZero [16]bool
for blkIdx := 0; blkIdx < 16; blkIdx++ {
mode, pred := selectIntra4x4Mode(e.f, e.reconY, width, e.height, mbX, mbY, blkIdx, e.mbCols)
modes[blkIdx] = mode
blkRow := blk4x4Pos[blkIdx][0]
blkCol := blk4x4Pos[blkIdx][1]
var block [16]int32
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
py := mbY*16 + blkRow + r
px := mbX*16 + blkCol + c
block[r*4+c] = int32(e.f.Y[py*width+px]) - int32(pred[r*4+c])
}
}
trans := forwardDCT4x4(block)
quant := quantize4x4(trans, qp)
for i := 0; i < 16; i++ {
quantBlocks[blkIdx][i] = quant[zigzag4x4[i]]
if quant[zigzag4x4[i]] != 0 {
hasNonZero[blkIdx] = true
}
}
var reconBlock [16]int32
if hasNonZero[blkIdx] {
reconBlock = invQuantize4x4(quant, qp)
}
idctBlock := inverseDCT4x4(reconBlock)
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
val := int32(pred[r*4+c]) + idctBlock[r*4+c]
if val < 0 {
val = 0
} else if val > 255 {
val = 255
}
e.reconY[(mbY*16+blkRow+r)*width+mbX*16+blkCol+c] = uint8(val)
}
}
frameRow := mbY*4 + blk4x4Grid[blkIdx][0]
frameCol := mbX*4 + blk4x4Grid[blkIdx][1]
e.mbModeGrid[frameRow*e.gridW+frameCol] = int8(mode)
}
// Phase 2: Compute per-8×8 luma CBP (§7.4.5.3)
// Each bit covers one 8×8 block containing four 4×4 sub-blocks.
lumaCBP := 0
for b8 := 0; b8 < 4; b8++ {
base := b8 * 4
for i := 0; i < 4; i++ {
if hasNonZero[base+i] {
lumaCBP |= 1 << uint(b8)
break
}
}
}
// Phase 3: Chroma residual (shared with I_16x16)
cd := e.encodeChromaResidual(mbX, mbY)
// Phase 4: Write bitstream
// mb_type = 0 for I_NxN (I_4x4)
bw.writeUE(0) // mb_type = 0 → ue(0) = single bit "1"
// Prediction mode signaling (§7.3.5.1): 16 blocks in Z-scan order
for blkIdx := 0; blkIdx < 16; blkIdx++ {
blkRow := blk4x4Grid[blkIdx][0]
blkCol := blk4x4Grid[blkIdx][1]
frameRow := mbY*4 + blkRow
frameCol := mbX*4 + blkCol
modeA := -1
if frameCol > 0 {
modeA = int(e.mbModeGrid[frameRow*e.gridW+(frameCol-1)])
}
modeB := -1
if frameRow > 0 {
modeB = int(e.mbModeGrid[(frameRow-1)*e.gridW+frameCol])
}
predicted := derivePredIntra4x4Mode(modeA, modeB)
actual := modes[blkIdx]
if actual == predicted {
bw.writeBit(1)
} else {
bw.writeBit(0)
rem := actual
if actual > predicted {
rem = actual - 1
}
bw.writeBits(uint32(rem), 3)
}
}
bw.writeUE(uint32(cd.mode)) // intra_chroma_pred_mode
// coded_block_pattern as me(v) — mapped Exp-Golomb (§7.4.5.3, Table 9-4)
cbpValue := cd.chromaCBP*16 + lumaCBP
bw.writeUE(uint32(intraCBPToGolomb[cbpValue]))
// mb_qp_delta — only if CBP > 0
if cbpValue > 0 {
bw.writeSE(0)
}
// Phase 5: Encode luma residual blocks (maxNumCoeff=16, per-8×8 CBP)
for blkIdx := 0; blkIdx < 16; blkIdx++ {
b8 := blkIdx / 4
frameRow := mbY*4 + blk4x4Grid[blkIdx][0]
frameCol := mbX*4 + blk4x4Grid[blkIdx][1]
if lumaCBP&(1<<uint(b8)) != 0 {
nC := computeNC(e.tcGrid, e.gridW, width, e.height, mbX, mbY, blk4x4Grid[blkIdx][0], blk4x4Grid[blkIdx][1])
tc := encodeCAVLCBlock(bw, quantBlocks[blkIdx][:], nC, 16)
e.tcGrid[frameRow*e.gridW+frameCol] = tc
} else {
e.tcGrid[frameRow*e.gridW+frameCol] = 0
}
}
// Phase 6: Encode chroma bitstream (shared with I_16x16)
e.writeChromaBitstream(&cd, mbX, mbY)
// Phase 7: Chroma reconstruction (shared with I_16x16)
e.reconstructChroma(&cd, mbX, mbY)
}
// --- Shared Chroma Encoding ---
//
// Chroma processing is identical for I_16x16 and I_4x4 macroblocks.
// These three methods handle the full pipeline: residual computation,
// bitstream writing, and reconstruction.
// encodeChromaResidual computes chroma prediction, residuals, DCT, quantization,
// and coded block pattern. Returns a chromaData struct used by the bitstream
// writer and reconstructor.
func (e *mbEncoder) encodeChromaResidual(mbX, mbY int) chromaData {
cd := chromaData{}
hasChromaDC := false
hasChromaAC := false
var cbDCCoeffs, crDCCoeffs [4]int32
cd.mode, cd.cbPredArr, cd.crPredArr = selectChromaMode(e.f, e.reconCb, e.reconCr, e.chromaW, mbX, mbY)
for cIdx := 0; cIdx < 4; cIdx++ {
cRow := (cIdx / 2) * 4
cCol := (cIdx % 2) * 4
var cbBlock, crBlock [16]int32
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
cy := mbY*8 + cRow + r
cx := mbX*8 + cCol + c
cbBlock[r*4+c] = int32(e.f.Cb[cy*e.chromaW+cx]) - int32(cd.cbPredArr[(cRow+r)*8+cCol+c])
crBlock[r*4+c] = int32(e.f.Cr[cy*e.chromaW+cx]) - int32(cd.crPredArr[(cRow+r)*8+cCol+c])
}
}
cbTrans := forwardDCT4x4(cbBlock)
crTrans := forwardDCT4x4(crBlock)
cbDCCoeffs[cIdx] = cbTrans[0]
crDCCoeffs[cIdx] = crTrans[0]
cbQuantAC := quantize4x4(cbTrans, e.chromaQP)
crQuantAC := quantize4x4(crTrans, e.chromaQP)
for i := 1; i < 16; i++ {
cd.cbACBlocks[cIdx][i-1] = cbQuantAC[zigzag4x4[i]]
cd.crACBlocks[cIdx][i-1] = crQuantAC[zigzag4x4[i]]
if cbQuantAC[zigzag4x4[i]] != 0 || crQuantAC[zigzag4x4[i]] != 0 {
hasChromaAC = true
}
}
}
cd.cbDCQ = quantizeChromaDC2x2(forwardHadamard2x2(cbDCCoeffs), e.qp)
cd.crDCQ = quantizeChromaDC2x2(forwardHadamard2x2(crDCCoeffs), e.qp)
for i := 0; i < 4; i++ {
if cd.cbDCQ[i] != 0 || cd.crDCQ[i] != 0 {
hasChromaDC = true
break
}
}
if hasChromaAC {
cd.chromaCBP = 2
} else if hasChromaDC {
cd.chromaCBP = 1
}
return cd
}
// writeChromaBitstream encodes chroma DC and AC coefficients into the bitstream.
func (e *mbEncoder) writeChromaBitstream(cd *chromaData, mbX, mbY int) {
if cd.chromaCBP > 0 {
encodeChromaDCBlock(e.bw, cd.cbDCQ[:])
encodeChromaDCBlock(e.bw, cd.crDCQ[:])
}
if cd.chromaCBP == 2 {
for cIdx := 0; cIdx < 4; cIdx++ {
blkRow := cIdx / 2
blkCol := cIdx % 2
nC := computeChromaNC(e.cbTCGrid, e.chromaGridW, mbX, mbY, blkRow, blkCol)
tc := encodeCAVLCBlock(e.bw, cd.cbACBlocks[cIdx][:], nC, 15)
e.cbTCGrid[(mbY*2+blkRow)*e.chromaGridW+mbX*2+blkCol] = tc
}
for cIdx := 0; cIdx < 4; cIdx++ {
blkRow := cIdx / 2
blkCol := cIdx % 2
nC := computeChromaNC(e.crTCGrid, e.chromaGridW, mbX, mbY, blkRow, blkCol)
tc := encodeCAVLCBlock(e.bw, cd.crACBlocks[cIdx][:], nC, 15)
e.crTCGrid[(mbY*2+blkRow)*e.chromaGridW+mbX*2+blkCol] = tc
}
} else {
for cIdx := 0; cIdx < 4; cIdx++ {
blkRow := cIdx / 2
blkCol := cIdx % 2
e.cbTCGrid[(mbY*2+blkRow)*e.chromaGridW+mbX*2+blkCol] = 0
e.crTCGrid[(mbY*2+blkRow)*e.chromaGridW+mbX*2+blkCol] = 0
}
}
}
// reconstructChroma simulates the decoder's chroma reconstruction (§8.5.7, §8.5.12).
func (e *mbEncoder) reconstructChroma(cd *chromaData, mbX, mbY int) {
if cd.chromaCBP > 0 {
invCbHad := invHadamard2x2(cd.cbDCQ)
invCrHad := invHadamard2x2(cd.crDCQ)
scaledCb := scaleChromaDC2x2(invCbHad, e.qp)
scaledCr := scaleChromaDC2x2(invCrHad, e.qp)
for cIdx := 0; cIdx < 4; cIdx++ {
cRow := (cIdx / 2) * 4
cCol := (cIdx % 2) * 4
var cbRecon, crRecon [16]int32
cbRecon[0] = scaledCb[cIdx]
crRecon[0] = scaledCr[cIdx]
if cd.chromaCBP == 2 {
var cbACRaster, crACRaster [16]int32
for j := 1; j < 16; j++ {
cbACRaster[zigzag4x4[j]] = cd.cbACBlocks[cIdx][j-1]
crACRaster[zigzag4x4[j]] = cd.crACBlocks[cIdx][j-1]
}
invCbAC := invQuantize4x4(cbACRaster, e.chromaQP)
invCrAC := invQuantize4x4(crACRaster, e.chromaQP)
for i := 1; i < 16; i++ {
cbRecon[i] = invCbAC[i]
crRecon[i] = invCrAC[i]
}
}
cbIDCT := inverseDCT4x4(cbRecon)
crIDCT := inverseDCT4x4(crRecon)
for r := 0; r < 4; r++ {
for c := 0; c < 4; c++ {
cbVal := int32(cd.cbPredArr[(cRow+r)*8+cCol+c]) + cbIDCT[r*4+c]
crVal := int32(cd.crPredArr[(cRow+r)*8+cCol+c]) + crIDCT[r*4+c]
if cbVal < 0 {
cbVal = 0
} else if cbVal > 255 {
cbVal = 255
}
if crVal < 0 {
crVal = 0
} else if crVal > 255 {
crVal = 255
}
e.reconCb[(mbY*8+cRow+r)*e.chromaW+mbX*8+cCol+c] = uint8(cbVal)
e.reconCr[(mbY*8+cRow+r)*e.chromaW+mbX*8+cCol+c] = uint8(crVal)
}
}
}
} else {
for y := 0; y < 8; y++ {
for x := 0; x < 8; x++ {
e.reconCb[(mbY*8+y)*e.chromaW+mbX*8+x] = cd.cbPredArr[y*8+x]
e.reconCr[(mbY*8+y)*e.chromaW+mbX*8+x] = cd.crPredArr[y*8+x]
}
}
}
}
// computeNC computes the nC prediction for a 4x4 block (§9.2.1).
// blk4Row, blk4Col are in 4x4-block units within the MB.
func computeNC(tcGrid []int, gridW, width, height, mbX, mbY, blk4Row, blk4Col int) int {
frameRow := mbY*4 + blk4Row
frameCol := mbX*4 + blk4Col
hasTop := frameRow > 0
hasLeft := frameCol > 0
if !hasTop && !hasLeft {
return 0
}
nA, nB := -1, -1
if hasLeft {
nA = tcGrid[frameRow*gridW+(frameCol-1)]
}
if hasTop {
nB = tcGrid[(frameRow-1)*gridW+frameCol]
}
if nA >= 0 && nB >= 0 {
return (nA + nB + 1) >> 1
}
if nA >= 0 {
return nA
}
return nB
}
// computeChromaNC computes the nC prediction for a chroma 4x4 block (§9.2.1).
// Uses chroma-resolution grid (2 blocks per MB dimension for 4:2:0).
func computeChromaNC(tcGrid []int, gridW, mbX, mbY, blkRow, blkCol int) int {
row := mbY*2 + blkRow
col := mbX*2 + blkCol
hasTop := row > 0
hasLeft := col > 0
if !hasTop && !hasLeft {
return 0
}
nA, nB := -1, -1
if hasLeft {
nA = tcGrid[row*gridW+(col-1)]
}
if hasTop {
nB = tcGrid[(row-1)*gridW+col]
}
if nA >= 0 && nB >= 0 {
return (nA + nB + 1) >> 1
}
if nA >= 0 {
return nA
}
return nB
}
// reconDCPred computes the DC prediction value from reconstructed neighbors.
// Mode 2 (DC): average of left column and/or top row from the reconstruction buffer.
func reconDCPred(reconY []uint8, width, height, mbX, mbY int) uint8 {
hasTop := mbY > 0
hasLeft := mbX > 0
if !hasTop && !hasLeft {
return 128
}
sum := 0
count := 0
if hasTop {
topY := mbY*16 - 1
for x := 0; x < 16; x++ {
sum += int(reconY[topY*width+mbX*16+x])
}
count += 16
}
if hasLeft {
leftX := mbX*16 - 1
for y := 0; y < 16; y++ {
sum += int(reconY[(mbY*16+y)*width+leftX])
}
count += 16
}
return uint8((sum + count/2) / count)
}
// lumaPredict16x16 computes the 16x16 luma prediction array for a given mode (§8.3.3).
// Returns a [256]uint8 with per-pixel predictions for the entire luma MB.
// Mode 0: Vertical (each column copies from top neighbor row).
// Mode 1: Horizontal (each row copies from left neighbor column).
// Mode 2: DC (flat value from average of top row + left column).
func lumaPredict16x16(reconY []uint8, width, height, mbX, mbY, mode int) [256]uint8 {
var pred [256]uint8
hasTop := mbY > 0
hasLeft := mbX > 0
switch mode {
case 0: // Vertical — each column copies from top neighbor (§8.3.3.1)
if hasTop {
topRow := mbY*16 - 1
for x := 0; x < 16; x++ {
val := reconY[topRow*width+mbX*16+x]
for y := 0; y < 16; y++ {
pred[y*16+x] = val
}
}