Coverage Report

Created: 2025-07-11 06:50

/src/libtheora/lib/state.c
Line
Count
Source (jump to first uncovered line)
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,2025           *
9
 * by the Xiph.Org Foundation and contributors                      *
10
 * https://www.xiph.org/                                            *
11
 *                                                                  *
12
 ********************************************************************
13
14
  function:
15
16
 ********************************************************************/
17
18
#include <stdlib.h>
19
#include <string.h>
20
#include "state.h"
21
#if defined(OC_DUMP_IMAGES)
22
# include <stdio.h>
23
# include "png.h"
24
# include "zlib.h"
25
#endif
26
27
/*The function used to fill in the chroma plane motion vectors for a macro
28
   block when 4 different motion vectors are specified in the luma plane.
29
  This version is for use with chroma decimated in the X and Y directions
30
   (4:2:0).
31
  _cbmvs: The chroma block-level motion vectors to fill in.
32
  _lbmvs: The luma block-level motion vectors.*/
33
123k
static void oc_set_chroma_mvs00(oc_mv _cbmvs[4],const oc_mv _lbmvs[4]){
34
123k
  int dx;
35
123k
  int dy;
36
123k
  dx=OC_MV_X(_lbmvs[0])+OC_MV_X(_lbmvs[1])
37
123k
   +OC_MV_X(_lbmvs[2])+OC_MV_X(_lbmvs[3]);
38
123k
  dy=OC_MV_Y(_lbmvs[0])+OC_MV_Y(_lbmvs[1])
39
123k
   +OC_MV_Y(_lbmvs[2])+OC_MV_Y(_lbmvs[3]);
40
123k
  _cbmvs[0]=OC_MV(OC_DIV_ROUND_POW2(dx,2,2),OC_DIV_ROUND_POW2(dy,2,2));
41
123k
}
42
43
/*The function used to fill in the chroma plane motion vectors for a macro
44
   block when 4 different motion vectors are specified in the luma plane.
45
  This version is for use with chroma decimated in the Y direction.
46
  _cbmvs: The chroma block-level motion vectors to fill in.
47
  _lbmvs: The luma block-level motion vectors.*/
48
0
static void oc_set_chroma_mvs01(oc_mv _cbmvs[4],const oc_mv _lbmvs[4]){
49
0
  int dx;
50
0
  int dy;
51
0
  dx=OC_MV_X(_lbmvs[0])+OC_MV_X(_lbmvs[2]);
52
0
  dy=OC_MV_Y(_lbmvs[0])+OC_MV_Y(_lbmvs[2]);
53
0
  _cbmvs[0]=OC_MV(OC_DIV_ROUND_POW2(dx,1,1),OC_DIV_ROUND_POW2(dy,1,1));
54
0
  dx=OC_MV_X(_lbmvs[1])+OC_MV_X(_lbmvs[3]);
55
0
  dy=OC_MV_Y(_lbmvs[1])+OC_MV_Y(_lbmvs[3]);
56
0
  _cbmvs[1]=OC_MV(OC_DIV_ROUND_POW2(dx,1,1),OC_DIV_ROUND_POW2(dy,1,1));
57
0
}
58
59
/*The function used to fill in the chroma plane motion vectors for a macro
60
   block when 4 different motion vectors are specified in the luma plane.
61
  This version is for use with chroma decimated in the X direction (4:2:2).
62
  _cbmvs: The chroma block-level motion vectors to fill in.
63
  _lbmvs: The luma block-level motion vectors.*/
64
138k
static void oc_set_chroma_mvs10(oc_mv _cbmvs[4],const oc_mv _lbmvs[4]){
65
138k
  int dx;
66
138k
  int dy;
67
138k
  dx=OC_MV_X(_lbmvs[0])+OC_MV_X(_lbmvs[1]);
68
138k
  dy=OC_MV_Y(_lbmvs[0])+OC_MV_Y(_lbmvs[1]);
69
138k
  _cbmvs[0]=OC_MV(OC_DIV_ROUND_POW2(dx,1,1),OC_DIV_ROUND_POW2(dy,1,1));
70
138k
  dx=OC_MV_X(_lbmvs[2])+OC_MV_X(_lbmvs[3]);
71
138k
  dy=OC_MV_Y(_lbmvs[2])+OC_MV_Y(_lbmvs[3]);
72
138k
  _cbmvs[2]=OC_MV(OC_DIV_ROUND_POW2(dx,1,1),OC_DIV_ROUND_POW2(dy,1,1));
73
138k
}
74
75
/*The function used to fill in the chroma plane motion vectors for a macro
76
   block when 4 different motion vectors are specified in the luma plane.
77
  This version is for use with no chroma decimation (4:4:4).
78
  _cbmvs: The chroma block-level motion vectors to fill in.
79
  _lmbmv: The luma macro-block level motion vector to fill in for use in
80
           prediction.
81
  _lbmvs: The luma block-level motion vectors.*/
82
124k
static void oc_set_chroma_mvs11(oc_mv _cbmvs[4],const oc_mv _lbmvs[4]){
83
124k
  _cbmvs[0]=_lbmvs[0];
84
124k
  _cbmvs[1]=_lbmvs[1];
85
124k
  _cbmvs[2]=_lbmvs[2];
86
124k
  _cbmvs[3]=_lbmvs[3];
87
124k
}
88
89
/*A table of functions used to fill in the chroma plane motion vectors for a
90
   macro block when 4 different motion vectors are specified in the luma
91
   plane.*/
92
const oc_set_chroma_mvs_func OC_SET_CHROMA_MVS_TABLE[TH_PF_NFORMATS]={
93
  (oc_set_chroma_mvs_func)oc_set_chroma_mvs00,
94
  (oc_set_chroma_mvs_func)oc_set_chroma_mvs01,
95
  (oc_set_chroma_mvs_func)oc_set_chroma_mvs10,
96
  (oc_set_chroma_mvs_func)oc_set_chroma_mvs11
97
};
98
99
100
101
/*Returns the fragment index of the top-left block in a macro block.
102
  This can be used to test whether or not the whole macro block is valid.
103
  _sb_map: The super block map.
104
  _quadi:  The quadrant number.
105
  Return: The index of the fragment of the upper left block in the macro
106
   block, or -1 if the block lies outside the coded frame.*/
107
3.10M
static ptrdiff_t oc_sb_quad_top_left_frag(oc_sb_map_quad _sb_map[4],int _quadi){
108
  /*It so happens that under the Hilbert curve ordering described below, the
109
     upper-left block in each macro block is at index 0, except in macro block
110
     3, where it is at index 2.*/
111
3.10M
  return _sb_map[_quadi][_quadi&_quadi<<1];
112
3.10M
}
113
114
/*Fills in the mapping from block positions to fragment numbers for a single
115
   color plane.
116
  This function also fills in the "valid" flag of each quadrant in the super
117
   block flags.
118
  _sb_maps:  The array of super block maps for the color plane.
119
  _sb_flags: The array of super block flags for the color plane.
120
  _frag0:    The index of the first fragment in the plane.
121
  _hfrags:   The number of horizontal fragments in a coded frame.
122
  _vfrags:   The number of vertical fragments in a coded frame.*/
