summaryrefslogtreecommitdiffstats
path: root/k9vamps/k9requant.cpp
blob: 009f76cb3f2d8fa1d89b5dbbd836f0f6a517e2ea (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
//
// C++ Implementation: k9requant
//
// Description:
//
//
// Author: Jean-Michel PETIT <k9copy@free.fr>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "k9requant.h"
#include "getvlc.h"
#include "putvlc.h"
#include "ac.h"
// Code from libmpeg2 and mpeg2enc copyright by their respective owners
// New code and modifications copyright Antoine Missout
// Thanks to Sven Goethel for error resilience patches
// Released under GPL license, see gnu.org

// toggles:

#define THREAD
// #define LOG_RATE_CONTROL // some stats
// #define DEMO // demo mode
// #define STAT // print stats on exit
// #define USE_FD // use 2 lasts args for input/output paths

#define NDEBUG // turns off asserts
#define REMOVE_BYTE_STUFFING	// removes series of 0x00
// #define USE_GLOBAL_REGISTER // assign registers to bit buffers
#define MAX_ERRORS 0 // if above copy slice

//#define CHANGE_BRIGHTNESS //add a param to command line, changing brightness: _will_not_recompress_, disables max_errors
//#define WIN // for windows fixes, use with USE_FD

// params:

// if not defined, non intra block in p frames are requantised
// if defined and >= 0, we keep coeff. in pos 0..n-1 in scan order
// and coeff which would have been non-null if requantised
// if defined and < 0 we drop max 1/x coeffs.
// experimental, looks better when undefined
// #define P_FRAME_NON_INTRA_DROP 8

// params for fact = 1.0, fact = 3.0 and fact = 10.0
// we'll make a linear interpolation between
static const int i_factors[3] = {  5, 15,  65 };
static const int p_factors[3] = {  5, 25,  85 };
static const int b_factors[3] = { 25, 45, 105 };


static const double i_min_stresses[3] = { 0.70, 0.40, 0.00 };
static const double p_min_stresses[3] = { 0.60, 0.35, 0.00 };
static const double b_min_stresses[3] = { 0.00, 0.00, 0.00 };


// factor up to which alt table will be used
// (though alt_table gives better psnr up to factor around ~2.5
// the result is less pleasing to watch than normal table
// so this is disabled)
static const double max_alt_table = 0.0;

// includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>

#ifndef USE_FD
#include <unistd.h>
#include <fcntl.h>
#endif

// quant table
#include "qTable.h"

// useful constants
#define I_TYPE 1
#define P_TYPE 2
#define B_TYPE 3

// gcc
#ifdef HAVE_BUILTIN_EXPECT
	#define likely(x) __builtin_expect ((x) != 0, 1)
	#define unlikely(x) __builtin_expect ((x) != 0, 0)
#else
	#define likely(x) (x)
	#define unlikely(x) (x)
#endif

#ifndef NDEBUG
	#define DEB(msg) fprintf (stderr, "%s:%d " msg, __FILE__, __LINE__)
	#define DEBF(format, args...) fprintf (stderr, "%s:%d " format, __FILE__, __LINE__, args)
#else
	#define DEB(msg)
	#ifdef WIN
		#define DEBF(format, args)
	#else
		#define DEBF(format, args...)
	#endif
#endif

#ifndef THREAD
#define LOG(msg) fprintf (stderr, msg)
#ifdef WIN
	#define LOGF(format, arg1) fprintf (stderr, format, arg1)
#else
	#define LOGF(format, args...) fprintf (stderr, format, args)
#endif
#endif



/*#define MOV_READ \
	mloka1 = rbuf - cbuf; if (mloka1) memmove(orbuf, cbuf, mloka1);\
	cbuf = rbuf = orbuf; rbuf += mloka1;
*/

#ifdef STAT

#define RETURN \
		assert(rbuf >= cbuf);\
		mloka1 = rbuf - cbuf;\
		if (mloka1) { COPY(mloka1); }\
		WRITE \
		free(orbuf); \
		free(owbuf); \
		\
		LOG("Stats:\n");\
		\
		LOGF("Wanted fact_x: %.1f\n", fact_x);\
		\
		LOGF("cnt_i: %.0f ", (float)cnt_i); \
		if (cnt_i) LOGF("ori_i: %.0f new_i: %.0f fact_i: %.1f\n", (float)ori_i, (float)new_i, (float)ori_i/(float)new_i); \
		else LOG("\n");\
		\
		LOGF("cnt_p: %.0f ", (float)cnt_p); \
		if (cnt_p) LOGF("ori_p: %.0f new_p: %.0f fact_p: %.1f cnt_p_i: %.0f cnt_p_ni: %.0f propor: %.1f i\n", \
			(float)ori_p, (float)new_p, (float)ori_p/(float)new_p, (float)cnt_p_i, (float)cnt_p_ni, (float)cnt_p_i/((float)cnt_p_i+(float)cnt_p_ni)); \
		else LOG("\n");\
		\
		LOGF("cnt_b: %.0f ", (float)cnt_b); \
		if (cnt_b) LOGF("ori_b: %.0f new_b: %.0f fact_b: %.1f cnt_b_i: %.0f cnt_b_ni: %.0f propor: %.1f i\n", \
			(float)ori_b, (float)new_b, (float)ori_b/(float)new_b, (float)cnt_b_i, (float)cnt_b_ni, (float)cnt_b_i/((float)cnt_b_i+(float)cnt_b_ni)); \
		else LOG("\n");\
		\
		LOGF("Final fact_x: %.1f\n", (float)inbytecnt/(float)outbytecnt);\
		exit(0);

#else

#define RETURN \
		assert(rbuf >= cbuf);\
		mloka1 = rbuf - cbuf;\
		if (mloka1) { COPY(mloka1); }\
		WRITE \
		free(orbuf); \
		free(owbuf); \
		exit(0);

#endif
	#define MOTION_CALL(routine,direction) 						\
do {														\
    if ((direction) & MACROBLOCK_MOTION_FORWARD)			\
		routine (f_code[0]);								\
    if ((direction) & MACROBLOCK_MOTION_BACKWARD)			\
		routine (f_code[1]);								\
} while (0)

#define NEXT_MACROBLOCK											\
do {															\
    h_offset += 16;												\
    if (h_offset == horizontal_size_value) 						\
	{															\
		v_offset += 16;											\
		if (v_offset > (vertical_size_value - 16)) return;		\
		h_offset = 0;											\
    }															\
} while (0)

#ifdef P_FRAME_NON_INTRA_DROP
	#if (P_FRAME_NON_INTRA_DROP < 0)
		#undef UPDATE_VAL
		#define UPDATE_VAL
		#define SAVE_VAL
		#define WRITE_VAL \
			blk->level = val; \
			blk->run = i - li - 1; \
			li = i; \
			blk++;
	#else
		#define SAVE_VAL oval = val;
		#define WRITE_VAL \
			if ((val) || (i < P_FRAME_NON_INTRA_DROP)) \
			{ \
				blk->level = oval; \
				blk->run = i - li - 1; \
				li = i; \
				blk++; \
			}
	#endif
#else
	#define SAVE_VAL
	#define WRITE_VAL \
		if (val) \
		{ \
			blk->level = val; \
			blk->run = i - li - 1; \
			li = i; \
			blk++; \
		}
#endif

#define UPDATE_VAL \
	val = curTable[val];

int quantisers[42] =
  {
    1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32,
    34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 72, 80,
    88, 96, 104, 112
  };

int non_linear_quantizer_scale [] =
  {
    0,  1,  2,  3,  4,  5,   6,   7,
    8, 10, 12, 14, 16, 18,  20,  22,
    24, 28, 32, 36, 40, 44,  48,  52,
    56, 64, 72, 80, 88, 96, 104, 112
  };


const uint8 non_linear_mquant_table[32] =
  {
    0, 1, 2, 3, 4, 5, 6, 7,
    8,10,12,14,16,18,20,22,
    24,28,32,36,40,44,48,52,
    56,64,72,80,88,96,104,112
  };
const uint8 map_non_linear_mquant[113] =
  {
    0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
    16,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,
    22,22,23,23,23,23,24,24,24,24,24,24,24,25,25,25,25,25,25,25,26,26,
    26,26,26,26,26,26,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,29,
    29,29,29,29,29,29,29,29,29,30,30,30,30,30,30,30,31,31,31,31,31
  };


k9requant::k9requant()
{

  cbuf=rbuf=orbuf=wbuf=NULL;
  quant_table_id = &quant_table_id_data[2048];
  rqt_run=false;
  initvar();
}
void k9requant::putbits(uint val, int n)
{
  assert(n < 32);
  assert(!(val & (0xffffffffU << n)));

  while (unlikely(n >= outbitcnt))
  {
    wbuf[0] = (outbitbuf << outbitcnt ) | (val >> (n - outbitcnt));
    SEEKW(1);
    n -= outbitcnt;
    outbitbuf = 0;
    val &= ~(0xffffffffU << n);
    outbitcnt = BITS_IN_BUF;
  }

  if (likely(n))
  {
    outbitbuf = (outbitbuf << n) | val;
    outbitcnt -= n;
  }

  assert(outbitcnt > 0);
  assert(outbitcnt <= BITS_IN_BUF);
}

void k9requant::Refill_bits(void)
{
  assert((rbuf - cbuf) >= 1);
  inbitbuf |= cbuf[0] << (24 - inbitcnt);
  inbitcnt += 8;
  SEEKR(1)
}

void k9requant::Flush_Bits(uint n)
{
  assert(inbitcnt >= n);

  inbitbuf <<= n;
  inbitcnt -= n;

  assert( (!n) || ((n>0) && !(inbitbuf & 0x1)) );

  while (unlikely(inbitcnt < 24)) Refill_bits();
}

uint k9requant::Show_Bits(uint n)
{
  return ((unsigned int)inbitbuf) >> (32 - n);
}

uint k9requant::Get_Bits(uint n)
{
  uint Val = Show_Bits(n);
  Flush_Bits(n);
  return Val;
}

uint k9requant::Copy_Bits(uint n)
{
  uint Val = Get_Bits(n);
  putbits(Val, n);
  return Val;
}

void k9requant::flush_read_buffer()
{
  int i = inbitcnt & 0x7;
  if (i)
  {
    if (inbitbuf >> (32 - i))
    {
      DEBF("illegal inbitbuf: 0x%08X, %i, 0x%02X, %i\n", inbitbuf, inbitcnt, (inbitbuf >> (32 - i)), i);
      sliceError++;
    }

    inbitbuf <<= i;
    inbitcnt -= i;
  }
  SEEKR(-1 * (inbitcnt >> 3));
  inbitcnt = 0;
}

void k9requant::flush_write_buffer()
{
  if (outbitcnt != 8) putbits(0, outbitcnt);
}

/////---- begin ext mpeg code
int k9requant::scale_quant(double quant )
{
  int iquant;
#ifdef DEMO
  if ((gopCount & 0x7F) < 10) // gop is ~ 0.5 sec, so 5 sec every ~minute (127 * 0.5 = 63.5 sec)
  {
    if (q_scale_type) return 112;
    else return 62;
  }
#endif
  if (q_scale_type)
  {
    iquant = (int) floor(quant+0.5);
    /* clip mquant to legal (linear) range */
    if (iquant<1) iquant = 1;
    if (iquant>112) iquant = 112;
    iquant = non_linear_mquant_table[map_non_linear_mquant[iquant]];
  }
  else
  {
    /* clip mquant to legal (linear) range */
    iquant = (int)floor(quant+0.5);
    if (iquant<2) iquant = 2;
    if (iquant>62) iquant = 62;
    iquant = (iquant/2)*2; // Must be *even*
  }
  return iquant;
}

int k9requant::increment_quant(int quant)
{
#ifdef DEMO
  if ((gopCount & 0x7F) < 10)
  {
    if (q_scale_type) return 112;
    else return 62;
  }
#endif
  if (q_scale_type)
  {
    if (quant < 1 || quant > 112)
    {
      DEBF("illegal quant: %d\n", quant);
      if (quant > 112) quant = 112;
      else if (quant < 1) quant = 1;
      DEBF("illegal quant changed to : %d\n", quant);
      sliceError++;
    }
    quant = map_non_linear_mquant[quant] + 1;
    if (quant > 31) quant = 31;
    quant = non_linear_mquant_table[quant];
  }
  else
  {
    if ((quant & 1) || (quant < 2) || (quant > 62))
    {
      DEBF("illegal quant: %d\n", quant);
      if (quant & 1) quant--;
      if (quant > 62) quant = 62;
      else if (quant < 2) quant = 2;
      DEBF("illegal quant changed to : %d\n", quant);
      sliceError++;
    }
    quant += 2;
    if (quant > 62) quant = 62;
  }
  return quant;
}

int k9requant::intmax( register int x, register int y )
{ return x < y ? y : x; }

int k9requant::intmin( register int x, register int y )
{ return x < y ? x : y; }


int k9requant::getNewQuant(int curQuant, int intra)
{
#ifdef CHANGE_BRIGHTNESS
  return curQuant;
#else
  int mquant = 0;
  double cStress;

  switch (picture_coding_type)
  {
  case I_TYPE:
    cStress = (stress_factor - i_min_stress) / (1.0 - i_min_stress);
    mquant = intmax(scale_quant(curQuant + i_factor*cStress), increment_quant(curQuant));
    break;

  case P_TYPE:
    cStress = (stress_factor - p_min_stress) / (1.0 - p_min_stress);
    if (intra) // since it might be used as a ref, treat it as an I frame block
      mquant = intmax(scale_quant(curQuant + i_factor*cStress), increment_quant(curQuant));
    else
      mquant = intmax(scale_quant(curQuant + p_factor*cStress), increment_quant(curQuant));
    break;

  case B_TYPE:
    cStress = (stress_factor - b_min_stress) / (1.0 - b_min_stress);
    mquant = intmax(scale_quant(curQuant + b_factor*cStress), increment_quant(curQuant));
    break;

  default:
    assert(0);
    break;
  }

  assert(mquant >= curQuant);

  return mquant;
#endif
}

int k9requant::isNotEmpty(RunLevel *blk)
{
  return (blk->level);
}


// return != 0 if error
int k9requant::putAC(int run, int signed_level, int vlcformat)
{
  int level, len;
  const VLCtable *ptab = NULL;

  level = (signed_level<0) ? -signed_level : signed_level; /* abs(signed_level) */

  // assert(!(run<0 || run>63 || level==0 || level>2047));
  if(run<0 || run>63)
  {
    DEBF("illegal run: %d\n", run);
    sliceError++;
    return 1;
  }
  if(level==0 || level>2047)
  {
    DEBF("illegal level: %d\n", level);
    sliceError++;
    return 1;
  }

  len = 0;

  if (run<2 && level<41)
  {
    if (vlcformat)  ptab = &dct_code_tab1a[run][level-1];
    else ptab = &dct_code_tab1[run][level-1];
    len = ptab->len;
  }
  else if (run<32 && level<6)
  {
    if (vlcformat) ptab = &dct_code_tab2a[run-2][level-1];
    else ptab = &dct_code_tab2[run-2][level-1];
    len = ptab->len;
  }

  if (len) /* a VLC code exists */
  {
    putbits(ptab->code, len);
    putbits(signed_level<0, 1); /* sign */
  }
  else
  {
    putbits(1l, 6); /* Escape */
    putbits(run, 6); /* 6 bit code for run */
    putbits(((uint)signed_level) & 0xFFF, 12);
  }

  return 0;
}

// return != 0 if error
int k9requant::putACfirst(int run, int val)
{
  if (run==0 && (val==1 || val==-1))
  {
    putbits(2|((val<0) ? 1 : 0), 2);
    return 0;
  }
  else return putAC(run,val,0);
}

void k9requant::putnonintrablk(RunLevel *blk)
{
  assert(blk->level);

  if (putACfirst(blk->run, blk->level)) return;
  blk++;

  while(blk->level)
  {
    if (putAC(blk->run, blk->level, 0)) return;
    blk++;
  }

  putbits(2,2);
}

void k9requant::putcbp(int cbp)
{
  assert(cbp > 0 && cbp < 64);
  putbits(cbptable[cbp].code,cbptable[cbp].len);
}

void k9requant::putmbtype(int mb_type)
{
  putbits(mbtypetab[picture_coding_type-1][mb_type].code,
          mbtypetab[picture_coding_type-1][mb_type].len);
}

int k9requant::get_macroblock_modes ()
{
  int macroblock_modes;
  const MBtab * tab;

  switch (picture_coding_type)
  {
  case I_TYPE:

    tab = MB_I + UBITS (bit_buf, 1);
    DUMPBITS (bit_buf, bits, tab->len);
    macroblock_modes = tab->modes;

    if ((! (frame_pred_frame_dct)) && (picture_structure == FRAME_PICTURE))
    {
      macroblock_modes |= UBITS (bit_buf, 1) * DCT_TYPE_INTERLACED;
      DUMPBITS (bit_buf, bits, 1);
    }

    return macroblock_modes;

  case P_TYPE:

    tab = MB_P + UBITS (bit_buf, 5);
    DUMPBITS (bit_buf, bits, tab->len);
    macroblock_modes = tab->modes;

    if (picture_structure != FRAME_PICTURE)
    {
      if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
      {
        macroblock_modes |= UBITS (bit_buf, 2) * MOTION_TYPE_BASE;
        DUMPBITS (bit_buf, bits, 2);
      }
      return macroblock_modes;
    }
    else if (frame_pred_frame_dct)
    {
      if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
        macroblock_modes |= MC_FRAME;
      return macroblock_modes;
    }
    else
    {
      if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
      {
        macroblock_modes |= UBITS (bit_buf, 2) * MOTION_TYPE_BASE;
        DUMPBITS (bit_buf, bits, 2);
      }
      if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
      {
        macroblock_modes |= UBITS (bit_buf, 1) * DCT_TYPE_INTERLACED;
        DUMPBITS (bit_buf, bits, 1);
      }
      return macroblock_modes;
    }

  case B_TYPE:

    tab = MB_B + UBITS (bit_buf, 6);
    DUMPBITS (bit_buf, bits, tab->len);
    macroblock_modes = tab->modes;

    if (picture_structure != FRAME_PICTURE)
    {
      if (! (macroblock_modes & MACROBLOCK_INTRA))
      {
        macroblock_modes |= UBITS (bit_buf, 2) * MOTION_TYPE_BASE;
        DUMPBITS (bit_buf, bits, 2);
      }
      return macroblock_modes;
    }
    else if (frame_pred_frame_dct)
    {
      /* if (! (macroblock_modes & MACROBLOCK_INTRA)) */
      macroblock_modes |= MC_FRAME;
      return macroblock_modes;
    }
    else
    {
      if (macroblock_modes & MACROBLOCK_INTRA) goto intra;
      macroblock_modes |= UBITS (bit_buf, 2) * MOTION_TYPE_BASE;
      DUMPBITS (bit_buf, bits, 2);
      if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
      {
      intra:
        macroblock_modes |= UBITS (bit_buf, 1) * DCT_TYPE_INTERLACED;
        DUMPBITS (bit_buf, bits, 1);
      }
      return macroblock_modes;
    }

  default:
    return 0;
  }

}

int k9requant::get_quantizer_scale ()
{
  int quantizer_scale_code;

  quantizer_scale_code = UBITS (bit_buf, 5);
  DUMPBITS (bit_buf, bits, 5);

  if (!quantizer_scale_code)
  {
    DEBF("illegal quant scale code: %d\n", quantizer_scale_code);
    sliceError++;
    quantizer_scale_code++;
  }

  if (q_scale_type) return non_linear_quantizer_scale[quantizer_scale_code];
  else return quantizer_scale_code << 1;
}

void k9requant::get_motion_delta (const int f_code)
{
#define bit_buf (inbitbuf)
  const MVtab * tab;

  if (bit_buf & 0x80000000)
  {
    COPYBITS (bit_buf, bits, 1);
    return;
  }
  else if (bit_buf >= 0x0c000000)
  {

    tab = MV_4 + UBITS (bit_buf, 4);
    COPYBITS (bit_buf, bits, tab->len + 1);
    if (f_code) COPYBITS (bit_buf, bits, f_code);
    return;
  }
  else
  {

    tab = MV_10 + UBITS (bit_buf, 10);
    COPYBITS (bit_buf, bits, tab->len + 1);
    if (f_code) COPYBITS (bit_buf, bits, f_code);
    return;
  }
}


void k9requant::get_dmv ()
{
  const DMVtab * tab;
  tab = DMV_2 + UBITS (bit_buf, 2);
  COPYBITS (bit_buf, bits, tab->len);
  return;
}

int k9requant::get_coded_block_pattern ()
{
#define bit_buf (inbitbuf)
  const CBPtab * tab;

  if (bit_buf >= 0x20000000)
  {
    tab = CBP_7 + (UBITS (bit_buf, 7) - 16);
    DUMPBITS (bit_buf, bits, tab->len);
    return tab->cbp;
  }
  else
  {
    tab = CBP_9 + UBITS (bit_buf, 9);
    DUMPBITS (bit_buf, bits, tab->len);
    return tab->cbp;
  }
}

int k9requant::get_luma_dc_dct_diff ()
{
#define bit_buf (inbitbuf)
#ifdef CHANGE_BRIGHTNESS
	#define DOBITS(x, y, z) DUMPBITS(x, y, z)
#else
	#define DOBITS(x, y, z) COPYBITS(x, y, z)
#endif
  const DCtab * tab;
  int size;
  int dc_diff;

  if (bit_buf < 0xf8000000)
  {
    tab = DC_lum_5 + UBITS (bit_buf, 5);
    size = tab->size;
    if (size)
    {
      DOBITS (bit_buf, bits, tab->len);
      //dc_diff = UBITS (bit_buf, size) - UBITS (SBITS (~bit_buf, 1), size);
      dc_diff = UBITS (bit_buf, size); if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
      DOBITS (bit_buf, bits, size);
      return dc_diff;
    }
    else
    {
      DOBITS (bit_buf, bits, 3);
      return 0;
    }
  }
  else
  {
    tab = DC_long + (UBITS (bit_buf, 9) - 0x1e0);
    size = tab->size;
    DOBITS (bit_buf, bits, tab->len);
    //dc_diff = UBITS (bit_buf, size) - UBITS (SBITS (~bit_buf, 1), size);
    dc_diff = UBITS (bit_buf, size); if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
    DOBITS (bit_buf, bits, size);
    return dc_diff;
  }
}

int k9requant::get_chroma_dc_dct_diff ()
{
#define bit_buf (inbitbuf)

  const DCtab * tab;
  int size;
  int dc_diff;

  if (bit_buf < 0xf8000000)
  {
    tab = DC_chrom_5 + UBITS (bit_buf, 5);
    size = tab->size;
    if (size)
    {
      COPYBITS (bit_buf, bits, tab->len);
      //dc_diff = UBITS (bit_buf, size) - UBITS (SBITS (~bit_buf, 1), size);
      dc_diff = UBITS (bit_buf, size); if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
      COPYBITS (bit_buf, bits, size);
      return dc_diff;
    }
    else
    {
      COPYBITS (bit_buf, bits, 2);
      return 0;
    }
  }
  else
  {
    tab = DC_long + (UBITS (bit_buf, 10) - 0x3e0);
    size = tab->size;
    COPYBITS (bit_buf, bits, tab->len + 1);
    //dc_diff = UBITS (bit_buf, size) - UBITS (SBITS (~bit_buf, 1), size);
    dc_diff = UBITS (bit_buf, size); if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
    COPYBITS (bit_buf, bits, size);
    return dc_diff;
  }
}


void k9requant::get_intra_block_B14 ()
{
#define bit_buf (inbitbuf)
  int i, li;
  int val;
  const DCTtab * tab;

  li = i = 0;

  while (1)
  {
    if (bit_buf >= 0x28000000)
    {
      tab = DCT_B14AC_5 + (UBITS (bit_buf, 5) - 5);

      i += tab->run;
      if (i >= 64) break;	/* end of block */

    normal_code:
      DUMPBITS (bit_buf, bits, tab->len);
      val = tab->level;
      val = (val ^ SBITS (bit_buf, 1)) - SBITS (bit_buf, 1);
      UPDATE_VAL
      if (val)
      {
        if (putAC(i - li - 1, val, 0)) break;
        li = i;
      }

      DUMPBITS (bit_buf, bits, 1);

      continue;
    }
    else if (bit_buf >= 0x04000000)
    {
      tab = DCT_B14_8 + (UBITS (bit_buf, 8) - 4);

      i += tab->run;
      if (i < 64) goto normal_code;

      /* escape code */
      i += (UBITS (bit_buf, 12) & 0x3F) - 64;
      if (i >= 64)
      {
        sliceError++;
        break;	/* illegal, check needed to avoid buffer overflow */
      }

      DUMPBITS (bit_buf, bits, 12);
      val = SBITS (bit_buf, 12);
      UPDATE_VAL
      if (val)
      {
        if (putAC(i - li - 1, val, 0)) break;
        li = i;
      }

      DUMPBITS (bit_buf, bits, 12);

      continue;
    }
    else if (bit_buf >= 0x02000000)
    {
      tab = DCT_B14_10 + (UBITS (bit_buf, 10) - 8);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00800000)
    {
      tab = DCT_13 + (UBITS (bit_buf, 13) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00200000)
    {
      tab = DCT_15 + (UBITS (bit_buf, 15) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else
    {
      tab = DCT_16 + UBITS (bit_buf, 16);
      DUMPBITS (bit_buf, bits, 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    sliceError++;
    break;	/* illegal, check needed to avoid buffer overflow */
  }

  COPYBITS (bit_buf, bits, 2);	/* end of block code */
}

void k9requant::get_intra_block_B15 ()
{
#define bit_buf (inbitbuf)
  int i, li;
  int val;
  const DCTtab * tab;

  li = i = 0;

  while (1)
  {
    if (bit_buf >= 0x04000000)
    {
      tab = DCT_B15_8 + (UBITS (bit_buf, 8) - 4);

      i += tab->run;
      if (i < 64)
      {
      normal_code:
        DUMPBITS (bit_buf, bits, tab->len);

        val = tab->level;
        val = (val ^ SBITS (bit_buf, 1)) - SBITS (bit_buf, 1);
        UPDATE_VAL
        if (val)
        {
          if (putAC(i - li - 1, val, 1)) break;
          li = i;
        }

        DUMPBITS (bit_buf, bits, 1);

        continue;
      }
      else
      {
        if (i >= 128) break; /* end of block */

        i += (UBITS (bit_buf, 12) & 0x3F) - 64;

        if (i >= 64)
        {
          sliceError++;
          break;	/* illegal, check against buffer overflow */
        }

        DUMPBITS (bit_buf, bits, 12);
        val = SBITS (bit_buf, 12);
        UPDATE_VAL
        if (val)
        {
          if (putAC(i - li - 1, val, 1)) break;
          li = i;
        }

        DUMPBITS (bit_buf, bits, 12);

        continue;
      }
    }
    else if (bit_buf >= 0x02000000)
    {
      tab = DCT_B15_10 + (UBITS (bit_buf, 10) - 8);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00800000)
    {
      tab = DCT_13 + (UBITS (bit_buf, 13) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00200000)
    {
      tab = DCT_15 + (UBITS (bit_buf, 15) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else
    {
      tab = DCT_16 + UBITS (bit_buf, 16);
      DUMPBITS (bit_buf, bits, 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    sliceError++;
    break;	/* illegal, check needed to avoid buffer overflow */
  }

  COPYBITS (bit_buf, bits, 4);	/* end of block code */
}

int k9requant::get_non_intra_block_rq (RunLevel *blk)
{
#define bit_buf (inbitbuf)
  //int q = quantizer_scale;
  //int nq = new_quantizer_scale, tst = (nq / q) + ((nq % q) ? 1 : 0);
  int i, li;
  int val;
  const DCTtab * tab;

  li = i = -1;

  if (bit_buf >= 0x28000000)
  {
    tab = DCT_B14DC_5 + (UBITS (bit_buf, 5) - 5);
    goto entry_1;
  }
  else goto entry_2;

  while (1)
  {
    if (bit_buf >= 0x28000000)
    {
      tab = DCT_B14AC_5 + (UBITS (bit_buf, 5) - 5);

    entry_1:
      i += tab->run;
      if (i >= 64)
        break;	/* end of block */

    normal_code:

      DUMPBITS (bit_buf, bits, tab->len);
      val = tab->level;
      val = (val ^ SBITS (bit_buf, 1)) - SBITS (bit_buf, 1);
      UPDATE_VAL
      if (val)
      {
        blk->level = val;
        blk->run = i - li - 1;
        li = i;
        blk++;
      }

      DUMPBITS (bit_buf, bits, 1);

      continue;
    }

  entry_2:
    if (bit_buf >= 0x04000000)
    {
      tab = DCT_B14_8 + (UBITS (bit_buf, 8) - 4);

      i += tab->run;
      if (i < 64) goto normal_code;

      /* escape code */

      i += (UBITS (bit_buf, 12) & 0x3F) - 64;

      if (i >= 64)
      {
        sliceError++;
        break;	/* illegal, check needed to avoid buffer overflow */
      }

      DUMPBITS (bit_buf, bits, 12);
      val = SBITS (bit_buf, 12);
      UPDATE_VAL
      if (val)
      {
        blk->level = val;
        blk->run = i - li - 1;
        li = i;
        blk++;
      }

      DUMPBITS (bit_buf, bits, 12);

      continue;
    }
    else if (bit_buf >= 0x02000000)
    {
      tab = DCT_B14_10 + (UBITS (bit_buf, 10) - 8);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00800000)
    {
      tab = DCT_13 + (UBITS (bit_buf, 13) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00200000)
    {
      tab = DCT_15 + (UBITS (bit_buf, 15) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else
    {
      tab = DCT_16 + UBITS (bit_buf, 16);
      DUMPBITS (bit_buf, bits, 16);

      i += tab->run;
      if (i < 64) goto normal_code;
    }

    sliceError++;
    break;	/* illegal, check needed to avoid buffer overflow */
  }
  DUMPBITS (bit_buf, bits, 2);	/* dump end of block code */

  blk->level = 0;

  return i;
}


int k9requant::get_non_intra_block_sav (RunLevel *blk, int cc)
{
#define bit_buf (inbitbuf)
  int i, li;
  int val;
  const DCTtab * tab;

#ifdef P_FRAME_NON_INTRA_DROP
	#if (P_FRAME_NON_INTRA_DROP < 0)
  RunLevel *oblk = blk;
#else
  int oval;
#endif
#endif

  li = i = -1;

  if (bit_buf >= 0x28000000)
  {
    tab = DCT_B14DC_5 + (UBITS (bit_buf, 5) - 5);
    goto entry_1;
  }
  else goto entry_2;

  while (1)
  {
    if (bit_buf >= 0x28000000)
    {
      tab = DCT_B14AC_5 + (UBITS (bit_buf, 5) - 5);

    entry_1:
      i += tab->run;
      if (i >= 64)
        break;	/* end of block */

    normal_code:

      DUMPBITS (bit_buf, bits, tab->len);
      val = tab->level;
      val = (val ^ SBITS (bit_buf, 1)) - SBITS (bit_buf, 1);
      SAVE_VAL
      if (li == -1)
      {
        if (abs(val) < abs(mb_sav_lev))
        {
          mb_sav_c = cc;
          mb_sav_lev = val;
          mb_sav_run = i - li - 1;
        }
      }
      UPDATE_VAL
      WRITE_VAL

      DUMPBITS (bit_buf, bits, 1);

      continue;
    }

  entry_2:
    if (bit_buf >= 0x04000000)
    {
      tab = DCT_B14_8 + (UBITS (bit_buf, 8) - 4);

      i += tab->run;
      if (i < 64) goto normal_code;

      /* escape code */

      i += (UBITS (bit_buf, 12) & 0x3F) - 64;

      if (i >= 64)
      {
        sliceError++;
        break;	/* illegal, check needed to avoid buffer overflow */
      }

      DUMPBITS (bit_buf, bits, 12);
      val = SBITS (bit_buf, 12);
      SAVE_VAL
      if (li == -1)
      {
        if (abs(val) < abs(mb_sav_lev))
        {
          mb_sav_c = cc;
          mb_sav_lev = val;
          mb_sav_run = i - li - 1;
        }
      }
      UPDATE_VAL
      WRITE_VAL

      DUMPBITS (bit_buf, bits, 12);

      continue;
    }
    else if (bit_buf >= 0x02000000)
    {
      tab = DCT_B14_10 + (UBITS (bit_buf, 10) - 8);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00800000)
    {
      tab = DCT_13 + (UBITS (bit_buf, 13) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00200000)
    {
      tab = DCT_15 + (UBITS (bit_buf, 15) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else
    {
      tab = DCT_16 + UBITS (bit_buf, 16);
      DUMPBITS (bit_buf, bits, 16);

      i += tab->run;
      if (i < 64) goto normal_code;
    }

    sliceError++;
    break;	/* illegal, check needed to avoid buffer overflow */
  }
  DUMPBITS (bit_buf, bits, 2);	/* dump end of block code */

#ifdef P_FRAME_NON_INTRA_DROP
	#if (P_FRAME_NON_INTRA_DROP < 0)
  blk -= (int)((blk - oblk) * (stress_factor / P_FRAME_NON_INTRA_DROP));
#ifdef DEMO
  if ((gopCount & 0x7F) < 10) blk = oblk;
#endif
	#endif
#endif

  blk->level = 0;

  return i;
}

#ifdef P_FRAME_NON_INTRA_DROP
int k9requant::get_non_intra_block_drop (RunLevel *blk, int cc)
{
#define bit_buf (inbitbuf)
  int i, li;
  int val;
  const DCTtab * tab;
#if (P_FRAME_NON_INTRA_DROP < 0)
  RunLevel *oblk = blk;
#else
  int oval;
#endif

  li = i = -1;

  if (bit_buf >= 0x28000000)
  {
    tab = DCT_B14DC_5 + (UBITS (bit_buf, 5) - 5);
    goto entry_1;
  }
  else goto entry_2;

  while (1)
  {
    if (bit_buf >= 0x28000000)
    {
      tab = DCT_B14AC_5 + (UBITS (bit_buf, 5) - 5);

    entry_1:
      i += tab->run;
      if (i >= 64)
        break;	/* end of block */

    normal_code:

      DUMPBITS (bit_buf, bits, tab->len);
      val = tab->level;
      val = (val ^ SBITS (bit_buf, 1)) - SBITS (bit_buf, 1);
      SAVE_VAL
      UPDATE_VAL
      WRITE_VAL

      DUMPBITS (bit_buf, bits, 1);

      continue;
    }

  entry_2:
    if (bit_buf >= 0x04000000)
    {
      tab = DCT_B14_8 + (UBITS (bit_buf, 8) - 4);

      i += tab->run;
      if (i < 64) goto normal_code;

      /* escape code */

      i += (UBITS (bit_buf, 12) & 0x3F) - 64;

      if (i >= 64)
      {
        sliceError++;
        break;	/* illegal, check needed to avoid buffer overflow */
      }

      DUMPBITS (bit_buf, bits, 12);
      val = SBITS (bit_buf, 12);
      SAVE_VAL
      UPDATE_VAL
      WRITE_VAL

      DUMPBITS (bit_buf, bits, 12);

      continue;
    }
    else if (bit_buf >= 0x02000000)
    {
      tab = DCT_B14_10 + (UBITS (bit_buf, 10) - 8);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00800000)
    {
      tab = DCT_13 + (UBITS (bit_buf, 13) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else if (bit_buf >= 0x00200000)
    {
      tab = DCT_15 + (UBITS (bit_buf, 15) - 16);
      i += tab->run;
      if (i < 64) goto normal_code;
    }
    else
    {
      tab = DCT_16 + UBITS (bit_buf, 16);
      DUMPBITS (bit_buf, bits, 16);

      i += tab->run;
      if (i < 64) goto normal_code;
    }

    sliceError++;
    break;	/* illegal, check needed to avoid buffer overflow */
  }
  DUMPBITS (bit_buf, bits, 2);	/* dump end of block code */

#if (P_FRAME_NON_INTRA_DROP < 0)
  blk -= (int)((blk - oblk) * (stress_factor / P_FRAME_NON_INTRA_DROP));
#ifdef DEMO
  if ((gopCount & 0x7F) < 10) blk = oblk;
#endif
	#endif

  blk->level = 0;

  return i;
}
#endif

#ifdef CHANGE_BRIGHTNESS
void k9requant::putDC(const sVLCtable *tab, int val)
{
  int absval, size;
  absval = abs(val);
  size = 0;
  while (absval)
  {
    absval >>= 1;
    size++;
  }
  putbits(tab[size].code,tab[size].len);
  if (size!=0)
  {
    if (val>=0) absval = val;
    else absval = val + (1<<size) - 1; /* val + (2 ^ size) - 1 */
    putbits(absval,size);
  }
}
#endif
void k9requant::slice_intra_DCT (const int cc)
{
#ifdef CHANGE_BRIGHTNESS
  if (cc == 0)
  {
    int val;
    int bri = get_luma_dc_dct_diff();
    if (dc_reset)
    {
      val = bri + (128 << intra_dc_precision);
      old_dc_pred = val;

      val += delta_bright << intra_dc_precision;
      if (val > (255 << intra_dc_precision)) val = 255 << intra_dc_precision;
      else if (val < 0) val = 0;

      bri = val - (128 << intra_dc_precision);
      new_dc_pred = val;

      dc_reset = 0;
    }
    else
    {
      val = bri + old_dc_pred;
      old_dc_pred = val;

      val += delta_bright << intra_dc_precision;
      if (val > (255 << intra_dc_precision)) val = 255 << intra_dc_precision;
      else if (val < 0) val = 0;

      bri = val - new_dc_pred;
      new_dc_pred = val;
    }
    putDC(DClumtab, bri);
  }
#else
  if (cc == 0)	get_luma_dc_dct_diff ();
#endif
  else			get_chroma_dc_dct_diff ();

  if (intra_vlc_format) get_intra_block_B15 ();
  else get_intra_block_B14 ();
}

void k9requant::slice_non_intra_DCT (int cur_block)
{
#ifdef P_FRAME_NON_INTRA_DROP
  if (picture_coding_type == P_TYPE)
  {
    if ((h_offset == 0) || (h_offset == horizontal_size_value - 16))
      get_non_intra_block_sav(block[cur_block], cur_block);
    else
      get_non_intra_block_drop(block[cur_block], cur_block);
  }
  else
    get_non_intra_block_rq(block[cur_block]);
#else
  if ((picture_coding_type == P_TYPE) && ((h_offset == 0) || (h_offset == horizontal_size_value - 16)))
    get_non_intra_block_sav(block[cur_block], cur_block);
  else
    get_non_intra_block_rq(block[cur_block]);
#endif
}

void k9requant::motion_fr_frame ( uint f_code[2] )
{
  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);
}

void k9requant::motion_fr_field ( uint f_code[2] )
{
  COPYBITS (bit_buf, bits, 1);
  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);

  COPYBITS (bit_buf, bits, 1);
  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);
}

void k9requant::motion_fr_dmv ( uint f_code[2] )
{
  get_motion_delta (f_code[0]);
  get_dmv ();

  get_motion_delta (f_code[1]);
  get_dmv ();
}

void k9requant::motion_fr_conceal ( )
{
  get_motion_delta (f_code[0][0]);
  get_motion_delta (f_code[0][1]);

  COPYBITS (bit_buf, bits, 1);
}

void k9requant::motion_fi_field ( uint f_code[2] )
{
  COPYBITS (bit_buf, bits, 1);

  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);
}

void k9requant::motion_fi_16x8 ( uint f_code[2] )
{
  COPYBITS (bit_buf, bits, 1);

  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);

  COPYBITS (bit_buf, bits, 1);

  get_motion_delta (f_code[0]);
  get_motion_delta (f_code[1]);
}

void k9requant::motion_fi_dmv ( uint f_code[2] )
{
  get_motion_delta (f_code[0]);
  get_dmv ();

  get_motion_delta (f_code[1]);
  get_dmv ();
}

void k9requant::motion_fi_conceal ()
{
  COPYBITS (bit_buf, bits, 1);

  get_motion_delta (f_code[0][0]);
  get_motion_delta (f_code[0][1]);

  COPYBITS (bit_buf, bits, 1);
}


void  k9requant::putmbdata(int macroblock_modes)
{
  putmbtype(macroblock_modes & 0x1F);

  /*switch (picture_coding_type)
  {
  	case I_TYPE:
  		if ((! (frame_pred_frame_dct)) && (picture_structure == FRAME_PICTURE))
  			putbits(macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
  		break;

  	case P_TYPE:
  		if (picture_structure != FRAME_PICTURE)
  		{
  			if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
  				putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
  			break;
  		}
  		else if (frame_pred_frame_dct) break;
  		else
  		{
  			if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
  				putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
  			if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
  				putbits(macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
  			break;
  		}

  	case B_TYPE:
  		if (picture_structure != FRAME_PICTURE)
  		{
  			if (! (macroblock_modes & MACROBLOCK_INTRA))
  				putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
  			break;
  		}
  		else if (frame_pred_frame_dct) break;
  		else
  		{
  			if (macroblock_modes & MACROBLOCK_INTRA) goto intra;
  			putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
  			if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
  			{
  				intra:
  				putbits(macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
  			}
  			break;
  		}
  }*/

  if (macroblock_modes & (MACROBLOCK_MOTION_FORWARD | MACROBLOCK_MOTION_BACKWARD))
  {
    if (picture_structure == FRAME_PICTURE)
    {
      if (frame_pred_frame_dct == 0)
      {
        putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
      }
    }
    else
    {
      putbits((macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
    }
  }
  if ((picture_structure == FRAME_PICTURE) && (frame_pred_frame_dct == 0) && (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN)))
  {
    putbits(macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
  }
}

void  k9requant::put_quantiser(int quantiser)
{
  putbits(q_scale_type ? map_non_linear_mquant[quantiser] : quantiser >> 1, 5);
  last_coded_scale = quantiser;
}

void  k9requant::putaddrinc(int addrinc)
{
  mb_out += addrinc;
  //LOGF("mb_out: %i\n", mb_out);
  if (mb_out > (horizontal_size_value >> 4))
  {
    sliceError++;
    //LOGF("mb_out: %i, hsv: %i, curo: %i\n", mb_out, horizontal_size_value, (int)outbytecnt + (wbuf - owbuf));
  }
  while (addrinc>33)
  {
    putbits(0x08,11); /* macroblock_escape */
    addrinc-= 33;
  }
  assert( addrinc >= 1 && addrinc <= 33 );
  putbits(addrinctab[addrinc-1].code,addrinctab[addrinc-1].len);
}

int  k9requant::slice_init (int code)
{
#define bit_buf (inbitbuf)

  int offset;
  const MBAtab * mba;

  mb_out = 0;
  v_offset = (code - 1) * 16;

  quantizer_scale = get_quantizer_scale ();
  new_quantizer_scale = getNewQuant(quantizer_scale, 0);
  put_quantiser(new_quantizer_scale);


  /* ignore intra_slice and all the extra data */
  while (bit_buf & 0x80000000)
  {
    DUMPBITS (bit_buf, bits, 9);
  }

  /* decode initial macroblock address increment */
  offset = 0;
  while (1)
  {
    if (bit_buf >= 0x08000000)
    {
      mba = MBA_5 + (UBITS (bit_buf, 6) - 2);
      break;
    }
    else if (bit_buf >= 0x01800000)
    {
      mba = MBA_11 + (UBITS (bit_buf, 12) - 24);
      break;
    }
    else switch (UBITS (bit_buf, 12))
      {
      case 8:		/* macroblock_escape */
        offset += 33;
        DUMPBITS (bit_buf, bits, 11);
        continue;
      default:	/* error */
        sliceError++;
        return 1;
      }
  }
  mb_add = offset + mba->mba + 1;
  mb_skip = 0;
  COPYBITS (bit_buf, bits, 1);
  DUMPBITS(bit_buf, bits, mba->len);

  h_offset = (offset + mba->mba) << 4;

  while (h_offset - (int)horizontal_size_value >= 0)
  {
    h_offset -= horizontal_size_value;
    v_offset += 16;
  }

  if (v_offset > (vertical_size_value - 16)) return 1;

  return 0;

}

void  k9requant::mpeg2_slice ( const int code )
{
#define bit_buf (inbitbuf)

#ifdef CHANGE_BRIGHTNESS
  dc_reset = 1;
#endif

  if (slice_init (code)) return;

  while (1)
  {
    int macroblock_modes;
    int mba_inc;
    const MBAtab * mba;

    macroblock_modes = get_macroblock_modes ();
    if (macroblock_modes & MACROBLOCK_QUANT) quantizer_scale = get_quantizer_scale ();

    if (macroblock_modes & MACROBLOCK_INTRA)
    {
#ifdef STAT
      if (picture_coding_type == P_TYPE) cnt_p_i++;
      else if (picture_coding_type == B_TYPE) cnt_b_i++;
#endif

      new_quantizer_scale = getNewQuant(quantizer_scale, 1);
      if (last_coded_scale == new_quantizer_scale) macroblock_modes &= 0xFFFFFFEF; // remove MACROBLOCK_QUANT
      else macroblock_modes |= MACROBLOCK_QUANT; //add MACROBLOCK_QUANT

      putaddrinc(mb_add + mb_skip); mb_skip = 0;
      putmbdata(macroblock_modes);
      if (macroblock_modes & MACROBLOCK_QUANT) put_quantiser(new_quantizer_scale);

      if (concealment_motion_vectors)
      {
        if (picture_structure == FRAME_PICTURE) motion_fr_conceal ();
        else motion_fi_conceal ();
      }

      curTable = quant_tables[quant_equ[quantizer_scale]][quant_equ[new_quantizer_scale]];
      if (!curTable)
      {
        /*DEBF("Inv. curTable: qs: %i nqs: %i qe_qs: %i qe_nqs: %i\n",
        		quantizer_scale, new_quantizer_scale,
        		quant_equ[quantizer_scale], quant_equ[new_quantizer_scale]);*/
        curTable = quant_table_id;
      }

      slice_intra_DCT ( 0);
      slice_intra_DCT ( 0);
      slice_intra_DCT ( 0);
      slice_intra_DCT ( 0);
      slice_intra_DCT ( 1);
      slice_intra_DCT ( 2);
    }
    else
    {
      int new_coded_block_pattern = 0;

      // begin saving data
      int batb;
      uint8	n_owbuf[32], *n_wbuf, *o_owbuf, *o_wbuf;
      uint32	n_outbitcnt, n_outbitbuf, o_outbitcnt, o_outbitbuf;

#ifdef CHANGE_BRIGHTNESS
      dc_reset = 1;
#endif

#define PUSH_BIT_IO \
			o_owbuf = owbuf; o_wbuf = wbuf; \
			o_outbitcnt = outbitcnt; o_outbitbuf = outbitbuf; \
			owbuf = wbuf = n_owbuf; \
			outbitcnt = BITS_IN_BUF; outbitbuf = 0;

#define POP_BIT_IO \
			n_wbuf = wbuf; \
			n_outbitcnt = outbitcnt; n_outbitbuf = outbitbuf; \
			owbuf = o_owbuf; wbuf = o_wbuf; \
			outbitcnt = o_outbitcnt; outbitbuf = o_outbitbuf;

      PUSH_BIT_IO

      if (picture_structure == FRAME_PICTURE)
        switch (macroblock_modes & MOTION_TYPE_MASK)
        {
        case MC_FRAME: MOTION_CALL (motion_fr_frame, macroblock_modes); break;
        case MC_FIELD: MOTION_CALL (motion_fr_field, macroblock_modes); break;
        case MC_DMV: MOTION_CALL (motion_fr_dmv, MACROBLOCK_MOTION_FORWARD); break;
        }
      else
        switch (macroblock_modes & MOTION_TYPE_MASK)
        {
        case MC_FIELD: MOTION_CALL (motion_fi_field, macroblock_modes); break;
        case MC_16X8: MOTION_CALL (motion_fi_16x8, macroblock_modes); break;
        case MC_DMV: MOTION_CALL (motion_fi_dmv, MACROBLOCK_MOTION_FORWARD); break;
        }

      POP_BIT_IO

      // end saving data

#ifdef STAT
      if (picture_coding_type == P_TYPE) cnt_p_ni++;
      else if (picture_coding_type == B_TYPE) cnt_b_ni++;
#endif
      new_quantizer_scale = getNewQuant(quantizer_scale, 0);

      if (macroblock_modes & MACROBLOCK_PATTERN)
      {
        int coded_block_pattern = get_coded_block_pattern ();

        mb_sav_lev = 0xFFFF;
        curTable = quant_tables[quant_equ[quantizer_scale]][quant_equ[new_quantizer_scale]];
        if (!curTable)
        {
          /*DEBF("Inv. curTable: qs: %i nqs: %i qe_qs: %i qe_nqs: %i\n",
          		quantizer_scale, new_quantizer_scale,
          		quant_equ[quantizer_scale], quant_equ[new_quantizer_scale]);*/
          curTable = quant_table_id;
        }

        if (coded_block_pattern & 0x20) { slice_non_intra_DCT(0); if (isNotEmpty(block[0])) new_coded_block_pattern |= 0x20; }
      if (coded_block_pattern & 0x10) { slice_non_intra_DCT(1); if (isNotEmpty(block[1])) new_coded_block_pattern |= 0x10; }
      if (coded_block_pattern & 0x08) { slice_non_intra_DCT(2); if (isNotEmpty(block[2])) new_coded_block_pattern |= 0x08; }
      if (coded_block_pattern & 0x04) { slice_non_intra_DCT(3); if (isNotEmpty(block[3])) new_coded_block_pattern |= 0x04; }
      if (coded_block_pattern & 0x02) { slice_non_intra_DCT(4); if (isNotEmpty(block[4])) new_coded_block_pattern |= 0x02; }
      if (coded_block_pattern & 0x01) { slice_non_intra_DCT(5); if (isNotEmpty(block[5])) new_coded_block_pattern |= 0x01; }
#ifdef P_FRAME_NON_INTRA_DROP
        if (picture_coding_type == P_TYPE) new_quantizer_scale = quantizer_scale;
#endif
        if (!new_coded_block_pattern)
        {
          macroblock_modes &= 0xFFFFFFED; // remove MACROBLOCK_PATTERN and MACROBLOCK_QUANT flag
          if (	(picture_coding_type == P_TYPE)
               && !(macroblock_modes & MACROBLOCK_MOTION_FORWARD))
          {
            assert(n_wbuf == n_owbuf);
            assert(n_outbitcnt == BITS_IN_BUF);

            if ((h_offset == 0) || (h_offset == horizontal_size_value - 16))  // can't skip last mb
            {
              // we can't transmit mv (0,0) since PMV could be different than 0 for last block
              // so we transmit the single smallest coeff. instead unrequantised
              // anyway this is likely to take no more bit than transmiting a null mv....

              assert((mb_sav_lev) && (mb_sav_lev != 0xFFFF));

              new_coded_block_pattern = 1 << (5 - mb_sav_c);
              macroblock_modes |= MACROBLOCK_PATTERN;
              new_quantizer_scale = quantizer_scale;
              block[mb_sav_c][0].run = mb_sav_run; block[mb_sav_c][0].level = mb_sav_lev;
              block[mb_sav_c][1].run = 0; block[mb_sav_c][1].level = 0;
            }
            else
            {
              mb_skip += mb_add;
              goto skip_mb;
            }
          }
        }
      }

      if (last_coded_scale == new_quantizer_scale) macroblock_modes &= 0xFFFFFFEF; // remove MACROBLOCK_QUANT
      else if (macroblock_modes & MACROBLOCK_PATTERN) macroblock_modes |= MACROBLOCK_QUANT; //add MACROBLOCK_QUANT
      assert( (macroblock_modes & MACROBLOCK_PATTERN) || !(macroblock_modes & MACROBLOCK_QUANT) );

      putaddrinc(mb_add + mb_skip); mb_skip = 0;
      putmbdata(macroblock_modes);
      if (macroblock_modes & MACROBLOCK_QUANT) put_quantiser(new_quantizer_scale);

      // put saved motion data...
      for (batb = 0; batb < (n_wbuf - n_owbuf); batb++) putbits(n_owbuf[batb], 8);
      putbits(n_outbitbuf, BITS_IN_BUF - n_outbitcnt);
      // end saved motion data...

      if (macroblock_modes & MACROBLOCK_PATTERN)
      {
        putcbp(new_coded_block_pattern);

        if (new_coded_block_pattern & 0x20) putnonintrablk(block[0]);
        if (new_coded_block_pattern & 0x10) putnonintrablk(block[1]);
        if (new_coded_block_pattern & 0x08) putnonintrablk(block[2]);
        if (new_coded_block_pattern & 0x04) putnonintrablk(block[3]);
        if (new_coded_block_pattern & 0x02) putnonintrablk(block[4]);
        if (new_coded_block_pattern & 0x01) putnonintrablk(block[5]);
      }
    }

  skip_mb:

    NEXT_MACROBLOCK;

    mba_inc = 0;
    while (1)
    {
      if (bit_buf >= 0x10000000)
      {
        mba = MBA_5 + (UBITS (bit_buf, 5) - 2);
        break;
      }
      else if (bit_buf >= 0x03000000)
      {
        mba = MBA_11 + (UBITS (bit_buf, 11) - 24);
        break;
      }
      else
        switch (UBITS (bit_buf, 11))
        {
        case 8:		/* macroblock_escape */
          mba_inc += 33;
          DUMPBITS (bit_buf, bits, 11);
          continue;
        default:	/* end of slice, or error */
          //LOGF("hoffset: %i, hsv: %i, curo: %i\n", h_offset, horizontal_size_value, (int)outbytecnt + (wbuf - owbuf));
          if (h_offset != 0)
            sliceError++;
          return;
        }
    }
    DUMPBITS (bit_buf, bits, mba->len); //PPP

    mba_inc += mba->mba;
    mb_add = mba_inc + 1;

#ifdef CHANGE_BRIGHTNESS
    if (mba_inc) dc_reset = 1;
#endif

  if (mba_inc) do { NEXT_MACROBLOCK; }
      while (--mba_inc);
  }

}

/////---- end ext mpeg code

void  k9requant::run ()
{
  uint8 ID, found;
  int64 greedyFactor, greedyFactor2;
  int i;

#ifdef DEMO
  gopCount = 0;
#endif

#ifdef LOG_RATE_CONTROL
  LOG_FILE = fopen("Logfile.txt", "w");
#endif

#ifdef STAT
  ori_i = ori_p = ori_b = 0;
  new_i = new_p = new_b = 0;
  cnt_i = cnt_p = cnt_b = 0;
  cnt_p_i = cnt_p_ni = 0;
  cnt_b_i = cnt_b_ni = 0;
#endif

#ifdef USE_FD
  if (argc < 3) { USAGE }
  ifd = fopen(argv[argc - 2], "rb");
  ofd = fopen(argv[argc - 1], "wb");
  if (!ifd)
  {
    LOGF("Bad input path! (%s)\n", argv[argc - 2]);
    return 2;
  }
  if (!ofd)
  {
    LOGF("Bad output path! (%s)\n", argv[argc - 1]);
    return 2;
  }
  argc -= 2;
#endif

#ifndef THREAD
  rbuf = cbuf = orbuf = malloc(BUF_SIZE);
  wbuf = owbuf = malloc(BUF_SIZE);
  inbytecnt = outbytecnt = 0;
  eof = 0;
#endif

  validPicHeader = 0;
  validSeqHeader = 0;
  validExtHeader = 0;

#ifndef THREAD
  // argument parsing
#ifdef CHANGE_BRIGHTNESS
  if (argc < 5) { USAGE }
  delta_bright = atoi(argv[4]);
#else
  if (argc < 4) { USAGE }
#endif
  fact_x = atof(argv[1]);
  sscanf(argv[3], "%lld", &orim2vsize);
#endif

#ifdef THREAD
	orim2vsize=rqt_visize;
	  fact_x     = rqt_fact;
#endif

  greedyFactor = orim2vsize / 100;
  greedyFactor2 = orim2vsize / 50;

#ifndef THREAD
  if (fact_x <= 1.0)
  {
    unsigned char buf[4096];

    while(1)
    {
      int i = read(0, buf, 4096);
      if (i > 0) write(1, buf, i);
      else return 0;
    }
  }
  
#endif
   if (fact_x > 10.0) fact_x = 10.0;

  // factor and stresses setting
  initRequant();

 // fill quant table
  // id table
  for (i = -2048; i <= 2047; i++) quant_table_id[i] = i;

  // other tables
  for (i = 0; i < 42; i++)
  {
    int q = quantisers[i];
    int j;

    for (j = i + 1; j < 42; j++)
    {
      int nq = quantisers[j];
      int k;
      short *cTab = quant_tables[quant_equ[q]][quant_equ[nq]];

      for (k = -2048; k <= 2047; k++)
      {
        int ov = k*q;
        int t = ov / nq;

        if (fact_x <= max_alt_table)
        {
          int t2, t3;
          int d, d2, d3;
          int nv, nv2, nv3;

          t2 = t + 1;
          t3 = t - 1;

          nv = t * nq;
          nv2 = t2 * nq;
          nv3 = t3 * nq;

          d = abs(nv - ov);
          d2 = abs(nv2 - ov);
          d3 = abs(nv3 - ov);

          if (d2 < d) { d = d2; t = t2; }
          if (d3 < d) t = t3;
        }

        if (t > 2047) t = 2047;
        else if (t < -2048) t = -2048;

        cTab[k] = t;
      }
    }
  }

#ifndef THREAD
  LOG("M2VRequantiser by Makira.\n");
#ifdef WIN
  fprintf(stderr, "Using %f as factor, %lld as m2v size.\n", fact_x, orim2vsize);
#else
  LOGF("Using %f as factor, %lld as m2v size.\n", fact_x, orim2vsize);
#endif
#endif

  // recoding
  while(1)
  {
    // get next start code prefix
    found = 0;
    while (!found)
    {
#ifndef REMOVE_BYTE_STUFFING
      LOCK(3)
#else
      LOCK(8)
      if		(		(cbuf[7] == 0) && (cbuf[6] == 0) && (cbuf[5] == 0) && (cbuf[4] == 0)
           &&  (cbuf[3] == 0) && (cbuf[2] == 0) && (cbuf[1] == 0) && (cbuf[0] == 0) ) { SEEKR(1) }
      else
#endif
      if ( (cbuf[0] == 0) && (cbuf[1] == 0) && (cbuf[2] == 1) ) found = 1; // start code !
    else { COPY(1) } // continue search
    }
    COPY(3)

    // get start code
    LOCK(1)
    ID = cbuf[0];
    COPY(1)

    if (ID == 0x00) // pic header
    {
      LOCK(4)
      picture_coding_type = (cbuf[1] >> 3) & 0x7;
      if (picture_coding_type < 1 || picture_coding_type > 3)
      {
        DEBF("illegal picture_coding_type: %i\n", picture_coding_type);
        validPicHeader = 0;
      }
      else
      {
        validPicHeader = 1;
        cbuf[1] |= 0x7; cbuf[2] = 0xFF; cbuf[3] |= 0xF8; // vbv_delay is now 0xFFFF
      }

      validExtHeader = 0;

      COPY(4)
    }
    else if (ID == 0xB3) // seq header
    {
      LOCK(8)
      horizontal_size_value = (cbuf[0] << 4) | (cbuf[1] >> 4);
      vertical_size_value = ((cbuf[1] & 0xF) << 8) | cbuf[2];
      if (	horizontal_size_value > 720 || horizontal_size_value < 352
           ||  vertical_size_value > 576 || vertical_size_value < 480
           || (horizontal_size_value & 0xF) || (vertical_size_value & 0xF))
      {
        DEBF("illegal size, hori: %i verti: %i\n", horizontal_size_value, vertical_size_value);
        validSeqHeader = 0;
      }
      else
        validSeqHeader = 1;

      validPicHeader = 0;
      validExtHeader = 0;

      COPY(8)
    }
    else if (ID == 0xB5) // extension
    {
      LOCK(1)
      if ((cbuf[0] >> 4) == 0x8) // pic coding ext
      {
        LOCK(5)

        f_code[0][0] = (cbuf[0] & 0xF) - 1;
        f_code[0][1] = (cbuf[1] >> 4) - 1;
        f_code[1][0] = (cbuf[1] & 0xF) - 1;
        f_code[1][1] = (cbuf[2] >> 4) - 1;

        intra_dc_precision = (cbuf[2] >> 2) & 0x3;
        picture_structure = cbuf[2] & 0x3;
        frame_pred_frame_dct = (cbuf[3] >> 6) & 0x1;
        concealment_motion_vectors = (cbuf[3] >> 5) & 0x1;
        q_scale_type = (cbuf[3] >> 4) & 0x1;
        intra_vlc_format = (cbuf[3] >> 3) & 0x1;
        alternate_scan = (cbuf[3] >> 2) & 0x1;

        if (	(f_code[0][0] > 8 && f_code[0][0] < 14)
             ||  (f_code[0][1] > 8 && f_code[0][1] < 14)
             ||  (f_code[1][0] > 8 && f_code[1][0] < 14)
             ||  (f_code[1][1] > 8 && f_code[1][1] < 14)
             ||  picture_structure == 0)
        {
          DEBF("illegal ext, f_code[0][0]: %i f_code[0][1]: %i f_code[1][0]: %i f_code[1][1]: %i picture_structure:%i\n",
               f_code[0][0], f_code[0][1], f_code[1][0], f_code[1][1], picture_structure);
          validExtHeader = 0;
        }
        else
          validExtHeader = 1;
        COPY(5)
      }
      else
      {
        COPY(1)
      }
    }
    else if (ID == 0xB8) // gop header
    {
      LOCK(4)
      COPY(4)

#ifdef DEMO
      gopCount++;
#endif
    }
    else if ((ID >= 0x01) && (ID <= 0xAF) && validPicHeader && validSeqHeader && validExtHeader) // slice
    {
      uint8 *outTemp = wbuf, *inTemp = cbuf;
      int64 threshold;

      bytediff = (outbytecnt + (wbuf - owbuf)) - ((inbytecnt - (rbuf - cbuf)) / fact_x);


      if (inbytecnt < greedyFactor2) threshold = inbytecnt >> 1;
      else if (orim2vsize - inbytecnt < greedyFactor2) threshold = (orim2vsize - inbytecnt) >> 1;
      else threshold = greedyFactor;

      if (threshold < 1024) threshold = 1024;

      stress_factor = (float)(bytediff + threshold) / (float)(threshold << 1);
      if (stress_factor > 1.0f)		stress_factor = 1.0f;
      else if (stress_factor < 0.0f)	stress_factor = 0.0f;
 

#ifdef LOG_RATE_CONTROL
      /*fprintf(LOG_FILE, "%f%%: Requested: %f  Current: %f  Delta: %lld   Threshold: %f  Stress: %f\n",
      	(float)(100.0f*inbytecnt)/orim2vsize,		//	percent
      	(float)fact_x,								//	requested
      	(float)(inbytecnt - (rbuf - cbuf))/(float)(outbytecnt + (wbuf - owbuf)), //	current
      	(long long)bytediff,						//	delta
      	(float)threshold, 							//	threshold
      	stress_factor								//	Stress
      );*/
      fprintf(LOG_FILE, "inb: %.0f inb_c: %.0f oub: %.0f oub_c: %.0f cur: %.3f dif: %.0f thr: %.0f str: %.03f\n",
              (float)inbytecnt,
              (float)(inbytecnt - (rbuf - cbuf)),
              (float)outbytecnt,
              (float)(outbytecnt + (wbuf - owbuf)),
              (float)(inbytecnt - (rbuf - cbuf))/(float)(outbytecnt + (wbuf - owbuf)),
              (float)bytediff,
              (float)threshold,
              (float)stress_factor );
#endif


#ifndef CHANGE_BRIGHTNESS
      if (	((picture_coding_type == I_TYPE) && ( stress_factor > i_min_stress))
           ||  ((picture_coding_type == P_TYPE) && ( stress_factor > p_min_stress))
           ||  ((picture_coding_type == B_TYPE) && ( stress_factor > b_min_stress))
#ifdef DEMO
           ||	((gopCount & 0x7F) < 10)
#endif
         )
#endif
      {
        // init error
        sliceError = 0;

        // init bit buffer
        inbitbuf = 0; inbitcnt = 0;
        outbitbuf = 0; outbitcnt = BITS_IN_BUF;

        // get 32 bits
        Refill_bits();
        Refill_bits();
        Refill_bits();
        Refill_bits();

        // begin bit level recoding
        mpeg2_slice(ID);
        flush_read_buffer();
        flush_write_buffer();
        // end bit level recoding

#ifndef CHANGE_BRIGHTNESS
        if ((wbuf - outTemp > cbuf - inTemp) || (sliceError > MAX_ERRORS)) // yes that might happen, rarely
        {
#ifndef NDEBUG
          if (sliceError > MAX_ERRORS)
          {
            DEBF("sliceError (%i) > MAX_ERRORS (%i)\n", sliceError, MAX_ERRORS);
          }
#endif

          // in this case, we'll just use the original slice !
          tc_memcpy(outTemp, inTemp, cbuf - inTemp);
          wbuf = outTemp + (cbuf - inTemp);

          // adjust outbytecnt
          outbytecnt -= (wbuf - outTemp) - (cbuf - inTemp);
        }
#endif

#ifdef STAT
	#ifdef LOG_RATE_CONTROL
        if (picture_coding_type == I_TYPE) fprintf(LOG_FILE, "-I-\n");
#endif
        switch(picture_coding_type)
        {
        case I_TYPE:
          ori_i += cbuf - inTemp;
          new_i += (wbuf - outTemp > cbuf - inTemp) ? (cbuf - inTemp) : (wbuf - outTemp);
          cnt_i ++;
          break;

        case P_TYPE:
          ori_p += cbuf - inTemp;
          new_p += (wbuf - outTemp > cbuf - inTemp) ? (cbuf - inTemp) : (wbuf - outTemp);
          cnt_p ++;
          break;

        case B_TYPE:
          ori_b += cbuf - inTemp;
          new_b += (wbuf - outTemp > cbuf - inTemp) ? (cbuf - inTemp) : (wbuf - outTemp);
          cnt_b ++;
          break;

        default:
          assert(0);
          break;
        }
#endif
      }
    }

#ifndef NDEBUG
    if ((ID >= 0x01) && (ID <= 0xAF) && (!validPicHeader || !validSeqHeader || !validExtHeader))
    {
      if (!validPicHeader) DEBF("missing pic header (%02X)\n", ID);
      if (!validSeqHeader) DEBF("missing seq header (%02X)\n", ID);
      if (!validExtHeader) DEBF("missing ext header (%02X)\n", ID);
    }
#endif
if (rbuf - orbuf > MAX_READ) { MOV_READ }
   if (wbuf - owbuf > MIN_WRITE) { WRITE }
  }


#ifdef LOG_RATE_CONTROL
  fclose(LOG_FILE);
#endif
  rqt_run=false;
  // keeps gcc happy
  return ;
}

void k9requant::initvar()
{
	cbuf = NULL;
	rbuf = NULL;
	wbuf = NULL;
	orbuf = NULL;
	owbuf = NULL;
	inbitcnt = outbitcnt = 0;
	inbitbuf =  outbitbuf = 0;
	inbytecnt = outbytecnt = 0;
	fact_x = 0;
	mloka1 = mloka2 = eof = 0;
	orim2vsize = 0;
	bytediff = 0;
	stress_factor = 0;
	i_factor = 0;
	p_factor = 0;
	b_factor = 0;
	i_min_stress = 0;
	p_min_stress = 0;
	b_min_stress = 0;
	quant_table_id = &quant_table_id_data[2048];
	horizontal_size_value = 0;
	vertical_size_value = 0;

	picture_coding_type = 0;

	memset( f_code,0 , sizeof(f_code));
	intra_dc_precision = 0;
	picture_structure = 0;
	frame_pred_frame_dct = 0;
	concealment_motion_vectors = 0;
	q_scale_type = 0;
	intra_vlc_format = 0;
	alternate_scan = 0;

	validPicHeader = 0;
	validSeqHeader = 0;
	validExtHeader = 0;
	sliceError = 0;

	quantizer_scale = 0;
	new_quantizer_scale = 0;
	last_coded_scale = 0;
	h_offset = v_offset = 0;
	mb_skip = mb_add = 0;
	mb_out = 0;

	mb_sav_run = mb_sav_lev = mb_sav_c = 0;
	curTable = NULL;
	memset( block, 0, sizeof(block));
}



void k9requant::initRequant() {
 int i;
  if (fact_x <= 1.0)
  {
    i_factor = i_factors[0];
    p_factor = p_factors[0];
    b_factor = b_factors[0];
    i_min_stress = i_min_stresses[0];
    p_min_stress = p_min_stresses[0];
    b_min_stress = b_min_stresses[0];
  }
  else if (fact_x >= 10.0)
  {
    i_factor = i_factors[2];
    p_factor = p_factors[2];
    b_factor = b_factors[2];
    i_min_stress = i_min_stresses[2];
    p_min_stress = p_min_stresses[2];
    b_min_stress = b_min_stresses[2];
  }
  else if (fact_x <= 3.0) // 1.0 .. 3.0
  {
    double inter = (fact_x - 1.0)/(3.0 - 1.0);
    i_factor = i_factors[0] + inter * (i_factors[1] - i_factors[0]);
    p_factor = p_factors[0] + inter * (p_factors[1] - p_factors[0]);
    b_factor = b_factors[0] + inter * (b_factors[1] - b_factors[0]);
    i_min_stress = i_min_stresses[0] + inter * (i_min_stresses[1] - i_min_stresses[0]);
    p_min_stress = p_min_stresses[0] + inter * (p_min_stresses[1] - p_min_stresses[0]);
    b_min_stress = b_min_stresses[0] + inter * (b_min_stresses[1] - b_min_stresses[0]);
  }
  else // 3.0 .. 10.0
  {
    double inter = (fact_x - 3.0)/(10.0 - 3.0);
    i_factor = i_factors[1] + inter * (i_factors[2] - i_factors[1]);
    p_factor = p_factors[1] + inter * (p_factors[2] - p_factors[1]);
    b_factor = b_factors[1] + inter * (b_factors[2] - b_factors[1]);
    i_min_stress = i_min_stresses[1] + inter * (i_min_stresses[2] - i_min_stresses[1]);
    p_min_stress = p_min_stresses[1] + inter * (p_min_stresses[2] - p_min_stresses[1]);
    b_min_stress = b_min_stresses[1] + inter * (b_min_stresses[2] - b_min_stresses[1]);
  }

  /*LOGF(   "i_factor: %i p_factor: %i b_factor: %i\n"
  		"i_min_stress: %.02f p_min_stress: %.02f b_min_stress: %.02f\n",
  		i_factor, p_factor, b_factor,
  		i_min_stress, p_min_stress, b_min_stress);*/

 

}

bool k9requant::lock( int64 x) {
  if (unlikely ((x) > (rbuf - cbuf))) 
  { 
    if (likely (wbuf))
    {
      QMutexLocker locker( &mutw );
      //mutw.lock();
      rqt_wcnt = wbuf - owbuf;
      condw.wakeAll();
      //mutw.unlock();
    }
    //mutr.lock();
    QMutexLocker locker( &mutr );
    while (!rqt_rcnt)
    {
      condr.wait( &mutr);
      if (rqt_stop==true) {
	//mutr.unlock();
	return false;
      }
    }
    cbuf       = rqt_rptr;    //src buffer
    rbuf =orbuf  = cbuf;
    rbuf      += rqt_rcnt + 3;  // end of src buffer
    rqt_rcnt   = 0;
    owbuf      = rqt_wptr;   // dest buffer
    inbytecnt  = rqt_inbytes;
    outbytecnt = rqt_outbytes;
    orim2vsize = rqt_visize;
    //mutr.unlock();
    wbuf = owbuf;
    if (    fact_x    <  rqt_fact) {
	fact_x=rqt_fact;
	initRequant();
    }
    fact_x=rqt_fact;
  }

  return true;

}