Git init
[external/libtheora.git] / lib / enquant.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
5  * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
7  *                                                                  *
8  * THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009                *
9  * by the Xiph.Org Foundation http://www.xiph.org/                  *
10  *                                                                  *
11  ********************************************************************
12
13   function:
14   last mod: $Id: enquant.c 16503 2009-08-22 18:14:02Z giles $
15
16  ********************************************************************/
17 #include <stdlib.h>
18 #include <string.h>
19 #include "encint.h"
20
21
22
23 void oc_quant_params_pack(oggpack_buffer *_opb,const th_quant_info *_qinfo){
24   const th_quant_ranges *qranges;
25   const th_quant_base   *base_mats[2*3*64];
26   int                    indices[2][3][64];
27   int                    nbase_mats;
28   int                    nbits;
29   int                    ci;
30   int                    qi;
31   int                    qri;
32   int                    qti;
33   int                    pli;
34   int                    qtj;
35   int                    plj;
36   int                    bmi;
37   int                    i;
38   i=_qinfo->loop_filter_limits[0];
39   for(qi=1;qi<64;qi++)i=OC_MAXI(i,_qinfo->loop_filter_limits[qi]);
40   nbits=OC_ILOG_32(i);
41   oggpackB_write(_opb,nbits,3);
42   for(qi=0;qi<64;qi++){
43     oggpackB_write(_opb,_qinfo->loop_filter_limits[qi],nbits);
44   }
45   /*580 bits for VP3.*/
46   i=1;
47   for(qi=0;qi<64;qi++)i=OC_MAXI(_qinfo->ac_scale[qi],i);
48   nbits=OC_ILOGNZ_32(i);
49   oggpackB_write(_opb,nbits-1,4);
50   for(qi=0;qi<64;qi++)oggpackB_write(_opb,_qinfo->ac_scale[qi],nbits);
51   /*516 bits for VP3.*/
52   i=1;
53   for(qi=0;qi<64;qi++)i=OC_MAXI(_qinfo->dc_scale[qi],i);
54   nbits=OC_ILOGNZ_32(i);
55   oggpackB_write(_opb,nbits-1,4);
56   for(qi=0;qi<64;qi++)oggpackB_write(_opb,_qinfo->dc_scale[qi],nbits);
57   /*Consolidate any duplicate base matrices.*/
58   nbase_mats=0;
59   for(qti=0;qti<2;qti++)for(pli=0;pli<3;pli++){
60     qranges=_qinfo->qi_ranges[qti]+pli;
61     for(qri=0;qri<=qranges->nranges;qri++){
62       for(bmi=0;;bmi++){
63         if(bmi>=nbase_mats){
64           base_mats[bmi]=qranges->base_matrices+qri;
65           indices[qti][pli][qri]=nbase_mats++;
66           break;
67         }
68         else if(memcmp(base_mats[bmi][0],qranges->base_matrices[qri],
69          sizeof(base_mats[bmi][0]))==0){
70           indices[qti][pli][qri]=bmi;
71           break;
72         }
73       }
74     }
75   }
76   /*Write out the list of unique base matrices.
77     1545 bits for VP3 matrices.*/
78   oggpackB_write(_opb,nbase_mats-1,9);
79   for(bmi=0;bmi<nbase_mats;bmi++){
80     for(ci=0;ci<64;ci++)oggpackB_write(_opb,base_mats[bmi][0][ci],8);
81   }
82   /*Now store quant ranges and their associated indices into the base matrix
83      list.
84     46 bits for VP3 matrices.*/
85   nbits=OC_ILOG_32(nbase_mats-1);
86   for(i=0;i<6;i++){
87     qti=i/3;
88     pli=i%3;
89     qranges=_qinfo->qi_ranges[qti]+pli;
90     if(i>0){
91       if(qti>0){
92         if(qranges->nranges==_qinfo->qi_ranges[qti-1][pli].nranges&&
93          memcmp(qranges->sizes,_qinfo->qi_ranges[qti-1][pli].sizes,
94          qranges->nranges*sizeof(qranges->sizes[0]))==0&&
95          memcmp(indices[qti][pli],indices[qti-1][pli],
96          (qranges->nranges+1)*sizeof(indices[qti][pli][0]))==0){
97           oggpackB_write(_opb,1,2);
98           continue;
99         }
100       }
101       qtj=(i-1)/3;
102       plj=(i-1)%3;
103       if(qranges->nranges==_qinfo->qi_ranges[qtj][plj].nranges&&
104        memcmp(qranges->sizes,_qinfo->qi_ranges[qtj][plj].sizes,
105        qranges->nranges*sizeof(qranges->sizes[0]))==0&&
106        memcmp(indices[qti][pli],indices[qtj][plj],
107        (qranges->nranges+1)*sizeof(indices[qti][pli][0]))==0){
108         oggpackB_write(_opb,0,1+(qti>0));
109         continue;
110       }
111       oggpackB_write(_opb,1,1);
112     }
113     oggpackB_write(_opb,indices[qti][pli][0],nbits);
114     for(qi=qri=0;qi<63;qri++){
115       oggpackB_write(_opb,qranges->sizes[qri]-1,OC_ILOG_32(62-qi));
116       qi+=qranges->sizes[qri];
117       oggpackB_write(_opb,indices[qti][pli][qri+1],nbits);
118     }
119   }
120 }
121
122 static void oc_iquant_init(oc_iquant *_this,ogg_uint16_t _d){
123   ogg_uint32_t t;
124   int          l;
125   _d<<=1;
126   l=OC_ILOGNZ_32(_d)-1;
127   t=1+((ogg_uint32_t)1<<16+l)/_d;
128   _this->m=(ogg_int16_t)(t-0x10000);
129   _this->l=l;
130 }
131
132 /*See comments at oc_dequant_tables_init() for how the quantization tables'
133    storage should be initialized.*/
134 void oc_enquant_tables_init(ogg_uint16_t *_dequant[64][3][2],
135  oc_iquant *_enquant[64][3][2],const th_quant_info *_qinfo){
136   int qi;
137   int pli;
138   int qti;
139   /*Initialize the dequantization tables first.*/
140   oc_dequant_tables_init(_dequant,NULL,_qinfo);
141   /*Derive the quantization tables directly from the dequantization tables.*/
142   for(qi=0;qi<64;qi++)for(qti=0;qti<2;qti++)for(pli=0;pli<3;pli++){
143     int zzi;
144     int plj;
145     int qtj;
146     int dupe;
147     dupe=0;
148     for(qtj=0;qtj<=qti;qtj++){
149       for(plj=0;plj<(qtj<qti?3:pli);plj++){
150         if(_dequant[qi][pli][qti]==_dequant[qi][plj][qtj]){
151           dupe=1;
152           break;
153         }
154       }
155       if(dupe)break;
156     }
157     if(dupe){
158       _enquant[qi][pli][qti]=_enquant[qi][plj][qtj];
159       continue;
160     }
161     /*In the original VP3.2 code, the rounding offset and the size of the
162        dead zone around 0 were controlled by a "sharpness" parameter.
163       We now R-D optimize the tokens for each block after quantization,
164        so the rounding offset should always be 1/2, and an explicit dead
165        zone is unnecessary.
166       Hence, all of that VP3.2 code is gone from here, and the remaining
167        floating point code has been implemented as equivalent integer
168        code with exact precision.*/
169     for(zzi=0;zzi<64;zzi++){
170       oc_iquant_init(_enquant[qi][pli][qti]+zzi,
171        _dequant[qi][pli][qti][zzi]);
172     }
173   }
174 }
175
176
177
178 /*This table gives the square root of the fraction of the squared magnitude of
179    each DCT coefficient relative to the total, scaled by 2**16, for both INTRA
180    and INTER modes.
181   These values were measured after motion-compensated prediction, before
182    quantization, over a large set of test video (from QCIF to 1080p) encoded at
183    all possible rates.
184   The DC coefficient takes into account the DPCM prediction (using the
185    quantized values from neighboring blocks, as the encoder does, but still
186    before quantization of the coefficient in the current block).
187   The results differ significantly from the expected variance (e.g., using an
188    AR(1) model of the signal with rho=0.95, as is frequently done to compute
189    the coding gain of the DCT).
190   We use them to estimate an "average" quantizer for a given quantizer matrix,
191    as this is used to parameterize a number of the rate control decisions.
192   These values are themselves probably quantizer-matrix dependent, since the
193    shape of the matrix affects the noise distribution in the reference frames,
194    but they should at least give us _some_ amount of adaptivity to different
195    matrices, as opposed to hard-coding a table of average Q values for the
196    current set.
197   The main features they capture are that a) only a few of the quantizers in
198    the upper-left corner contribute anything significant at all (though INTER
199    mode is significantly flatter) and b) the DPCM prediction of the DC
200    coefficient gives a very minor improvement in the INTRA case and a quite
201    significant one in the INTER case (over the expected variance).*/
202 static const ogg_uint16_t OC_RPSD[2][64]={
203   {
204     52725,17370,10399, 6867, 5115, 3798, 2942, 2076,
205     17370, 9900, 6948, 4994, 3836, 2869, 2229, 1619,
206     10399, 6948, 5516, 4202, 3376, 2573, 2015, 1461,
207      6867, 4994, 4202, 3377, 2800, 2164, 1718, 1243,
208      5115, 3836, 3376, 2800, 2391, 1884, 1530, 1091,
209      3798, 2869, 2573, 2164, 1884, 1495, 1212,  873,
210      2942, 2229, 2015, 1718, 1530, 1212, 1001,  704,
211      2076, 1619, 1461, 1243, 1091,  873,  704,  474
212   },
213   {
214     23411,15604,13529,11601,10683, 8958, 7840, 6142,
215     15604,11901,10718, 9108, 8290, 6961, 6023, 4487,
216     13529,10718, 9961, 8527, 7945, 6689, 5742, 4333,
217     11601, 9108, 8527, 7414, 7084, 5923, 5175, 3743,
218     10683, 8290, 7945, 7084, 6771, 5754, 4793, 3504,
219      8958, 6961, 6689, 5923, 5754, 4679, 3936, 2989,
220      7840, 6023, 5742, 5175, 4793, 3936, 3522, 2558,
221      6142, 4487, 4333, 3743, 3504, 2989, 2558, 1829
222   }
223 };
224
225 /*The fraction of the squared magnitude of the residuals in each color channel
226    relative to the total, scaled by 2**16, for each pixel format.
227   These values were measured after motion-compensated prediction, before
228    quantization, over a large set of test video encoded at all possible rates.
229   TODO: These values are only from INTER frames; it should be re-measured for
230    INTRA frames.*/
231 static const ogg_uint16_t OC_PCD[4][3]={
232   {59926, 3038, 2572},
233   {55201, 5597, 4738},
234   {55201, 5597, 4738},
235   {47682, 9669, 8185}
236 };
237
238
239 /*Compute an "average" quantizer for each qi level.
240   We do one for INTER and one for INTRA, since their behavior is very
241    different, but average across chroma channels.
242   The basic approach is to compute a harmonic average of the squared quantizer,
243    weighted by the expected squared magnitude of the DCT coefficients.
244   Under the (not quite true) assumption that DCT coefficients are
245    Laplacian-distributed, this preserves the product Q*lambda, where
246    lambda=sqrt(2/sigma**2) is the Laplacian distribution parameter (not to be
247    confused with the lambda used in R-D optimization throughout most of the
248    rest of the code).
249   The value Q*lambda completely determines the entropy of the coefficients.*/
250 void oc_enquant_qavg_init(ogg_int64_t _log_qavg[2][64],
251  ogg_uint16_t *_dequant[64][3][2],int _pixel_fmt){
252   int qi;
253   int pli;
254   int qti;
255   int ci;
256   for(qti=0;qti<2;qti++)for(qi=0;qi<64;qi++){
257     ogg_int64_t q2;
258     q2=0;
259     for(pli=0;pli<3;pli++){
260       ogg_uint32_t qp;
261       qp=0;
262       for(ci=0;ci<64;ci++){
263         unsigned rq;
264         unsigned qd;
265         qd=_dequant[qi][pli][qti][OC_IZIG_ZAG[ci]];
266         rq=(OC_RPSD[qti][ci]+(qd>>1))/qd;
267         qp+=rq*(ogg_uint32_t)rq;
268       }
269       q2+=OC_PCD[_pixel_fmt][pli]*(ogg_int64_t)qp;
270     }
271     /*qavg=1.0/sqrt(q2).*/
272     _log_qavg[qti][qi]=OC_Q57(48)-oc_blog64(q2)>>1;
273   }
274 }