123
static void oc_sb_create_plane_mapping(oc_sb_map _sb_maps[],
124
2.97k
 oc_sb_flags _sb_flags[],ptrdiff_t _frag0,int _hfrags,int _vfrags){
125
  /*Contains the (macro_block,block) indices for a 4x4 grid of
126
     fragments.
127
    The pattern is a 4x4 Hilbert space-filling curve.
128
    A Hilbert curve has the nice property that as the curve grows larger, its
129
     fractal dimension approaches 2.
130
    The intuition is that nearby blocks in the curve are also close spatially,
131
     with the previous element always an immediate neighbor, so that runs of
132
     blocks should be well correlated.*/
133
2.97k
  static const int SB_MAP[4][4][2]={
134
2.97k
    {{0,0},{0,1},{3,2},{3,3}},
135
2.97k
    {{0,3},{0,2},{3,1},{3,0}},
136
2.97k
    {{1,0},{1,3},{2,0},{2,3}},
137
2.97k
    {{1,1},{1,2},{2,1},{2,2}}
138
2.97k
  };
139
2.97k
  ptrdiff_t  yfrag;
140
2.97k
  unsigned   sbi;
141
2.97k
  int        y;
142
2.97k
  sbi=0;
143
2.97k
  yfrag=_frag0;
144
47.9k
  for(y=0;;y+=4){
145
47.9k
    int imax;
146
47.9k
    int x;
147
    /*Figure out how many columns of blocks in this super block lie within the
148
       image.*/
149
47.9k
    imax=_vfrags-y;
150
47.9k
    if(imax>4)imax=4;
151
5.94k
    else if(imax<=0)break;
152
822k
    for(x=0;;x+=4,sbi++){
153
822k
      ptrdiff_t xfrag;
154
822k
      int       jmax;
155
822k
      int       quadi;
156
822k
      int       i;
157
      /*Figure out how many rows of blocks in this super block lie within the
158
         image.*/
159
822k
      jmax=_hfrags-x;
160
822k
      if(jmax>4)jmax=4;
161
89.8k
      else if(jmax<=0)break;
162
      /*By default, set all fragment indices to -1.*/
163
777k
      memset(_sb_maps[sbi],0xFF,sizeof(_sb_maps[sbi]));
164
      /*Fill in the fragment map for this super block.*/
165
777k
      xfrag=yfrag+x;
166
3.84M
      for(i=0;i<imax;i++){
167
3.06M
        int j;
168
15.0M
        for(j=0;j<jmax;j++){
169
12.0M
          _sb_maps[sbi][SB_MAP[i][j][0]][SB_MAP[i][j][1]]=xfrag+j;
170
12.0M
        }
171
3.06M
        xfrag+=_hfrags;
172
3.06M
      }
173
      /*Mark which quadrants of this super block lie within the image.*/
174
3.88M
      for(quadi=0;quadi<4;quadi++){
175
3.10M
        _sb_flags[sbi].quad_valid|=
176
3.10M
         (oc_sb_quad_top_left_frag(_sb_maps[sbi],quadi)>=0)<<quadi;
177
3.10M
      }
178
777k
    }
179
44.9k
    yfrag+=_hfrags<<2;
180
44.9k
  }
181
2.97k
}
182
183
/*Fills in the Y plane fragment map for a macro block given the fragment
184
   coordinates of its upper-left hand corner.
185
  _mb_map:    The macro block map to fill.
186
  _fplane: The description of the Y plane.
187
  _xfrag0: The X location of the upper-left hand fragment in the luma plane.
188
  _yfrag0: The Y location of the upper-left hand fragment in the luma plane.*/
189
static void oc_mb_fill_ymapping(oc_mb_map_plane _mb_map[3],
190
1.44M
 const oc_fragment_plane *_fplane,int _xfrag0,int _yfrag0){
191
1.44M
  int i;
192
1.44M
  int j;
193
8.68M
  for(i=0;i<2;i++)for(j=0;j<2;j++){
194
5.78M
    _mb_map[0][i<<1|j]=(_yfrag0+i)*(ptrdiff_t)_fplane->nhfrags+_xfrag0+j;
195
5.78M
  }
196
1.44M
}
197
198
/*Fills in the chroma plane fragment maps for a macro block.
199
  This version is for use with chroma decimated in the X and Y directions
200
   (4:2:0).
201
  _mb_map:  The macro block map to fill.
202
  _fplanes: The descriptions of the fragment planes.
203
  _xfrag0:  The X location of the upper-left hand fragment in the luma plane.
204
  _yfrag0:  The Y location of the upper-left hand fragment in the luma plane.*/
205
static void oc_mb_fill_cmapping00(oc_mb_map_plane _mb_map[3],
206
612k
 const oc_fragment_plane _fplanes[3],int _xfrag0,int _yfrag0){
207
612k
  ptrdiff_t fragi;
208
612k
  _xfrag0>>=1;
209
612k
  _yfrag0>>=1;
210
612k
  fragi=_yfrag0*(ptrdiff_t)_fplanes[1].nhfrags+_xfrag0;
211
612k
  _mb_map[1][0]=fragi+_fplanes[1].froffset;
212
612k
  _mb_map[2][0]=fragi+_fplanes[2].froffset;
213
612k
}
214
215
/*Fills in the chroma plane fragment maps for a macro block.
216
  This version is for use with chroma decimated in the Y direction.
217
  _mb_map:  The macro block map to fill.
218
  _fplanes: The descriptions of the fragment planes.
219
  _xfrag0:  The X location of the upper-left hand fragment in the luma plane.
220
  _yfrag0:  The Y location of the upper-left hand fragment in the luma plane.*/
221
static void oc_mb_fill_cmapping01(oc_mb_map_plane _mb_map[3],
222
0
 const oc_fragment_plane _fplanes[3],int _xfrag0,int _yfrag0){
223
0
  ptrdiff_t fragi;
224
0
  int       j;
225
0
  _yfrag0>>=1;
226
0
  fragi=_yfrag0*(ptrdiff_t)_fplanes[1].nhfrags+_xfrag0;
227
0
  for(j=0;j<2;j++){
228
0
    _mb_map[1][j]=fragi+_fplanes[1].froffset;
229
0
    _mb_map[2][j]=fragi+_fplanes[2].froffset;
230
0
    fragi++;
231
0
  }
232
0
}
233
234
/*Fills in the chroma plane fragment maps for a macro block.
235
  This version is for use with chroma decimated in the X direction (4:2:2).
236
  _mb_map:  The macro block map to fill.
237
  _fplanes: The descriptions of the fragment planes.
238
  _xfrag0:  The X location of the upper-left hand fragment in the luma plane.
239
  _yfrag0:  The Y location of the upper-left hand fragment in the luma plane.*/
240
static void oc_mb_fill_cmapping10(oc_mb_map_plane _mb_map[3],
241
419k
 const oc_fragment_plane _fplanes[3],int _xfrag0,int _yfrag0){
242
419k
  ptrdiff_t fragi;
243
419k
  int       i;
244
419k
  _xfrag0>>=1;
245
419k
  fragi=_yfrag0*(ptrdiff_t)_fplanes[1].nhfrags+_xfrag0;
246
1.25M
  for(i=0;i<2;i++){
247
838k
    _mb_map[1][i<<1]=fragi+_fplanes[1].froffset;
248
838k
    _mb_map[2][i<<1]=fragi+_fplanes[2].froffset;
249
838k
    fragi+=_fplanes[1].nhfrags;
250
838k
  }
251
419k
}
252
253
/*Fills in the chroma plane fragment maps for a macro block.
254
  This version is for use with no chroma decimation (4:4:4).
255
  This uses the already filled-in luma plane values.
256
  _mb_map:  The macro block map to fill.
257
  _fplanes: The descriptions of the fragment planes.
258
  _xfrag0:  The X location of the upper-left hand fragment in the luma plane.
259
  _yfrag0:  The Y location of the upper-left hand fragment in the luma plane.*/
260
static void oc_mb_fill_cmapping11(oc_mb_map_plane _mb_map[3],
261
415k
 const oc_fragment_plane _fplanes[3],int _xfrag0,int _yfrag0){
262
415k
  int k;
263
415k
  (void)_xfrag0;
264
415k
  (void)_yfrag0;
265
2.07M
  for(k=0;k<4;k++){
266
1.66M
    _mb_map[1][k]=_mb_map[0][k]+_fplanes[1].froffset;
267
1.66M
    _mb_map[2][k]=_mb_map[0][k]+_fplanes[2].froffset;
268
1.66M
  }
269
415k
}
270
271
/*The function type used to fill in the chroma plane fragment maps for a
272
   macro block.
273
  _mb_map:  The macro block map to fill.
274
  _fplanes: The descriptions of the fragment planes.
275
  _xfrag0:  The X location of the upper-left hand fragment in the luma plane.
276
  _yfrag0:  The Y location of the upper-left hand fragment in the luma plane.*/
277
typedef void (*oc_mb_fill_cmapping_func)(oc_mb_map_plane _mb_map[3],
278
 const oc_fragment_plane _fplanes[3],int _xfrag0,int _yfrag0);
279
280
/*A table of functions used to fill in the chroma plane fragment maps for a
281
   macro block for each type of chrominance decimation.*/
282
static const oc_mb_fill_cmapping_func OC_MB_FILL_CMAPPING_TABLE[4]={
283
  oc_mb_fill_cmapping00,
284
  oc_mb_fill_cmapping01,
285
  oc_mb_fill_cmapping10,
286
  oc_mb_fill_cmapping11
287
};
288
289
/*Fills in the mapping from macro blocks to their corresponding fragment
290
   numbers in each plane.
291
  _mb_maps:   The list of macro block maps.
292
  _mb_modes:  The list of macro block modes; macro blocks completely outside
293
               the coded region are marked invalid.
294
  _fplanes:   The descriptions of the fragment planes.
295
  _pixel_fmt: The chroma decimation type.*/
