-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcabac_macroblock.py
More file actions
2262 lines (1870 loc) · 75.5 KB
/
cabac_macroblock.py
File metadata and controls
2262 lines (1870 loc) · 75.5 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
# h264/entropy/cabac_macroblock.py
"""CABAC macroblock-level decoding.
High-level macroblock decoding using CABAC entropy coding.
Wraps lower-level syntax element decoding with neighbor context.
H.264 Spec Reference: Section 7.3.5 - Macroblock layer syntax
"""
from typing import List, Dict, Any, Optional, TYPE_CHECKING
import numpy as np
from entropy.cabac_residual import (
decode_residual_block_cabac,
decode_residual_block_cabac_with_cbf,
decode_residual_block_8x8,
)
from entropy.cabac_syntax import (
decode_mb_skip_flag,
decode_mb_type_i,
decode_mb_type_p,
decode_mb_type_b,
decode_sub_mb_type_p,
decode_sub_mb_type_b,
decode_intra_chroma_pred_mode,
decode_cbp_luma,
decode_cbp_chroma,
decode_prev_intra4x4_pred_mode_flag,
decode_rem_intra4x4_pred_mode,
decode_ref_idx,
decode_mvd_lx,
decode_mb_qp_delta,
)
if TYPE_CHECKING:
from entropy.cabac_arith import CABACDecoder
from entropy.cabac_context import CABACContext
# Context indices
CTX_TRANSFORM_SIZE_FLAG = 399
CTX_MB_FIELD_DECODING_FLAG = 70
CTX_END_OF_SLICE_FLAG = 276
# Sub-MB index to 4x4 block base position (blk_x, blk_y)
_SUB_MB_BASE = [(0, 0), (2, 0), (0, 2), (2, 2)]
# Sub-partition block offsets within a sub-MB for each sub_mb_type
# P: type 0=8x8, 1=8x4, 2=4x8, 3=4x4
_P_SUB_PART_OFFSETS = {
0: [(0, 0)], # 8x8: 1 MVD
1: [(0, 0), (0, 1)], # 8x4: top, bottom
2: [(0, 0), (1, 0)], # 4x8: left, right
3: [(0, 0), (1, 0), (0, 1), (1, 1)], # 4x4: raster scan
}
# Block coverage (rows, cols) for each sub-partition type
_P_SUB_PART_COVERAGE = {
0: [(2, 2)], # 8x8
1: [(1, 2), (1, 2)], # 8x4: each covers 1 row x 2 cols
2: [(2, 1), (2, 1)], # 4x8: each covers 2 rows x 1 col
3: [(1, 1), (1, 1), (1, 1), (1, 1)], # 4x4: each covers 1x1
}
# B sub-partition block offsets within a sub-MB (H.264 Table 7-18)
# sub_type 0 (Direct) derives MVDs, not decoded — no entry needed
_B_SUB_PART_OFFSETS = {
1: [(0, 0)], # B_L0_8x8
2: [(0, 0)], # B_L1_8x8
3: [(0, 0)], # B_Bi_8x8
4: [(0, 0), (0, 1)], # B_L0_8x4
5: [(0, 0), (1, 0)], # B_L0_4x8
6: [(0, 0), (0, 1)], # B_L1_8x4
7: [(0, 0), (1, 0)], # B_L1_4x8
8: [(0, 0), (0, 1)], # B_Bi_8x4
9: [(0, 0), (1, 0)], # B_Bi_4x8
10: [(0, 0), (1, 0), (0, 1), (1, 1)], # B_L0_4x4
11: [(0, 0), (1, 0), (0, 1), (1, 1)], # B_L1_4x4
12: [(0, 0), (1, 0), (0, 1), (1, 1)], # B_Bi_4x4
}
_B_SUB_PART_COVERAGE = {
1: [(2, 2)], # 8x8
2: [(2, 2)],
3: [(2, 2)],
4: [(1, 2), (1, 2)], # 8x4
5: [(2, 1), (2, 1)], # 4x8
6: [(1, 2), (1, 2)],
7: [(2, 1), (2, 1)],
8: [(1, 2), (1, 2)],
9: [(2, 1), (2, 1)],
10: [(1, 1), (1, 1), (1, 1), (1, 1)], # 4x4
11: [(1, 1), (1, 1), (1, 1), (1, 1)],
12: [(1, 1), (1, 1), (1, 1), (1, 1)],
}
def _compute_ref_idx_ctx_inc(
blk_x: int,
blk_y: int,
cur_refs: np.ndarray,
left_refs: Optional[np.ndarray],
top_refs: Optional[np.ndarray],
) -> int:
"""Compute ctxIdxInc for ref_idx bin 0 (H.264 Table 9-34).
condTermFlagA = 1 if left neighbor's ref_idx > 0, else 0.
condTermFlagB = 1 if top neighbor's ref_idx > 0, else 0.
ctxIdxInc = condTermFlagA + 2 * condTermFlagB.
Args:
blk_x, blk_y: Top-left 4x4 block position of current partition (0-3)
cur_refs: Current MB's ref_idx grid [4, 4]
left_refs: Left MB's ref_idx grid [4, 4] or None
top_refs: Top MB's ref_idx grid [4, 4] or None
Returns:
ctxIdxInc: 0, 1, 2, or 3
"""
# Left neighbor (A)
cond_a = 0
if blk_x > 0:
cond_a = 1 if cur_refs[blk_y, blk_x - 1] > 0 else 0
elif left_refs is not None:
cond_a = 1 if left_refs[blk_y, 3] > 0 else 0
# Top neighbor (B)
cond_b = 0
if blk_y > 0:
cond_b = 1 if cur_refs[blk_y - 1, blk_x] > 0 else 0
elif top_refs is not None:
cond_b = 1 if top_refs[3, blk_x] > 0 else 0
return cond_a + 2 * cond_b
def _compute_mvd_ctx_inc(
comp: int,
blk_x: int,
blk_y: int,
cur_mvds: np.ndarray,
left_mvds: Optional[np.ndarray],
top_mvds: Optional[np.ndarray],
) -> int:
"""Compute ctxIdxInc for MVD bin0 (H.264 Section 9.3.3.1.1.7).
Args:
comp: 0=x, 1=y
blk_x, blk_y: Current 4x4 block position (0-3)
cur_mvds: Current MB's MVD grid [4, 4, 2]
left_mvds: Left MB's MVD grid [4, 4, 2] or None
top_mvds: Top MB's MVD grid [4, 4, 2] or None
Returns:
ctxIdxInc: 0, 1, or 2
"""
# Left neighbor (A)
abs_a = 0
if blk_x > 0:
abs_a = abs(int(cur_mvds[blk_y, blk_x - 1, comp]))
elif left_mvds is not None:
abs_a = abs(int(left_mvds[blk_y, 3, comp]))
# Top neighbor (B)
abs_b = 0
if blk_y > 0:
abs_b = abs(int(cur_mvds[blk_y - 1, blk_x, comp]))
elif top_mvds is not None:
abs_b = abs(int(top_mvds[3, blk_x, comp]))
total = abs_a + abs_b
if total < 3:
return 0
elif total > 32:
return 2
else:
return 1
def decode_mb_skip_flag_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
slice_type: int,
mb_info: Dict[str, Any],
) -> int:
"""Decode mb_skip_flag with neighbor context from mb_info.
Args:
decoder: CABAC decoder
contexts: Context models
slice_type: 0=P, 1=B, 2=I
mb_info: Dict with mb_x, mb_y, left_available, top_available,
left_skip, top_skip
Returns:
0 (not skipped) or 1 (skipped)
"""
mb_x = mb_info.get('mb_x', 0)
mb_y = mb_info.get('mb_y', 0)
# H.264 9.3.3.1.1.3: condTermFlagN = 1 if neighbor available AND NOT skip
left_available = mb_info.get('left_available', False)
top_available = mb_info.get('top_available', False)
left_cond = left_available and not mb_info.get('left_skip', False)
top_cond = top_available and not mb_info.get('top_skip', False)
return decode_mb_skip_flag(
decoder, contexts, slice_type, mb_x, mb_y, left_cond, top_cond
)
def decode_mb_type_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
slice_type: int,
mb_info: Dict[str, Any],
) -> int:
"""Decode mb_type with neighbor context.
H.264 Section 9.3.3.1.1.3: condTermFlagN = 1 if neighbor available
and NOT I_NxN (I_4x4/I_8x8), 0 otherwise.
Args:
decoder: CABAC decoder
contexts: Context models
slice_type: 0=P, 1=B, 2=I
mb_info: Neighbor information
Returns:
mb_type value
"""
if slice_type == 2: # I-slice
# Compute condTermFlagA + condTermFlagB for mb_type context
left_available = mb_info.get('left_available', False)
top_available = mb_info.get('top_available', False)
left_mb_type = mb_info.get('left_mb_type', None)
top_mb_type = mb_info.get('top_mb_type', None)
# condTermFlag = 1 if neighbor available AND NOT I_NxN (type 0)
cond_a = 1 if (left_available and left_mb_type is not None and left_mb_type != 0) else 0
cond_b = 1 if (top_available and top_mb_type is not None and top_mb_type != 0) else 0
ctx_inc = cond_a + cond_b
return decode_mb_type_i(decoder, contexts, ctx_inc=ctx_inc)
elif slice_type == 0: # P-slice
return decode_mb_type_p(decoder, contexts)
else: # B-slice
# H.264 9.3.3.1.1.3: condTermFlagN = 1 if neighbor available
# and mb_type != B_Direct_16x16 (type 0) and not skip
left_available = mb_info.get('left_available', False)
top_available = mb_info.get('top_available', False)
left_mb_type = mb_info.get('left_mb_type', None)
top_mb_type = mb_info.get('top_mb_type', None)
left_skip = mb_info.get('left_skip', False)
top_skip = mb_info.get('top_skip', False)
cond_a = 1 if (left_available and left_mb_type is not None
and left_mb_type != 0 and not left_skip) else 0
cond_b = 1 if (top_available and top_mb_type is not None
and top_mb_type != 0 and not top_skip) else 0
ctx_inc = cond_a + cond_b
return decode_mb_type_b(decoder, contexts, ctx_inc=ctx_inc)
def decode_sub_mb_type_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
slice_type: int,
mb_type: int = 0,
) -> int:
"""Decode sub_mb_type for P_8x8 or B_8x8 macroblocks.
Args:
decoder: CABAC decoder
contexts: Context models
slice_type: 0=P, 1=B
mb_type: Parent macroblock type (not used, for API compatibility)
Returns:
sub_mb_type value
"""
if slice_type == 0: # P-slice
return decode_sub_mb_type_p(decoder, contexts)
else: # B-slice
return decode_sub_mb_type_b(decoder, contexts)
def decode_intra_chroma_pred_mode_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
mb_info: Dict[str, Any],
) -> int:
"""Decode intra_chroma_pred_mode with neighbor context.
H.264 Section 9.3.3.1.1.8:
ctxIdxInc = condTermFlagA + condTermFlagB
condTermFlagN = 0 if N unavailable, else (chroma_pred_mode_N != 0 ? 1 : 0)
Args:
decoder: CABAC decoder
contexts: Context models
mb_info: Neighbor information
Returns:
Chroma prediction mode (0=DC, 1=Horizontal, 2=Vertical, 3=Plane)
"""
left_available = mb_info.get('left_available', False)
top_available = mb_info.get('top_available', False)
left_mode = mb_info.get('left_intra_chroma_pred_mode',
mb_info.get('left_chroma_mode', 0)) if left_available else 0
top_mode = mb_info.get('top_intra_chroma_pred_mode',
mb_info.get('top_chroma_mode', 0)) if top_available else 0
# condTermFlag = 1 if neighbor available AND chroma_pred_mode != 0
cond_a = 1 if (left_available and left_mode != 0) else 0
cond_b = 1 if (top_available and top_mode != 0) else 0
ctx_inc = cond_a + cond_b
return decode_intra_chroma_pred_mode(decoder, contexts, ctx_inc=ctx_inc)
def decode_cbp_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
mb_info: Dict[str, Any],
is_inter: bool = False,
) -> int:
"""Decode coded_block_pattern.
Args:
decoder: CABAC decoder
contexts: Context models
mb_info: Neighbor information with cbp values
is_inter: True for inter macroblocks
Returns:
CBP value (bits 0-3: luma, bits 4-5: chroma)
"""
# Get mb_type from mb_info for context selection
mb_type = mb_info.get('mb_type', 0)
# Get neighbor CBP values for context derivation
left_available = mb_info.get('left_available', False)
top_available = mb_info.get('top_available', False)
# Extract neighbor luma CBP (bits 0-3)
left_cbp = mb_info.get('left_cbp', 0) if left_available else -1
top_cbp = mb_info.get('top_cbp', 0) if top_available else -1
# For luma CBP context, we need just the luma bits (0-3)
left_cbp_luma = (left_cbp & 0x0F) if left_cbp >= 0 else -1
top_cbp_luma = (top_cbp & 0x0F) if top_cbp >= 0 else -1
# Extract neighbor chroma CBP (bits 4-5 shifted to 0-1 range)
left_cbp_chroma = ((left_cbp >> 4) & 0x03) if left_cbp >= 0 else -1
top_cbp_chroma = ((top_cbp >> 4) & 0x03) if top_cbp >= 0 else -1
# Decode luma CBP (4 bits) with neighbor context
cbp_luma = decode_cbp_luma(decoder, contexts, mb_type, left_cbp_luma, top_cbp_luma)
# Decode chroma CBP (2 bits) with neighbor context
cbp_chroma = decode_cbp_chroma(decoder, contexts, mb_type, left_cbp_chroma, top_cbp_chroma)
return cbp_luma | (cbp_chroma << 4)
def decode_transform_size_8x8_flag_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
mb_info: Dict[str, Any],
) -> int:
"""Decode transform_size_8x8_flag.
Args:
decoder: CABAC decoder
contexts: Context models
mb_info: Neighbor information
Returns:
0 (4x4 transform) or 1 (8x8 transform)
"""
# Context depends on neighbor transform sizes
left_8x8 = mb_info.get('left_transform_8x8', False) if mb_info.get('left_available', False) else False
top_8x8 = mb_info.get('top_transform_8x8', False) if mb_info.get('top_available', False) else False
ctx_inc = (1 if left_8x8 else 0) + (1 if top_8x8 else 0)
ctx_idx = CTX_TRANSFORM_SIZE_FLAG + ctx_inc
return decoder.decode_decision(contexts[ctx_idx])
def decode_mb_pred_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
mb_type: int,
slice_type: int,
mb_info: Dict[str, Any],
) -> Dict[str, Any]:
"""Decode mb_pred or sub_mb_pred.
H.264 Section 7.3.5.1 (mb_pred) and 7.3.5.2 (sub_mb_pred).
Parses ref_idx and MVD for each partition in syntax order.
Args:
decoder: CABAC decoder
contexts: Context models
mb_type: Macroblock type
slice_type: Slice type
mb_info: Neighbor information
Returns:
Dict with intra_pred_modes, ref_idx, mvd values, sub_mb_types
"""
result = {
'intra_pred_modes': [],
'ref_idx_l0': [],
'ref_idx_l1': [],
'mvd_l0': [],
'mvd_l1': [],
'sub_mb_types': [],
}
is_intra = _is_intra_mb_type(mb_type, slice_type)
if is_intra:
# Intra prediction modes
intra_base = mb_type
if slice_type == 0:
intra_base = mb_type - 5
elif slice_type == 1:
intra_base = mb_type - 23
if intra_base == 0: # I_NxN (I_4x4 or I_8x8)
# I_8x8: 4 prediction modes; I_4x4: 16 prediction modes
t8x8 = mb_info.get('transform_size_8x8_flag', 0)
num_modes = 4 if t8x8 else 16
for _ in range(num_modes):
if decode_prev_intra4x4_pred_mode_flag(decoder, contexts) == 1:
result['intra_pred_modes'].append(-1)
else:
mode = decode_rem_intra4x4_pred_mode(decoder, contexts)
result['intra_pred_modes'].append(mode)
result['intra_chroma_pred_mode'] = decode_intra_chroma_pred_mode_cabac(
decoder, contexts, mb_info
)
return result
num_ref_l0 = mb_info.get('num_ref_idx_l0_active', 1)
num_ref_l1 = mb_info.get('num_ref_idx_l1_active', 1)
if slice_type == 0: # P-slice
_decode_p_mb_pred(decoder, contexts, mb_type, num_ref_l0, result, mb_info)
elif slice_type == 1: # B-slice
_decode_b_mb_pred(decoder, contexts, mb_type, num_ref_l0, num_ref_l1, result, mb_info)
return result
def _decode_p_mb_pred(
decoder: 'CABACDecoder',
contexts: list,
mb_type: int,
num_ref_l0: int,
result: dict,
mb_info: dict,
) -> None:
"""Decode P-slice mb_pred or sub_mb_pred."""
if mb_type == 3: # P_8x8
_decode_p_sub_mb_pred(decoder, contexts, num_ref_l0, result, mb_info)
return
if mb_type == 4: # P_8x8ref0
_decode_p_sub_mb_pred(decoder, contexts, 1, result, mb_info)
return
# Regular P partitions: 0=16x16, 1=16x8, 2=8x16
num_parts = _get_num_partitions(mb_type, 0)
# Partition top-left block positions: 16x16→(0,0), 16x8→(0,0)/(0,2), 8x16→(0,0)/(2,0)
part_positions = [(0, 0)]
if mb_type == 1: # P_L0_16x8
part_positions = [(0, 0), (0, 2)]
elif mb_type == 2: # P_L0_8x16
part_positions = [(0, 0), (2, 0)]
# ref_idx context derivation needs neighbor grids
cur_refs_l0 = np.zeros((4, 4), dtype=np.int8)
left_refs_l0 = mb_info.get('left_mb_ref_l0')
top_refs_l0 = mb_info.get('top_mb_ref_l0')
# Partition coverage in 4x4 blocks: 16x16→(4,4), 16x8→(4,2), 8x16→(2,4)
if mb_type == 0:
part_rows, part_cols = 4, 4
elif mb_type == 1:
part_rows, part_cols = 2, 4
else:
part_rows, part_cols = 4, 2
# ref_idx_l0 for all partitions
for part_idx in range(num_parts):
blk_x, blk_y = part_positions[part_idx]
ctx_inc = _compute_ref_idx_ctx_inc(blk_x, blk_y, cur_refs_l0,
left_refs_l0, top_refs_l0)
ref = decode_ref_idx(decoder, contexts, 0, num_ref_l0, ctx_inc)
result['ref_idx_l0'].append(ref)
cur_refs_l0[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols] = ref
result['ref_idx_grid_l0'] = cur_refs_l0
# MVD grid for neighbor context computation
cur_mvds = np.zeros((4, 4, 2), dtype=np.int32)
left_mvds = mb_info.get('left_mb_mvds_l0')
top_mvds = mb_info.get('top_mb_mvds_l0')
# mvd_l0 for all partitions
for part_idx in range(num_parts):
blk_x, blk_y = part_positions[part_idx]
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds, left_mvds, top_mvds)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds, left_mvds, top_mvds)
mvd_x = decode_mvd_lx(decoder, contexts, 0, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 0, 1, ctx_inc_y)
result['mvd_l0'].append((mvd_x, mvd_y))
# Fill MVD grid for this partition
if mb_type == 0: # P_16x16: all blocks
cur_mvds[:, :, 0] = mvd_x
cur_mvds[:, :, 1] = mvd_y
elif mb_type == 1: # P_16x8
cur_mvds[blk_y:blk_y + 2, :, 0] = mvd_x
cur_mvds[blk_y:blk_y + 2, :, 1] = mvd_y
elif mb_type == 2: # P_8x16
cur_mvds[:, blk_x:blk_x + 2, 0] = mvd_x
cur_mvds[:, blk_x:blk_x + 2, 1] = mvd_y
result['mvd_grid_l0'] = cur_mvds
def _decode_p_sub_mb_pred(
decoder: 'CABACDecoder',
contexts: list,
num_ref_l0: int,
result: dict,
mb_info: dict,
) -> None:
"""Decode P_8x8 sub_mb_pred (H.264 7.3.5.2)."""
# sub_mb_type[4]
sub_types = []
for _ in range(4):
sub_types.append(decode_sub_mb_type_p(decoder, contexts))
result['sub_mb_types'] = sub_types
# ref_idx_l0[4] — one per 8x8 sub-MB
cur_refs_l0 = np.zeros((4, 4), dtype=np.int8)
left_refs_l0 = mb_info.get('left_mb_ref_l0')
top_refs_l0 = mb_info.get('top_mb_ref_l0')
for i in range(4):
base_x, base_y = _SUB_MB_BASE[i]
ctx_inc = _compute_ref_idx_ctx_inc(base_x, base_y, cur_refs_l0,
left_refs_l0, top_refs_l0)
ref = decode_ref_idx(decoder, contexts, 0, num_ref_l0, ctx_inc)
result['ref_idx_l0'].append(ref)
cur_refs_l0[base_y:base_y + 2, base_x:base_x + 2] = ref
result['ref_idx_grid_l0'] = cur_refs_l0
# MVD grid for neighbor context computation
cur_mvds = np.zeros((4, 4, 2), dtype=np.int32)
left_mvds = mb_info.get('left_mb_mvds_l0')
top_mvds = mb_info.get('top_mb_mvds_l0')
# mvd_l0 for each sub-partition
for sub_idx in range(4):
base_x, base_y = _SUB_MB_BASE[sub_idx]
sub_type = sub_types[sub_idx]
offsets = _P_SUB_PART_OFFSETS.get(sub_type, [(0, 0)])
coverage = _P_SUB_PART_COVERAGE.get(sub_type, [(2, 2)])
for part_i, (dx, dy) in enumerate(offsets):
blk_x = base_x + dx
blk_y = base_y + dy
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds, left_mvds, top_mvds)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds, left_mvds, top_mvds)
mvd_x = decode_mvd_lx(decoder, contexts, 0, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 0, 1, ctx_inc_y)
result['mvd_l0'].append((mvd_x, mvd_y))
# Fill MVD grid for this sub-partition
rows, cols = coverage[part_i]
cur_mvds[blk_y:blk_y + rows, blk_x:blk_x + cols, 0] = mvd_x
cur_mvds[blk_y:blk_y + rows, blk_x:blk_x + cols, 1] = mvd_y
result['mvd_grid_l0'] = cur_mvds
def _decode_b_mb_pred(
decoder: 'CABACDecoder',
contexts: list,
mb_type: int,
num_ref_l0: int,
num_ref_l1: int,
result: dict,
mb_info: dict,
) -> None:
"""Decode B-slice mb_pred or sub_mb_pred."""
if mb_type == 0: # B_Direct_16x16 — no ref_idx or MVD in bitstream
return
if mb_type == 22: # B_8x8
_decode_b_sub_mb_pred(decoder, contexts, num_ref_l0, num_ref_l1, result, mb_info)
return
# Regular B partitions (types 1-21)
num_parts = _get_num_partitions(mb_type, 1)
pred_flags = _get_b_pred_flags(mb_type)
# Partition positions and coverage in 4x4 block units
if mb_type <= 3: # 16x16
part_positions = [(0, 0)]
part_rows, part_cols = 4, 4
elif mb_type % 2 == 0: # 16x8 (even types 4,6,...,20)
part_positions = [(0, 0), (0, 2)]
part_rows, part_cols = 2, 4
else: # 8x16 (odd types 5,7,...,21)
part_positions = [(0, 0), (2, 0)]
part_rows, part_cols = 4, 2
# ref_idx grids for context derivation (H.264 9.3.3.1.1.3)
cur_refs_l0 = np.zeros((4, 4), dtype=np.int8)
cur_refs_l1 = np.zeros((4, 4), dtype=np.int8)
left_refs_l0 = mb_info.get('left_mb_ref_l0')
top_refs_l0 = mb_info.get('top_mb_ref_l0')
left_refs_l1 = mb_info.get('left_mb_ref_l1')
top_refs_l1 = mb_info.get('top_mb_ref_l1')
# ref_idx_l0 for all partitions (H.264 7.3.5.1 order)
for i in range(num_parts):
if pred_flags[i][0]: # predFlagL0
blk_x, blk_y = part_positions[i]
ctx_inc = _compute_ref_idx_ctx_inc(blk_x, blk_y, cur_refs_l0,
left_refs_l0, top_refs_l0)
ref = decode_ref_idx(decoder, contexts, 0, num_ref_l0, ctx_inc)
result['ref_idx_l0'].append(ref)
cur_refs_l0[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols] = ref
# ref_idx_l1 for all partitions
for i in range(num_parts):
if pred_flags[i][1]: # predFlagL1
blk_x, blk_y = part_positions[i]
ctx_inc = _compute_ref_idx_ctx_inc(blk_x, blk_y, cur_refs_l1,
left_refs_l1, top_refs_l1)
ref = decode_ref_idx(decoder, contexts, 1, num_ref_l1, ctx_inc)
result['ref_idx_l1'].append(ref)
cur_refs_l1[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols] = ref
result['ref_idx_grid_l0'] = cur_refs_l0
result['ref_idx_grid_l1'] = cur_refs_l1
# MVD grids for neighbor context computation (H.264 9.3.3.1.1.7)
cur_mvds_l0 = np.zeros((4, 4, 2), dtype=np.int32)
cur_mvds_l1 = np.zeros((4, 4, 2), dtype=np.int32)
left_mvds_l0 = mb_info.get('left_mb_mvds_l0')
top_mvds_l0 = mb_info.get('top_mb_mvds_l0')
left_mvds_l1 = mb_info.get('left_mb_mvds_l1')
top_mvds_l1 = mb_info.get('top_mb_mvds_l1')
# mvd_l0 for all partitions
for i in range(num_parts):
if pred_flags[i][0]:
blk_x, blk_y = part_positions[i]
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds_l0, left_mvds_l0, top_mvds_l0)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds_l0, left_mvds_l0, top_mvds_l0)
mvd_x = decode_mvd_lx(decoder, contexts, 0, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 0, 1, ctx_inc_y)
result['mvd_l0'].append((mvd_x, mvd_y))
cur_mvds_l0[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols, 0] = mvd_x
cur_mvds_l0[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols, 1] = mvd_y
# mvd_l1 for all partitions
for i in range(num_parts):
if pred_flags[i][1]:
blk_x, blk_y = part_positions[i]
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds_l1, left_mvds_l1, top_mvds_l1)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds_l1, left_mvds_l1, top_mvds_l1)
mvd_x = decode_mvd_lx(decoder, contexts, 1, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 1, 1, ctx_inc_y)
result['mvd_l1'].append((mvd_x, mvd_y))
cur_mvds_l1[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols, 0] = mvd_x
cur_mvds_l1[blk_y:blk_y + part_rows, blk_x:blk_x + part_cols, 1] = mvd_y
result['mvd_grid_l0'] = cur_mvds_l0
result['mvd_grid_l1'] = cur_mvds_l1
def _decode_b_sub_mb_pred(
decoder: 'CABACDecoder',
contexts: list,
num_ref_l0: int,
num_ref_l1: int,
result: dict,
mb_info: dict,
) -> None:
"""Decode B_8x8 sub_mb_pred (H.264 7.3.5.2)."""
# sub_mb_type[4]
sub_types = []
for _ in range(4):
sub_types.append(decode_sub_mb_type_b(decoder, contexts))
result['sub_mb_types'] = sub_types
# ref_idx grids for context derivation (H.264 9.3.3.1.1.3)
cur_refs_l0 = np.zeros((4, 4), dtype=np.int8)
cur_refs_l1 = np.zeros((4, 4), dtype=np.int8)
left_refs_l0 = mb_info.get('left_mb_ref_l0')
top_refs_l0 = mb_info.get('top_mb_ref_l0')
left_refs_l1 = mb_info.get('left_mb_ref_l1')
top_refs_l1 = mb_info.get('top_mb_ref_l1')
# ref_idx_l0[4] — one per sub-MB, only if sub-partition uses L0
# B_Direct_8x8 (sub_type=0) derives ref_idx, does not read from bitstream
for i in range(4):
base_x, base_y = _SUB_MB_BASE[i]
if sub_types[i] != 0 and _b_sub_uses_l0(sub_types[i]):
ctx_inc = _compute_ref_idx_ctx_inc(base_x, base_y, cur_refs_l0,
left_refs_l0, top_refs_l0)
ref = decode_ref_idx(decoder, contexts, 0, num_ref_l0, ctx_inc)
result['ref_idx_l0'].append(ref)
cur_refs_l0[base_y:base_y + 2, base_x:base_x + 2] = ref
else:
result['ref_idx_l0'].append(0) # placeholder or derived
# ref_idx_l1[4]
for i in range(4):
base_x, base_y = _SUB_MB_BASE[i]
if sub_types[i] != 0 and _b_sub_uses_l1(sub_types[i]):
ctx_inc = _compute_ref_idx_ctx_inc(base_x, base_y, cur_refs_l1,
left_refs_l1, top_refs_l1)
ref = decode_ref_idx(decoder, contexts, 1, num_ref_l1, ctx_inc)
result['ref_idx_l1'].append(ref)
cur_refs_l1[base_y:base_y + 2, base_x:base_x + 2] = ref
else:
result['ref_idx_l1'].append(0) # placeholder or derived
result['ref_idx_grid_l0'] = cur_refs_l0
result['ref_idx_grid_l1'] = cur_refs_l1
# MVD grids for neighbor context computation
cur_mvds_l0 = np.zeros((4, 4, 2), dtype=np.int32)
cur_mvds_l1 = np.zeros((4, 4, 2), dtype=np.int32)
left_mvds_l0 = mb_info.get('left_mb_mvds_l0')
top_mvds_l0 = mb_info.get('top_mb_mvds_l0')
left_mvds_l1 = mb_info.get('left_mb_mvds_l1')
top_mvds_l1 = mb_info.get('top_mb_mvds_l1')
# mvd_l0 per sub-partition
for sub_idx in range(4):
if _b_sub_uses_l0(sub_types[sub_idx]) and sub_types[sub_idx] != 0:
base_x, base_y = _SUB_MB_BASE[sub_idx]
sub_type = sub_types[sub_idx]
offsets = _B_SUB_PART_OFFSETS.get(sub_type, [(0, 0)])
coverage = _B_SUB_PART_COVERAGE.get(sub_type, [(2, 2)])
for part_i, (dx, dy) in enumerate(offsets):
blk_x = base_x + dx
blk_y = base_y + dy
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds_l0, left_mvds_l0, top_mvds_l0)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds_l0, left_mvds_l0, top_mvds_l0)
mvd_x = decode_mvd_lx(decoder, contexts, 0, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 0, 1, ctx_inc_y)
result['mvd_l0'].append((mvd_x, mvd_y))
rows, cols = coverage[part_i]
cur_mvds_l0[blk_y:blk_y + rows, blk_x:blk_x + cols, 0] = mvd_x
cur_mvds_l0[blk_y:blk_y + rows, blk_x:blk_x + cols, 1] = mvd_y
# mvd_l1 per sub-partition
for sub_idx in range(4):
if _b_sub_uses_l1(sub_types[sub_idx]) and sub_types[sub_idx] != 0:
base_x, base_y = _SUB_MB_BASE[sub_idx]
sub_type = sub_types[sub_idx]
offsets = _B_SUB_PART_OFFSETS.get(sub_type, [(0, 0)])
coverage = _B_SUB_PART_COVERAGE.get(sub_type, [(2, 2)])
for part_i, (dx, dy) in enumerate(offsets):
blk_x = base_x + dx
blk_y = base_y + dy
ctx_inc_x = _compute_mvd_ctx_inc(0, blk_x, blk_y, cur_mvds_l1, left_mvds_l1, top_mvds_l1)
ctx_inc_y = _compute_mvd_ctx_inc(1, blk_x, blk_y, cur_mvds_l1, left_mvds_l1, top_mvds_l1)
mvd_x = decode_mvd_lx(decoder, contexts, 1, 0, ctx_inc_x)
mvd_y = decode_mvd_lx(decoder, contexts, 1, 1, ctx_inc_y)
result['mvd_l1'].append((mvd_x, mvd_y))
rows, cols = coverage[part_i]
cur_mvds_l1[blk_y:blk_y + rows, blk_x:blk_x + cols, 0] = mvd_x
cur_mvds_l1[blk_y:blk_y + rows, blk_x:blk_x + cols, 1] = mvd_y
result['mvd_grid_l0'] = cur_mvds_l0
result['mvd_grid_l1'] = cur_mvds_l1
def _p_sub_num_parts(sub_type: int) -> int:
"""Number of sub-partitions for P sub_mb_type."""
# 0=8x8(1), 1=8x4(2), 2=4x8(2), 3=4x4(4)
return [1, 2, 2, 4][min(sub_type, 3)]
def _b_sub_num_parts(sub_type: int) -> int:
"""Number of sub-partitions for B sub_mb_type."""
# H.264 Table 7-18
# 0=Direct(4), 1=L0_8x8(1), 2=L1_8x8(1), 3=Bi_8x8(1),
# 4=L0_8x4(2), 5=L0_4x8(2), 6=L1_8x4(2), 7=L1_4x8(2),
# 8=Bi_8x4(2), 9=Bi_4x8(2), 10=L0_4x4(4), 11=L1_4x4(4), 12=Bi_4x4(4)
return [4, 1, 1, 1, 2, 2, 2, 2, 2, 2, 4, 4, 4][min(sub_type, 12)]
def _b_sub_uses_l0(sub_type: int) -> bool:
"""Whether B sub_mb_type uses L0 prediction."""
# Direct(0), L0(1,4,5,10), Bi(3,8,9,12)
return sub_type in (0, 1, 3, 4, 5, 8, 9, 10, 12)
def _b_sub_uses_l1(sub_type: int) -> bool:
"""Whether B sub_mb_type uses L1 prediction."""
# Direct(0), L1(2,6,7,11), Bi(3,8,9,12)
return sub_type in (0, 2, 3, 6, 7, 8, 9, 11, 12)
# B-MB type prediction flags: per partition (predFlagL0, predFlagL1)
# H.264 Table 7-14
_B_PRED_FLAGS = {
1: [(True, False)], # B_L0_16x16
2: [(False, True)], # B_L1_16x16
3: [(True, True)], # B_Bi_16x16
4: [(True, False), (True, False)], # B_L0_L0_16x8
5: [(True, False), (True, False)], # B_L0_L0_8x16
6: [(False, True), (False, True)], # B_L1_L1_16x8
7: [(False, True), (False, True)], # B_L1_L1_8x16
8: [(True, False), (False, True)], # B_L0_L1_16x8
9: [(True, False), (False, True)], # B_L0_L1_8x16
10: [(False, True), (True, False)], # B_L1_L0_16x8
11: [(False, True), (True, False)], # B_L1_L0_8x16
12: [(True, False), (True, True)], # B_L0_Bi_16x8
13: [(True, False), (True, True)], # B_L0_Bi_8x16
14: [(False, True), (True, True)], # B_L1_Bi_16x8
15: [(False, True), (True, True)], # B_L1_Bi_8x16
16: [(True, True), (True, False)], # B_Bi_L0_16x8
17: [(True, True), (True, False)], # B_Bi_L0_8x16
18: [(True, True), (False, True)], # B_Bi_L1_16x8
19: [(True, True), (False, True)], # B_Bi_L1_8x16
20: [(True, True), (True, True)], # B_Bi_Bi_16x8
21: [(True, True), (True, True)], # B_Bi_Bi_8x16
}
def _get_b_pred_flags(mb_type: int) -> list:
"""Get per-partition prediction flags for B mb_type."""
return _B_PRED_FLAGS.get(mb_type, [])
def decode_macroblock_layer_cabac(
decoder: 'CABACDecoder',
contexts: List['CABACContext'],
slice_type: int,
mb_info: Dict[str, Any],
) -> Dict[str, Any]:
"""Decode complete macroblock layer.
Args:
decoder: CABAC decoder
contexts: Context models
slice_type: Slice type
mb_info: Neighbor information
Returns:
Dict with mb_type, cbp, qp_delta, prediction info, coefficients
"""
result = {
'mb_skip_flag': 0,
'mb_type': 0,
'cbp': 0,
'mb_qp_delta': 0,
'transform_size_8x8_flag': 0,
}
# Check for skip (P/B slices only)
if slice_type in (0, 1): # P or B
result['mb_skip_flag'] = decode_mb_skip_flag_cabac(
decoder, contexts, slice_type, mb_info
)
if result['mb_skip_flag'] == 1:
return result
# Decode mb_type
result['mb_type'] = decode_mb_type_cabac(
decoder, contexts, slice_type, mb_info
)
# Check for I_PCM
if _is_i_pcm(result['mb_type'], slice_type):
result['i_pcm'] = decode_i_pcm_cabac(decoder, mb_info)
return result
# H.264 7.3.5: transform_size_8x8_flag position depends on MB type
is_intra_nxn = _is_intra_mb_type(result['mb_type'], slice_type) and \
not _is_i_16x16(result['mb_type'], slice_type) and \
not _is_i_pcm(result['mb_type'], slice_type)
# For I_NxN: parse transform_size_8x8_flag BEFORE mb_pred
if is_intra_nxn and mb_info.get('transform_8x8_mode_flag', False):
result['transform_size_8x8_flag'] = decode_transform_size_8x8_flag_cabac(
decoder, contexts, mb_info
)
# mb_pred needs this to decide 4 vs 16 intra modes
mb_info['transform_size_8x8_flag'] = result['transform_size_8x8_flag']
# Decode mb_pred
result['mb_pred'] = decode_mb_pred_cabac(
decoder, contexts, result['mb_type'], slice_type, mb_info
)
# Decode CBP (if not I_16x16)
if not _is_i_16x16(result['mb_type'], slice_type):
result['cbp'] = decode_cbp_cabac(
decoder, contexts, mb_info,
is_inter=not _is_intra_mb_type(result['mb_type'], slice_type)
)
else:
# For I_16x16, CBP is embedded in mb_type
cbp_luma, cbp_chroma = _extract_i16x16_cbp(result['mb_type'], slice_type)
result['cbp_luma'] = cbp_luma
result['cbp_chroma'] = cbp_chroma
result['cbp'] = cbp_luma | (cbp_chroma << 4)
# For inter MBs: parse transform_size_8x8_flag AFTER CBP (H.264 7.3.5)
# Only when noSubMbPartSizeLessThan8x8Flag == 1 (all sub-partitions >= 8x8)
if not is_intra_nxn and not _is_i_16x16(result['mb_type'], slice_type) and \
not _is_intra_mb_type(result['mb_type'], slice_type) and \
mb_info.get('transform_8x8_mode_flag', False):
cbp_luma = result['cbp'] & 0x0F
if cbp_luma > 0:
# H.264 7.4.5: noSubMbPartSizeLessThan8x8Flag
# Note: B_Direct_8x8 (sub_mb_type=0) counts as 8x8 when
# direct_8x8_inference_flag=1, which is mandatory for High
# Profile (the only profile where transform_8x8_mode_flag=1).
no_sub_lt_8x8 = True
mb_pred = result.get('mb_pred', {})
sub_types = mb_pred.get('sub_mb_types', None) if isinstance(mb_pred, dict) else getattr(mb_pred, 'sub_mb_types', None)
if sub_types is not None:
# P_8x8: sub_mb_type must be 0 (P_L0_8x8)
# B_8x8: sub_mb_type must be <= 3 (B_*_8x8)
is_b = (slice_type == 1)
for st in sub_types:
if is_b and st > 3:
no_sub_lt_8x8 = False
break
elif not is_b and st > 0:
no_sub_lt_8x8 = False
break
if no_sub_lt_8x8:
result['transform_size_8x8_flag'] = decode_transform_size_8x8_flag_cabac(
decoder, contexts, mb_info
)
# Decode mb_qp_delta: H.264 Section 7.3.5.1
# Condition: CBP_luma > 0 OR CBP_chroma > 0 OR MbPartPredMode == Intra_16x16
is_16x16 = _is_i_16x16(result['mb_type'], slice_type)
has_coded_blocks = False
if is_16x16:
# I_16x16 always decodes mb_qp_delta (spec: MbPartPredMode == Intra_16x16)
has_coded_blocks = True
else:
has_coded_blocks = result['cbp'] != 0
if has_coded_blocks:
# Context for first bin depends on whether prev MB had nonzero qp_delta
prev_qp_delta = mb_info.get('prev_mb_qp_delta', 0)
ctx_inc_first = 1 if prev_qp_delta != 0 else 0
result['mb_qp_delta'] = decode_mb_qp_delta(
decoder, contexts, ctx_inc_first=ctx_inc_first
)
# Decode residual blocks
if has_coded_blocks:
result['residual'] = _decode_residual_cabac(
decoder, contexts, result['mb_type'], slice_type, result['cbp'],
result.get('transform_size_8x8_flag', 0),
mb_info=mb_info,
)
else:
result['residual'] = _empty_residual()
return result