296
static void oc_mb_create_mapping(oc_mb_map _mb_maps[],
297
990
 signed char _mb_modes[],const oc_fragment_plane _fplanes[3],int _pixel_fmt){
298
990
  oc_mb_fill_cmapping_func  mb_fill_cmapping;
299
990
  unsigned                  sbi;
300
990
  int                       y;
301
990
  mb_fill_cmapping=OC_MB_FILL_CMAPPING_TABLE[_pixel_fmt];
302
  /*Loop through the luma plane super blocks.*/
303
18.6k
  for(sbi=y=0;y<_fplanes[0].nvfrags;y+=4){
304
17.6k
    int x;
305
389k
    for(x=0;x<_fplanes[0].nhfrags;x+=4,sbi++){
306
371k
      int ymb;
307
      /*Loop through the macro blocks in each super block in display order.*/
308
1.11M
      for(ymb=0;ymb<2;ymb++){
309
743k
        int xmb;
310
2.22M
        for(xmb=0;xmb<2;xmb++){
311
1.48M
          unsigned mbi;
312
1.48M
          int      mbx;
313
1.48M
          int      mby;
314
1.48M
          mbi=sbi<<2|OC_MB_MAP[ymb][xmb];
315
1.48M
          mbx=x|xmb<<1;
316
1.48M
          mby=y|ymb<<1;
317
          /*Initialize fragment indices to -1.*/
318
1.48M
          memset(_mb_maps[mbi],0xFF,sizeof(_mb_maps[mbi]));
319
          /*Make sure this macro block is within the encoded region.*/
320
1.48M
          if(mbx>=_fplanes[0].nhfrags||mby>=_fplanes[0].nvfrags){
321
39.0k
            _mb_modes[mbi]=OC_MODE_INVALID;
322
39.0k
            continue;
323
39.0k
          }
324
          /*Fill in the fragment indices for the luma plane.*/
325
1.44M
          oc_mb_fill_ymapping(_mb_maps[mbi],_fplanes,mbx,mby);
326
          /*Fill in the fragment indices for the chroma planes.*/
327
1.44M
          (*mb_fill_cmapping)(_mb_maps[mbi],_fplanes,mbx,mby);
328
1.44M
        }
329
743k
      }
330
371k
    }
331
17.6k
  }
332
990
}
333
334
/*Marks the fragments which fall all or partially outside the displayable
335
   region of the frame.
336
  _state: The Theora state containing the fragments to be marked.*/
337
990
static void oc_state_border_init(oc_theora_state *_state){
338
990
  oc_fragment       *frag;
339
990
  oc_fragment       *yfrag_end;
340
990
  oc_fragment       *xfrag_end;
341
990
  oc_fragment_plane *fplane;
342
990
  int                crop_x0;
343
990
  int                crop_y0;
344
990
  int                crop_xf;
345
990
  int                crop_yf;
346
990
  int                pli;
347
990
  int                y;
348
990
  int                x;
349
  /*The method we use here is slow, but the code is dead simple and handles
350
     all the special cases easily.
351
    We only ever need to do it once.*/
352
  /*Loop through the fragments, marking those completely outside the
353
     displayable region and constructing a border mask for those that straddle
354
     the border.*/
355
990
  _state->nborders=0;
356
990
  yfrag_end=frag=_state->frags;
357
3.96k
  for(pli=0;pli<3;pli++){
358
2.97k
    fplane=_state->fplanes+pli;
359
    /*Set up the cropping rectangle for this plane.*/
360
2.97k
    crop_x0=_state->info.pic_x;
361
2.97k
    crop_xf=_state->info.pic_x+_state->info.pic_width;
362
2.97k
    crop_y0=_state->info.pic_y;
363
2.97k
    crop_yf=_state->info.pic_y+_state->info.pic_height;
364
2.97k
    if(pli>0){
365
1.98k
      if(!(_state->info.pixel_fmt&1)){
366
1.56k
        crop_x0=crop_x0>>1;
367
1.56k
        crop_xf=crop_xf+1>>1;
368
1.56k
      }
369
1.98k
      if(!(_state->info.pixel_fmt&2)){
370
1.06k
        crop_y0=crop_y0>>1;
371
1.06k
        crop_yf=crop_yf+1>>1;
372
1.06k
      }
373
1.98k
    }
374
2.97k
    y=0;
375
178k
    for(yfrag_end+=fplane->nfrags;frag<yfrag_end;y+=8){
376
175k
      x=0;
377
12.1M
      for(xfrag_end=frag+fplane->nhfrags;frag<xfrag_end;frag++,x+=8){
378
        /*First check to see if this fragment is completely outside the
379
           displayable region.*/
380
        /*Note the special checks for an empty cropping rectangle.
381
          This guarantees that if we count a fragment as straddling the
382
           border below, at least one pixel in the fragment will be inside
383
           the displayable region.*/
384
12.0M
        if(x+8<=crop_x0||crop_xf<=x||y+8<=crop_y0||crop_yf<=y||
385
12.0M
         crop_x0>=crop_xf||crop_y0>=crop_yf){
386
11.3M
          frag->invalid=1;
387
11.3M
        }
388
        /*Otherwise, check to see if it straddles the border.*/
389
644k
        else if(x<crop_x0&&crop_x0<x+8||x<crop_xf&&crop_xf<x+8||
390
644k
         y<crop_y0&&crop_y0<y+8||y<crop_yf&&crop_yf<y+8){
391
86.7k
          ogg_uint64_t mask;
392
86.7k
          int         npixels;
393
86.7k
          int         i;
394
86.7k
          mask=npixels=0;
395
780k
          for(i=0;i<8;i++){
396
694k
            int j;
397
6.24M
            for(j=0;j<8;j++){
398
5.55M
              if(x+j>=crop_x0&&x+j<crop_xf&&y+i>=crop_y0&&y+i<crop_yf){
399
2.46M
                mask|=(ogg_uint64_t)1<<(i<<3|j);
400
2.46M
                npixels++;
401
2.46M
              }
402
5.55M
            }
403
694k
          }
404
          /*Search the fragment array for border info with the same pattern.
405
            In general, there will be at most 8 different patterns (per
406
             plane).*/
407
442k
          for(i=0;;i++){
408
442k
            if(i>=_state->nborders){
409
4.52k
              _state->nborders++;
410
4.52k
              _state->borders[i].mask=mask;
411
4.52k
              _state->borders[i].npixels=npixels;
412
4.52k
            }
413
437k
            else if(_state->borders[i].mask!=mask)continue;
414
86.7k
            frag->borderi=i;
415
86.7k
            break;
416
442k
          }
417
86.7k
        }
418
557k
        else frag->borderi=-1;
419
12.0M
      }
420
175k
    }
421
2.97k
  }
422
990
}
423
424
990
static int oc_state_frarray_init(oc_theora_state *_state){
425
990
  int       yhfrags;
426
990
  int       yvfrags;
427
990
  int       chfrags;
428
990
  int       cvfrags;
429
990
  ptrdiff_t yfrags;
430
990
  ptrdiff_t cfrags;
431
990
  ptrdiff_t nfrags;
432
990
  unsigned  yhsbs;
433
990
  unsigned  yvsbs;
434
990
  unsigned  chsbs;
435
990
  unsigned  cvsbs;
436
990
  unsigned  ysbs;
437
990
  unsigned  csbs;
438
990
  unsigned  nsbs;
439
990
  size_t    nmbs;
440
990
  int       hdec;
441
990
  int       vdec;
442
990
  int       pli;
443
  /*Figure out the number of fragments in each plane.*/
444
  /*These parameters have already been validated to be multiples of 16.*/
445
990
  yhfrags=_state->info.frame_width>>3;
446
990
  yvfrags=_state->info.frame_height>>3;
447
990
  hdec=!(_state->info.pixel_fmt&1);
448
990
  vdec=!(_state->info.pixel_fmt&2);
449
990
  chfrags=yhfrags+hdec>>hdec;
450
990
  cvfrags=yvfrags+vdec>>vdec;
451
990
  yfrags=yhfrags*(ptrdiff_t)yvfrags;
452
990
  cfrags=chfrags*(ptrdiff_t)cvfrags;
453
990
  nfrags=yfrags+2*cfrags;
454
  /*Figure out the number of super blocks in each plane.*/
455
990
  yhsbs=yhfrags+3>>2;
456
990
  yvsbs=yvfrags+3>>2;
457
990
  chsbs=chfrags+3>>2;
458
990
  cvsbs=cvfrags+3>>2;
459
990
  ysbs=yhsbs*yvsbs;
460
990
  csbs=chsbs*cvsbs;
461
990
  nsbs=ysbs+2*csbs;
462
990
  nmbs=(size_t)ysbs<<2;
463
  /*Check for overflow.
464
    We support the ridiculous upper limits of the specification (1048560 by
465
     1048560, or 3 TB frames) if the target architecture has 64-bit pointers,
466
     but for those with 32-bit pointers (or smaller!) we have to check.
467
    If the caller wants to prevent denial-of-service by imposing a more
468
     reasonable upper limit on the size of attempted allocations, they must do
469
     so themselves; we have no platform independent way to determine how much
470
     system memory there is nor an application-independent way to decide what a
471
     "reasonable" allocation is.*/
472
990
  if(yfrags/yhfrags!=yvfrags||2*cfrags<cfrags||nfrags<yfrags||
473
990
   ysbs/yhsbs!=yvsbs||2*csbs<csbs||nsbs<ysbs||nmbs>>2!=ysbs){
474
0
    return TH_EIMPL;
475
0
  }
476
  /*Initialize the fragment array.*/
477
990
  _state->fplanes[0].nhfrags=yhfrags;
478
990
  _state->fplanes[0].nvfrags=yvfrags;
479
990
  _state->fplanes[0].froffset=0;
480
990
  _state->fplanes[0].nfrags=yfrags;
481
990
  _state->fplanes[0].nhsbs=yhsbs;
482
990
  _state->fplanes[0].nvsbs=yvsbs;
483
990
  _state->fplanes[0].sboffset=0;
484
990
  _state->fplanes[0].nsbs=ysbs;
485
990
  _state->fplanes[1].nhfrags=_state->fplanes[2].nhfrags=chfrags;
486
990
  _state->fplanes[1].nvfrags=_state->fplanes[2].nvfrags=cvfrags;
487
990
  _state->fplanes[1].froffset=yfrags;
488
990
  _state->fplanes[2].froffset=yfrags+cfrags;
489
990
  _state->fplanes[1].nfrags=_state->fplanes[2].nfrags=cfrags;
490
990
  _state->fplanes[1].nhsbs=_state->fplanes[2].nhsbs=chsbs;
491
990
  _state->fplanes[1].nvsbs=_state->fplanes[2].nvsbs=cvsbs;
492
990
  _state->fplanes[1].sboffset=ysbs;
493
990
  _state->fplanes[2].sboffset=ysbs+csbs;
494
990
  _state->fplanes[1].nsbs=_state->fplanes[2].nsbs=csbs;
495
990
  _state->nfrags=nfrags;
496
990
  _state->frags=_ogg_calloc(nfrags,sizeof(*_state->frags));
497
990
  _state->frag_mvs=_ogg_malloc(nfrags*sizeof(*_state->frag_mvs));
498
990
  _state->nsbs=nsbs;
499
990
  _state->sb_maps=_ogg_malloc(nsbs*sizeof(*_state->sb_maps));
500
990
  _state->sb_flags=_ogg_calloc(nsbs,sizeof(*_state->sb_flags));
501
990
  _state->nhmbs=yhsbs<<1;
502
990
  _state->nvmbs=yvsbs<<1;
503
990
  _state->nmbs=nmbs;
504
990
  _state->mb_maps=_ogg_calloc(nmbs,sizeof(*_state->mb_maps));
505
990
  _state->mb_modes=_ogg_calloc(nmbs,sizeof(*_state->mb_modes));
506
990
  _state->coded_fragis=_ogg_malloc(nfrags*sizeof(*_state->coded_fragis));
507
990
  if(_state->frags==NULL||_state->frag_mvs==NULL||_state->sb_maps==NULL||
508
990
   _state->sb_flags==NULL||_state->mb_maps==NULL||_state->mb_modes==NULL||
509
990
   _state->coded_fragis==NULL){
510
0
    return TH_EFAULT;
511
0
  }
512
  /*Create the mapping from super blocks to fragments.*/
513
3.96k
  for(pli=0;pli<3;pli++){
514
2.97k
    oc_fragment_plane *fplane;
515
2.97k
    fplane=_state->fplanes+pli;
516
2.97k
    oc_sb_create_plane_mapping(_state->sb_maps+fplane->sboffset,
517
2.97k
     _state->sb_flags+fplane->sboffset,fplane->froffset,
518
2.97k
     fplane->nhfrags,fplane->nvfrags);
519
2.97k
  }
520
  /*Create the mapping from macro blocks to fragments.*/
521
990
  oc_mb_create_mapping(_state->mb_maps,_state->mb_modes,
522
990
   _state->fplanes,_state->info.pixel_fmt);
523
  /*Initialize the invalid and borderi fields of each fragment.*/
524
990
  oc_state_border_init(_state);
525
990
  return 0;
526
990
}
527
528
990
static void oc_state_frarray_clear(oc_theora_state *_state){
529
990
  _ogg_free(_state->coded_fragis);
530
990
  _ogg_free(_state->mb_modes);
531
990
  _ogg_free(_state->mb_maps);
532
990
  _ogg_free(_state->sb_flags);
533
990
  _ogg_free(_state->sb_maps);
534
990
  _ogg_free(_state->frag_mvs);
535
990
  _ogg_free(_state->frags);
536
990
}
537
538
539
/*Initializes the buffers used for reconstructed frames.
540
  These buffers are padded with 16 extra pixels on each side, to allow
541
   unrestricted motion vectors without special casing the boundary.
542
  If chroma is decimated in either direction, the padding is reduced by a
543
   factor of 2 on the appropriate sides.
544
  _nrefs: The number of reference buffers to init; must be in the range 3...6.*/
545
990
static int oc_state_ref_bufs_init(oc_theora_state *_state,int _nrefs){
546
990
  th_info       *info;
547
990
  unsigned char *ref_frame_data;
548
990
  size_t         ref_frame_data_sz;
549
990
  size_t         ref_frame_sz;
550
990
  size_t         yplane_sz;
551
990
  size_t         cplane_sz;
552
990
  int            yhstride;
553
990
  int            yheight;
554
990
  int            chstride;
555
990
  int            cheight;
556
990
  ptrdiff_t      align;
557
990
  ptrdiff_t      yoffset;
558
990
  ptrdiff_t      coffset;
559
990
  ptrdiff_t     *frag_buf_offs;
560
990
  ptrdiff_t      fragi;
561
990
  int            hdec;
562
990
  int            vdec;
563
990
  int            rfi;
564
990
  int            pli;
565
990
  if(_nrefs<3||_nrefs>6)return TH_EINVAL;
566
990
  info=&_state->info;
567
  /*Compute the image buffer parameters for each plane.*/
568
990
  hdec=!(info->pixel_fmt&1);
569
990
  vdec=!(info->pixel_fmt&2);
570
990
  yhstride=info->frame_width+2*OC_UMV_PADDING;
571
990
  yheight=info->frame_height+2*OC_UMV_PADDING;
572
  /*Require 16-byte aligned rows in the chroma planes.*/
573
990
  chstride=(yhstride>>hdec)+15&~15;
574
990
  cheight=yheight>>vdec;
575
990
  yplane_sz=yhstride*(size_t)yheight;
576
990
  cplane_sz=chstride*(size_t)cheight;
577
990
  yoffset=OC_UMV_PADDING+OC_UMV_PADDING*(ptrdiff_t)yhstride;
578
990
  coffset=(OC_UMV_PADDING>>hdec)+(OC_UMV_PADDING>>vdec)*(ptrdiff_t)chstride;
579
  /*Although we guarantee the rows of the chroma planes are a multiple of 16
580
     bytes, the initial padding on the first row may only be 8 bytes.
581
    Compute the offset needed to the actual image data to a multiple of 16.*/
582
990
  align=-coffset&15;
583
990
  ref_frame_sz=yplane_sz+2*cplane_sz+16;
584
990
  ref_frame_data_sz=_nrefs*ref_frame_sz;
585
  /*Check for overflow.
586
    The same caveats apply as for oc_state_frarray_init().*/
587
990
  if(yplane_sz/yhstride!=(size_t)yheight||2*cplane_sz+16<cplane_sz||
588
990
   ref_frame_sz<yplane_sz||ref_frame_data_sz/_nrefs!=ref_frame_sz){
589
0
    return TH_EIMPL;
590
0
  }
591
990
  ref_frame_data=oc_aligned_malloc(ref_frame_data_sz,16);
592
990
  frag_buf_offs=_state->frag_buf_offs=
593
990
   _ogg_malloc(_state->nfrags*sizeof(*frag_buf_offs));
594
990
  if(ref_frame_data==NULL||frag_buf_offs==NULL){
595
0
    _ogg_free(frag_buf_offs);
596
0
    oc_aligned_free(ref_frame_data);
597
0
    return TH_EFAULT;
598
0
  }
599
  /*Set up the width, height and stride for the image buffers.*/
600
990
  _state->ref_frame_bufs[0][0].width=info->frame_width;
601
990
  _state->ref_frame_bufs[0][0].height=info->frame_height;
602
990
  _state->ref_frame_bufs[0][0].stride=yhstride;
603
990
  _state->ref_frame_bufs[0][1].width=_state->ref_frame_bufs[0][2].width=
604
990
   info->frame_width>>hdec;
605
990
  _state->ref_frame_bufs[0][1].height=_state->ref_frame_bufs[0][2].height=
606
990
   info->frame_height>>vdec;
607
990
  _state->ref_frame_bufs[0][1].stride=_state->ref_frame_bufs[0][2].stride=
608
990
   chstride;
609
2.97k
  for(rfi=1;rfi<_nrefs;rfi++){
610
1.98k
    memcpy(_state->ref_frame_bufs[rfi],_state->ref_frame_bufs[0],
611
1.98k
     sizeof(_state->ref_frame_bufs[0]));
612
1.98k
  }
613
990
  _state->ref_frame_handle=ref_frame_data;
614
  /*Set up the data pointers for the image buffers.*/
615
3.96k
  for(rfi=0;rfi<_nrefs;rfi++){
616
2.97k
    _state->ref_frame_bufs[rfi][0].data=ref_frame_data+yoffset;
617
2.97k
    ref_frame_data+=yplane_sz+align;
618
2.97k
    _state->ref_frame_bufs[rfi][1].data=ref_frame_data+coffset;
619
2.97k
    ref_frame_data+=cplane_sz;
620
2.97k
    _state->ref_frame_bufs[rfi][2].data=ref_frame_data+coffset;
621
2.97k
    ref_frame_data+=cplane_sz+(16-align);
622
    /*Flip the buffer upside down.
623
      This allows us to decode Theora's bottom-up frames in their natural
624
       order, yet return a top-down buffer with a positive stride to the user.*/
625
2.97k
    oc_ycbcr_buffer_flip(_state->ref_frame_bufs[rfi],
626
2.97k
     _state->ref_frame_bufs[rfi]);
627
2.97k
  }
628
990
  _state->ref_ystride[0]=-yhstride;
629
990
  _state->ref_ystride[1]=_state->ref_ystride[2]=-chstride;
630
  /*Initialize the fragment buffer offsets.*/
631
990
  ref_frame_data=_state->ref_frame_bufs[0][0].data;
632
990
  fragi=0;
633
3.96k
  for(pli=0;pli<3;pli++){
634
2.97k
    th_img_plane      *iplane;
635
2.97k
    oc_fragment_plane *fplane;
636
2.97k
    unsigned char     *vpix;
637
2.97k
    ptrdiff_t          stride;
638
2.97k
    ptrdiff_t          vfragi_end;
639
2.97k
    int                nhfrags;
640
2.97k
    iplane=_state->ref_frame_bufs[0]+pli;
641
2.97k
    fplane=_state->fplanes+pli;
642
2.97k
    vpix=iplane->data;
643
2.97k
    vfragi_end=fplane->froffset+fplane->nfrags;
644
2.97k
    nhfrags=fplane->nhfrags;
645
2.97k
    stride=iplane->stride;
646
178k
    while(fragi<vfragi_end){
647
175k
      ptrdiff_t      hfragi_end;
648
175k
      unsigned char *hpix;
649
175k
      hpix=vpix;
650
12.1M
      for(hfragi_end=fragi+nhfrags;fragi<hfragi_end;fragi++){
651
12.0M
        frag_buf_offs[fragi]=hpix-ref_frame_data;
652
12.0M
        hpix+=8;
653
12.0M
      }
654
175k
      vpix+=stride*8;
655
175k
    }
656
2.97k
  }
657
  /*Initialize the reference frame pointers and indices.*/
658
990
  _state->ref_frame_idx[OC_FRAME_GOLD]=
659
990
   _state->ref_frame_idx[OC_FRAME_PREV]=
660
990
   _state->ref_frame_idx[OC_FRAME_GOLD_ORIG]=
661
990
   _state->ref_frame_idx[OC_FRAME_PREV_ORIG]=
662
990
   _state->ref_frame_idx[OC_FRAME_SELF]=
663
990
   _state->ref_frame_idx[OC_FRAME_IO]=-1;
664
990
  _state->ref_frame_data[OC_FRAME_GOLD]=
665
990
   _state->ref_frame_data[OC_FRAME_PREV]=
666
990
   _state->ref_frame_data[OC_FRAME_GOLD_ORIG]=
667
990
   _state->ref_frame_data[OC_FRAME_PREV_ORIG]=
668
990
   _state->ref_frame_data[OC_FRAME_SELF]=
669
990
   _state->ref_frame_data[OC_FRAME_IO]=NULL;
670
990
  return 0;
671
990
}
672
673
990
static void oc_state_ref_bufs_clear(oc_theora_state *_state){
674
990
  _ogg_free(_state->frag_buf_offs);
675
990
  oc_aligned_free(_state->ref_frame_handle);
676
990
}
677
678
679
990
void oc_state_accel_init_c(oc_theora_state *_state){
680
990
  _state->cpu_flags=0;
681
#if defined(OC_STATE_USE_VTABLE)
682
  _state->opt_vtable.frag_copy=oc_frag_copy_c;
683
  _state->opt_vtable.frag_copy_list=oc_frag_copy_list_c;
684
  _state->opt_vtable.frag_recon_intra=oc_frag_recon_intra_c;
685
  _state->opt_vtable.frag_recon_inter=oc_frag_recon_inter_c;
686
  _state->opt_vtable.frag_recon_inter2=oc_frag_recon_inter2_c;
687
  _state->opt_vtable.idct8x8=oc_idct8x8_c;
688
  _state->opt_vtable.state_frag_recon=oc_state_frag_recon_c;
689
  _state->opt_vtable.loop_filter_init=oc_loop_filter_init_c;
690
  _state->opt_vtable.state_loop_filter_frag_rows=
691
   oc_state_loop_filter_frag_rows_c;
692
  _state->opt_vtable.restore_fpu=oc_restore_fpu_c;
693
#endif
694
990
  _state->opt_data.dct_fzig_zag=OC_FZIG_ZAG;
695
990
}
696
697
698
997
int oc_state_init(oc_theora_state *_state,const th_info *_info,int _nrefs){
699
997
  int ret;
700
  /*First validate the parameters.*/
701
997
  if(_info==NULL)return TH_EFAULT;
702
  /*The width and height of the encoded frame must be multiples of 16.
703
    They must also, when divided by 16, fit into a 16-bit unsigned integer.
704
    The displayable frame offset coordinates must fit into an 8-bit unsigned
705
     integer.
706
    Note that the offset Y in the API is specified on the opposite side from
707
     how it is specified in the bitstream, because the Y axis is flipped in
708
     the bitstream.
709
    The displayable frame must fit inside the encoded frame.
710
    The color space must be one known by the encoder.
711
    The framerate ratio must not contain a zero value.*/
712
997
  if((_info->frame_width&0xF)||(_info->frame_height&0xF)||
713
997
   _info->frame_width<=0||_info->frame_width>=0x100000||
714
997
   _info->frame_height<=0||_info->frame_height>=0x100000||
715
997
   _info->pic_x+_info->pic_width>_info->frame_width||
716
997
   _info->pic_y+_info->pic_height>_info->frame_height||
717
997
   _info->pic_x>255||_info->frame_height-_info->pic_height-_info->pic_y>255||
718
   /*Note: the following <0 comparisons may generate spurious warnings on
719
      platforms where enums are unsigned.
720
     We could cast them to unsigned and just use the following >= comparison,
721
      but there are a number of compilers which will mis-optimize this.
722
     It's better to live with the spurious warnings.*/
723
997
   _info->colorspace<0||_info->colorspace>=TH_CS_NSPACES||
724
997
   _info->pixel_fmt<0||_info->pixel_fmt>=TH_PF_NFORMATS||
725
997
   _info->fps_numerator<1||_info->fps_denominator<1){
726
7
    return TH_EINVAL;
727
7
  }
728
990
  memset(_state,0,sizeof(*_state));
729
990
  memcpy(&_state->info,_info,sizeof(*_info));
730
  /*Invert the sense of pic_y to match Theora's right-handed coordinate
731
     system.*/
732
990
  _state->info.pic_y=_info->frame_height-_info->pic_height-_info->pic_y;
733
990
  _state->frame_type=OC_UNKWN_FRAME;
734
990
  oc_state_accel_init(_state);
735
990
  ret=oc_state_frarray_init(_state);
736
990
  if(ret>=0)ret=oc_state_ref_bufs_init(_state,_nrefs);
737
990
  if(ret<0){
738
0
    oc_state_frarray_clear(_state);
739
0
    return ret;
740
0
  }
741
  /*If the keyframe_granule_shift is out of range, use the maximum allowable
742
     value.*/
743
990
  if(_info->keyframe_granule_shift<0||_info->keyframe_granule_shift>31){
744
0
    _state->info.keyframe_granule_shift=31;
745
0
  }
746
990
  _state->keyframe_num=0;
747
990
  _state->curframe_num=-1;
748
  /*3.2.0 streams mark the frame index instead of the frame count.
749
    This was changed with stream version 3.2.1 to conform to other Ogg
750
     codecs.
751
    We add an extra bias when computing granule positions for new streams.*/
752
990
  _state->granpos_bias=TH_VERSION_CHECK(_info,3,2,1);
753
990
  return 0;
754
990
}
755
756
990
void oc_state_clear(oc_theora_state *_state){
757
990
  oc_state_ref_bufs_clear(_state);
758
990
  oc_state_frarray_clear(_state);
759
990
}
760
761
762
/*Duplicates the pixels on the border of the image plane out into the
763
   surrounding padding for use by unrestricted motion vectors.
764
  This function only adds the left and right borders, and only for the fragment
765
   rows specified.
766
  _refi: The index of the reference buffer to pad.
767
  _pli:  The color plane.
768
  _y0:   The Y coordinate of the first row to pad.
769
  _yend: The Y coordinate of the row to stop padding at.*/
770
void oc_state_borders_fill_rows(oc_theora_state *_state,int _refi,int _pli,
771
40.5k
 int _y0,int _yend){
772
40.5k
  th_img_plane  *iplane;
773
40.5k
  unsigned char *apix;
774
40.5k
  unsigned char *bpix;
775
40.5k
  unsigned char *epix;
776
40.5k
  int            stride;
777
40.5k
  int            hpadding;
778
40.5k
  hpadding=OC_UMV_PADDING>>(_pli!=0&&!(_state->info.pixel_fmt&1));
779
40.5k
  iplane=_state->ref_frame_bufs[_refi]+_pli;
780
40.5k
  stride=iplane->stride;
781
40.5k
  apix=iplane->data+_y0*(ptrdiff_t)stride;
782
40.5k
  bpix=apix+iplane->width-1;
783
40.5k
  epix=iplane->data+_yend*(ptrdiff_t)stride;
784
  /*Note the use of != instead of <, which allows the stride to be negative.*/
785
1.39M
  while(apix!=epix){
786
1.35M
    memset(apix-hpadding,apix[0],hpadding);
787
1.35M
    memset(bpix+1,bpix[0],hpadding);
788
1.35M
    apix+=stride;
789
1.35M
    bpix+=stride;
790
1.35M
  }
791
40.5k
}
792
793
/*Duplicates the pixels on the border of the image plane out into the
794
   surrounding padding for use by unrestricted motion vectors.
795
  This function only adds the top and bottom borders, and must be called after
796
   the left and right borders are added.
797
  _refi:      The index of the reference buffer to pad.
798
  _pli:       The color plane.*/
799
3.15k
void oc_state_borders_fill_caps(oc_theora_state *_state,int _refi,int _pli){
800
3.15k
  th_img_plane  *iplane;
801
3.15k
  unsigned char *apix;
802
3.15k
  unsigned char *bpix;
803
3.15k
  unsigned char *epix;
804
3.15k
  int            stride;
805
3.15k
  int            hpadding;
806
3.15k
  int            vpadding;
807
3.15k
  int            fullw;
808
3.15k
  hpadding=OC_UMV_PADDING>>(_pli!=0&&!(_state->info.pixel_fmt&1));
809
3.15k
  vpadding=OC_UMV_PADDING>>(_pli!=0&&!(_state->info.pixel_fmt&2));
810
3.15k
  iplane=_state->ref_frame_bufs[_refi]+_pli;
811
3.15k
  stride=iplane->stride;
812
3.15k
  fullw=iplane->width+(hpadding<<1);
813
3.15k
  apix=iplane->data-hpadding;
814
3.15k
  bpix=iplane->data+(iplane->height-1)*(ptrdiff_t)stride-hpadding;
815
3.15k
  epix=apix-stride*(ptrdiff_t)vpadding;
816
45.1k
  while(apix!=epix){
817
41.9k
    memcpy(apix-stride,apix,fullw);
818
41.9k
    memcpy(bpix+stride,bpix,fullw);
819
41.9k
    apix-=stride;
820
41.9k
    bpix+=stride;
821
41.9k
  }
822
3.15k
}
823
824
/*Duplicates the pixels on the border of the given reference image out into
825
   the surrounding padding for use by unrestricted motion vectors.
826
  _state: The context containing the reference buffers.
827
  _refi:  The index of the reference buffer to pad.*/
828
0
void oc_state_borders_fill(oc_theora_state *_state,int _refi){
829
0
  int pli;
830
0
  for(pli=0;pli<3;pli++){
831
0
    oc_state_borders_fill_rows(_state,_refi,pli,0,
832
0
     _state->ref_frame_bufs[_refi][pli].height);
833
0
    oc_state_borders_fill_caps(_state,_refi,pli);
834
0
  }
835
0
}
836
837
/*Determines the offsets in an image buffer to use for motion compensation.
838
  _state:   The Theora state the offsets are to be computed with.
839
  _offsets: Returns the offset for the buffer(s).
840
            _offsets[0] is always set.
841
            _offsets[1] is set if the motion vector has non-zero fractional
842
             components.
843
  _pli:     The color plane index.
844
  _mv:      The motion vector.
845
  Return: The number of offsets returned: 1 or 2.*/
846
int oc_state_get_mv_offsets(const oc_theora_state *_state,int _offsets[2],
847
2.48M
 int _pli,oc_mv _mv){
848
  /*Here is a brief description of how Theora handles motion vectors:
849
    Motion vector components are specified to half-pixel accuracy in
850
     undecimated directions of each plane, and quarter-pixel accuracy in
851
     decimated directions.
852
    Integer parts are extracted by dividing (not shifting) by the
853
     appropriate amount, with truncation towards zero.
854
    These integer values are used to calculate the first offset.
855
856
    If either of the fractional parts are non-zero, then a second offset is
857
     computed.
858
    No third or fourth offsets are computed, even if both components have
859
     non-zero fractional parts.
860
    The second offset is computed by dividing (not shifting) by the
861
     appropriate amount, always truncating _away_ from zero.*/
862
#if 0
863
  /*This version of the code doesn't use any tables, but is slower.*/
864
  int ystride;
865
  int xprec;
866
  int yprec;
867
  int xfrac;
868
  int yfrac;
869
  int offs;
870
  int dx;
871
  int dy;
872
  ystride=_state->ref_ystride[_pli];
873
  /*These two variables decide whether we are in half- or quarter-pixel
874
     precision in each component.*/
875
  xprec=1+(_pli!=0&&!(_state->info.pixel_fmt&1));
876
  yprec=1+(_pli!=0&&!(_state->info.pixel_fmt&2));
877
  dx=OC_MV_X(_mv);
878
  dy=OC_MV_Y(_mv);
879
  /*These two variables are either 0 if all the fractional bits are zero or -1
880
     if any of them are non-zero.*/
881
  xfrac=OC_SIGNMASK(-(dx&(xprec|1)));
882
  yfrac=OC_SIGNMASK(-(dy&(yprec|1)));
883
  offs=(dx>>xprec)+(dy>>yprec)*ystride;
884
  if(xfrac||yfrac){
885
    int xmask;
886
    int ymask;
887
    xmask=OC_SIGNMASK(dx);
888
    ymask=OC_SIGNMASK(dy);
889
    yfrac&=ystride;
890
    _offsets[0]=offs-(xfrac&xmask)+(yfrac&ymask);
891
    _offsets[1]=offs-(xfrac&~xmask)+(yfrac&~ymask);
892
    return 2;
893
  }
894
  else{
895
    _offsets[0]=offs;
896
    return 1;
897
  }
898
#else
899
  /*Using tables simplifies the code, and there's enough arithmetic to hide the
900
     latencies of the memory references.*/
901
2.48M
  static const signed char OC_MVMAP[2][64]={
902
2.48M
    {
903
2.48M
          -15,-15,-14,-14,-13,-13,-12,-12,-11,-11,-10,-10, -9, -9, -8,
904
2.48M
       -8, -7, -7, -6, -6, -5, -5, -4, -4, -3, -3, -2, -2, -1, -1,  0,
905
2.48M
        0,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,  5,  6,  6,  7,  7,
906
2.48M
        8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15
907
2.48M
    },
908
2.48M
    {
909
2.48M
           -7, -7, -7, -7, -6, -6, -6, -6, -5, -5, -5, -5, -4, -4, -4,
910
2.48M
       -4, -3, -3, -3, -3, -2, -2, -2, -2, -1, -1, -1, -1,  0,  0,  0,
911
2.48M
        0,  0,  0,  0,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,
912
2.48M
        4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7
913
2.48M
    }
914
2.48M
  };
915
2.48M
  static const signed char OC_MVMAP2[2][64]={
916
2.48M
    {
917
2.48M
        -1, 0,-1,  0,-1, 0,-1,  0,-1, 0,-1,  0,-1, 0,-1,
918
2.48M
      0,-1, 0,-1,  0,-1, 0,-1,  0,-1, 0,-1,  0,-1, 0,-1,
919
2.48M
      0, 1, 0, 1,  0, 1, 0, 1,  0, 1, 0, 1,  0, 1, 0, 1,
920
2.48M
      0, 1, 0, 1,  0, 1, 0, 1,  0, 1, 0, 1,  0, 1, 0, 1
921
2.48M
    },
922
2.48M
    {
923
2.48M
        -1,-1,-1,  0,-1,-1,-1,  0,-1,-1,-1,  0,-1,-1,-1,
924
2.48M
      0,-1,-1,-1,  0,-1,-1,-1,  0,-1,-1,-1,  0,-1,-1,-1,
925
2.48M
      0, 1, 1, 1,  0, 1, 1, 1,  0, 1, 1, 1,  0, 1, 1, 1,
926
2.48M
      0, 1, 1, 1,  0, 1, 1, 1,  0, 1, 1, 1,  0, 1, 1, 1
927
2.48M
    }
928
2.48M
  };
929
2.48M
  int ystride;
930
2.48M
  int qpx;
931
2.48M
  int qpy;
932
2.48M
  int mx;
933
2.48M
  int my;
934
2.48M
  int mx2;
935
2.48M
  int my2;
936
2.48M
  int offs;
937
2.48M
  int dx;
938
2.48M
  int dy;
939
2.48M
  ystride=_state->ref_ystride[_pli];
940
2.48M
  qpy=_pli!=0&&!(_state->info.pixel_fmt&2);
941
2.48M
  dx=OC_MV_X(_mv);
942
2.48M
  dy=OC_MV_Y(_mv);
943
2.48M
  my=OC_MVMAP[qpy][dy+31];
944
2.48M
  my2=OC_MVMAP2[qpy][dy+31];
945
2.48M
  qpx=_pli!=0&&!(_state->info.pixel_fmt&1);
946
2.48M
  mx=OC_MVMAP[qpx][dx+31];
947
2.48M
  mx2=OC_MVMAP2[qpx][dx+31];
948
2.48M
  offs=my*ystride+mx;
949
2.48M
  if(mx2||my2){
950
32.3k
    _offsets[1]=offs+my2*ystride+mx2;
951
32.3k
    _offsets[0]=offs;
952
32.3k
    return 2;
953
32.3k
  }
954
2.45M
  _offsets[0]=offs;
955
2.45M
  return 1;
956
2.48M
#endif
957
2.48M
}
958
959
void oc_state_frag_recon_c(const oc_theora_state *_state,ptrdiff_t _fragi,
960
0
 int _pli,ogg_int16_t _dct_coeffs[128],int _last_zzi,ogg_uint16_t _dc_quant){
961
0
  unsigned char *dst;
962
0
  ptrdiff_t      frag_buf_off;
963
0
  int            ystride;
964
0
  int            refi;
965
  /*Apply the inverse transform.*/
966
  /*Special case only having a DC component.*/
967
0
  if(_last_zzi<2){
968
0
    ogg_int16_t p;
969
0
    int         ci;
970
    /*We round this dequant product (and not any of the others) because there's
971
       no iDCT rounding.*/
972
0
    p=(ogg_int16_t)(_dct_coeffs[0]*(ogg_int32_t)_dc_quant+15>>5);
973
    /*LOOP VECTORIZES.*/
974
0
    for(ci=0;ci<64;ci++)_dct_coeffs[64+ci]=p;
975
0
  }
976
0
  else{
977
    /*First, dequantize the DC coefficient.*/
978
0
    _dct_coeffs[0]=(ogg_int16_t)(_dct_coeffs[0]*(int)_dc_quant);
979
0
    oc_idct8x8(_state,_dct_coeffs+64,_dct_coeffs,_last_zzi);
980
0
  }
981
  /*Fill in the target buffer.*/
982
0
  frag_buf_off=_state->frag_buf_offs[_fragi];
983
0
  refi=_state->frags[_fragi].refi;
984
0
  ystride=_state->ref_ystride[_pli];
985
0
  dst=_state->ref_frame_data[OC_FRAME_SELF]+frag_buf_off;
986
0
  if(refi==OC_FRAME_SELF)oc_frag_recon_intra(_state,dst,ystride,_dct_coeffs+64);
987
0
  else{
988
0
    const unsigned char *ref;
989
0
    int                  mvoffsets[2];
990
0
    ref=_state->ref_frame_data[refi]+frag_buf_off;
991
0
    if(oc_state_get_mv_offsets(_state,mvoffsets,_pli,
992
0
     _state->frag_mvs[_fragi])>1){
993
0
      oc_frag_recon_inter2(_state,
994
0
       dst,ref+mvoffsets[0],ref+mvoffsets[1],ystride,_dct_coeffs+64);
995
0
    }
996
0
    else{
997
0
      oc_frag_recon_inter(_state,dst,ref+mvoffsets[0],ystride,_dct_coeffs+64);
998
0
    }
999
0
  }
1000
0
}
1001
1002
0
static void loop_filter_h(unsigned char *_pix,int _ystride,signed char *_bv){
1003
0
  int y;
1004
0
  _pix-=2;
1005
0
  for(y=0;y<8;y++){
1006
0
    int f;
1007
0
    f=_pix[0]-_pix[3]+3*(_pix[2]-_pix[1]);
1008
    /*The _bv array is used to compute the function
1009
      f=OC_CLAMPI(OC_MINI(-_2flimit-f,0),f,OC_MAXI(_2flimit-f,0));
1010
      where _2flimit=_state->loop_filter_limits[_state->qis[0]]<<1;*/
1011
0
    f=*(_bv+(f+4>>3));
1012
0
    _pix[1]=OC_CLAMP255(_pix[1]+f);
1013
0
    _pix[2]=OC_CLAMP255(_pix[2]-f);
1014
0
    _pix+=_ystride;
1015
0
  }
1016
0
}
1017
1018
0
static void loop_filter_v(unsigned char *_pix,int _ystride,signed char *_bv){
1019
0
  int x;
1020
0
  _pix-=_ystride*2;
1021
0
  for(x=0;x<8;x++){
1022
0
    int f;
1023
0
    f=_pix[x]-_pix[_ystride*3+x]+3*(_pix[_ystride*2+x]-_pix[_ystride+x]);
1024
    /*The _bv array is used to compute the function
1025
      f=OC_CLAMPI(OC_MINI(-_2flimit-f,0),f,OC_MAXI(_2flimit-f,0));
1026
      where _2flimit=_state->loop_filter_limits[_state->qis[0]]<<1;*/
1027
0
    f=*(_bv+(f+4>>3));
1028
0
    _pix[_ystride+x]=OC_CLAMP255(_pix[_ystride+x]+f);
1029
0
    _pix[_ystride*2+x]=OC_CLAMP255(_pix[_ystride*2+x]-f);
1030
0
  }
1031
0
}
1032
1033
/*Initialize the bounding values array used by the loop filter.
1034
  _bv: Storage for the array.
1035
  _flimit: The filter limit as defined in Section 7.10 of the spec.*/
1036
0
void oc_loop_filter_init_c(signed char _bv[256],int _flimit){
1037
0
  int i;
1038
0
  memset(_bv,0,sizeof(_bv[0])*256);
1039
0
  for(i=0;i<_flimit;i++){
1040
0
    if(127-i-_flimit>=0)_bv[127-i-_flimit]=(signed char)(i-_flimit);
1041
0
    _bv[127-i]=(signed char)(-i);
1042
0
    _bv[127+i]=(signed char)(i);
1043
0
    if(127+i+_flimit<256)_bv[127+i+_flimit]=(signed char)(_flimit-i);
1044
0
  }
1045
0
}
1046
1047
/*Apply the loop filter to a given set of fragment rows in the given plane.
1048
  The filter may be run on the bottom edge, affecting pixels in the next row of
1049
   fragments, so this row also needs to be available.
1050
  _bv:        The bounding values array.
1051
  _refi:      The index of the frame buffer to filter.
1052
  _pli:       The color plane to filter.
1053
  _fragy0:    The Y coordinate of the first fragment row to filter.
1054
  _fragy_end: The Y coordinate of the fragment row to stop filtering at.*/
1055
void oc_state_loop_filter_frag_rows_c(const oc_theora_state *_state,
1056
0
 signed char _bvarray[256],int _refi,int _pli,int _fragy0,int _fragy_end){
1057
0
  const oc_fragment_plane *fplane;
1058
0
  const oc_fragment       *frags;
1059
0
  const ptrdiff_t         *frag_buf_offs;
1060
0
  unsigned char           *ref_frame_data;
1061
0
  ptrdiff_t                fragi_top;
1062
0
  ptrdiff_t                fragi_bot;
1063
0
  ptrdiff_t                fragi0;
1064
0
  ptrdiff_t                fragi0_end;
1065
0
  int                      ystride;
1066
0
  int                      nhfrags;
1067
0
  signed char             *_bv = &_bvarray[127];
1068
0
  fplane=_state->fplanes+_pli;
1069
0
  nhfrags=fplane->nhfrags;
1070
0
  fragi_top=fplane->froffset;
1071
0
  fragi_bot=fragi_top+fplane->nfrags;
1072
0
  fragi0=fragi_top+_fragy0*(ptrdiff_t)nhfrags;
1073
0
  fragi0_end=fragi_top+_fragy_end*(ptrdiff_t)nhfrags;
1074
0
  ystride=_state->ref_ystride[_pli];
1075
0
  frags=_state->frags;
1076
0
  frag_buf_offs=_state->frag_buf_offs;
1077
0
  ref_frame_data=_state->ref_frame_data[_refi];
1078
  /*The following loops are constructed somewhat non-intuitively on purpose.
1079
    The main idea is: if a block boundary has at least one coded fragment on
1080
     it, the filter is applied to it.
1081
    However, the order that the filters are applied in matters, and VP3 chose
1082
     the somewhat strange ordering used below.*/
1083
0
  while(fragi0<fragi0_end){
1084
0
    ptrdiff_t fragi;
1085
0
    ptrdiff_t fragi_end;
1086
0
    fragi=fragi0;
1087
0
    fragi_end=fragi+nhfrags;
1088
0
    while(fragi<fragi_end){
1089
0
      if(frags[fragi].coded){
1090
0
        unsigned char *ref;
1091
0
        ref=ref_frame_data+frag_buf_offs[fragi];
1092
0
        if(fragi>fragi0)loop_filter_h(ref,ystride,_bv);
1093
0
        if(fragi0>fragi_top)loop_filter_v(ref,ystride,_bv);
1094
0
        if(fragi+1<fragi_end&&!frags[fragi+1].coded){
1095
0
          loop_filter_h(ref+8,ystride,_bv);
1096
0
        }
1097
0
        if(fragi+nhfrags<fragi_bot&&!frags[fragi+nhfrags].coded){
1098
0
          loop_filter_v(ref+(ystride*8),ystride,_bv);
1099
0
        }
1100
0
      }
1101
0
      fragi++;
1102
0
    }
1103
0
    fragi0+=nhfrags;
1104
0
  }
1105
0
}
1106
1107
#if defined(OC_DUMP_IMAGES)
1108
int oc_state_dump_frame(const oc_theora_state *_state,int _frame,
1109
 const char *_suf){
1110
  /*Dump a PNG of the reconstructed image.*/
1111
  png_structp    png;
1112
  png_infop      info;
1113
  png_bytep     *image;
1114
  FILE          *fp;
1115
  char           fname[16];
1116
  unsigned char *y_row;
1117
  unsigned char *u_row;
1118
  unsigned char *v_row;
1119
  unsigned char *y;
1120
  unsigned char *u;
1121
  unsigned char *v;
1122
  ogg_int64_t    iframe;
1123
  ogg_int64_t    pframe;
1124
  int            y_stride;
1125
  int            u_stride;
1126
  int            v_stride;
1127
  int            framei;
1128
  int            width;
1129
  int            height;
1130
  int            imgi;
1131
  int            imgj;
1132
  width=_state->info.frame_width;
1133
  height=_state->info.frame_height;
1134
  iframe=_state->granpos>>_state->info.keyframe_granule_shift;
1135
  pframe=_state->granpos-(iframe<<_state->info.keyframe_granule_shift);
1136
  sprintf(fname,"%08i%s.png",(int)(iframe+pframe),_suf);
1137
  fp=fopen(fname,"wb");
1138
  if(fp==NULL)return TH_EFAULT;
1139
  image=(png_bytep *)oc_malloc_2d(height,6*width,sizeof(**image));
1140
  if(image==NULL){
1141
    fclose(fp);
1142
    return TH_EFAULT;
1143
  }
1144
  png=png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
1145
  if(png==NULL){
1146
    oc_free_2d(image);
1147
    fclose(fp);
1148
    return TH_EFAULT;
1149
  }
1150
  info=png_create_info_struct(png);
1151
  if(info==NULL){
1152
    png_destroy_write_struct(&png,NULL);
1153
    oc_free_2d(image);
1154
    fclose(fp);
1155
    return TH_EFAULT;
1156
  }
1157
  if(setjmp(png_jmpbuf(png))){
1158
    png_destroy_write_struct(&png,&info);
1159
    oc_free_2d(image);
1160
    fclose(fp);
1161
    return TH_EFAULT;
1162
  }
1163
  framei=_state->ref_frame_idx[_frame];
1164
  y_row=_state->ref_frame_bufs[framei][0].data;
1165
  u_row=_state->ref_frame_bufs[framei][1].data;
1166
  v_row=_state->ref_frame_bufs[framei][2].data;
1167
  y_stride=_state->ref_frame_bufs[framei][0].stride;
1168
  u_stride=_state->ref_frame_bufs[framei][1].stride;
1169
  v_stride=_state->ref_frame_bufs[framei][2].stride;
1170
  /*Chroma up-sampling is just done with a box filter.
1171
    This is very likely what will actually be used in practice on a real
1172
     display, and also removes one more layer to search in for the source of
1173
     artifacts.
1174
    As an added bonus, it's dead simple.*/
1175
  for(imgi=height;imgi-->0;){
1176
    int dc;
1177
    y=y_row;
1178
    u=u_row;
1179
    v=v_row;
1180
    for(imgj=0;imgj<6*width;){
1181
      float    yval;
1182
      float    uval;
1183
      float    vval;
1184
      unsigned rval;
1185
      unsigned gval;
1186
      unsigned bval;
1187
      /*This is intentionally slow and very accurate.*/
1188
      yval=(*y-16)*(1.0F/219);
1189
      uval=(*u-128)*(2*(1-0.114F)/224);
1190
      vval=(*v-128)*(2*(1-0.299F)/224);
1191
      rval=OC_CLAMPI(0,(int)(65535*(yval+vval)+0.5F),65535);
1192
      gval=OC_CLAMPI(0,(int)(65535*(
1193
       yval-uval*(0.114F/0.587F)-vval*(0.299F/0.587F))+0.5F),65535);
1194
      bval=OC_CLAMPI(0,(int)(65535*(yval+uval)+0.5F),65535);
1195
      image[imgi][imgj++]=(unsigned char)(rval>>8);
1196
      image[imgi][imgj++]=(unsigned char)(rval&0xFF);
1197
      image[imgi][imgj++]=(unsigned char)(gval>>8);
1198
      image[imgi][imgj++]=(unsigned char)(gval&0xFF);
1199
      image[imgi][imgj++]=(unsigned char)(bval>>8);
1200
      image[imgi][imgj++]=(unsigned char)(bval&0xFF);
1201
      dc=(y-y_row&1)|(_state->info.pixel_fmt&1);
1202
      y++;
1203
      u+=dc;
1204
      v+=dc;
1205
    }
1206
    dc=-((height-1-imgi&1)|_state->info.pixel_fmt>>1);
1207
    y_row+=y_stride;
1208
    u_row+=dc&u_stride;
1209
    v_row+=dc&v_stride;
1210
  }
1211
  png_init_io(png,fp);
1212
  png_set_compression_level(png,Z_BEST_COMPRESSION);
1213
  png_set_IHDR(png,info,width,height,16,PNG_COLOR_TYPE_RGB,
1214
   PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);
1215
  switch(_state->info.colorspace){
1216
    case TH_CS_ITU_REC_470M:{
1217
      png_set_gAMA(png,info,2.2);
1218
      png_set_cHRM_fixed(png,info,31006,31616,
1219
       67000,32000,21000,71000,14000,8000);
1220
    }break;
1221
    case TH_CS_ITU_REC_470BG:{
1222
      png_set_gAMA(png,info,2.67);
1223
      png_set_cHRM_fixed(png,info,31271,32902,
1224
       64000,33000,29000,60000,15000,6000);
1225
    }break;
1226
    default:break;
1227
  }
1228
  png_set_pHYs(png,info,_state->info.aspect_numerator,
1229
   _state->info.aspect_denominator,0);
1230
  png_set_rows(png,info,image);
1231
  png_write_png(png,info,PNG_TRANSFORM_IDENTITY,NULL);
1232
  png_write_end(png,info);
1233
  png_destroy_write_struct(&png,&info);
1234
  oc_free_2d(image);
1235
  fclose(fp);
1236
  return 0;
1237
}
1238
#endif
1239
1240
1241
1242
0
ogg_int64_t th_granule_frame(void *_encdec,ogg_int64_t _granpos){
1243
0
  oc_theora_state *state;
1244
0
  state=(oc_theora_state *)_encdec;
1245
0
  if(_granpos>=0){
1246
0
    ogg_int64_t iframe;
1247
0
    ogg_int64_t pframe;
1248
0
    iframe=_granpos>>state->info.keyframe_granule_shift;
1249
0
    pframe=_granpos-(iframe<<state->info.keyframe_granule_shift);
1250
    /*3.2.0 streams store the frame index in the granule position.
1251
      3.2.1 and later store the frame count.
1252
      We return the index, so adjust the value if we have a 3.2.1 or later
1253
       stream.*/
1254
0
    return iframe+pframe-TH_VERSION_CHECK(&state->info,3,2,1);
1255
0
  }
1256
0
  return -1;
1257
0
}
1258
1259
0
double th_granule_time(void *_encdec,ogg_int64_t _granpos){
1260
0
  oc_theora_state *state;
1261
0
  state=(oc_theora_state *)_encdec;
1262
0
  if(_granpos>=0){
1263
0
    return (th_granule_frame(_encdec, _granpos)+1)*(
1264
0
     (double)state->info.fps_denominator/state->info.fps_numerator);
1265
0
  }
1266
0
  return -1;
1267
0
}