]> git.sesse.net Git - ffmpeg/blob - libavcodec/roqvideoenc.c
avcodec/roqvideo: Use dedicated context for encoder
[ffmpeg] / libavcodec / roqvideoenc.c
1 /*
2  * RoQ Video Encoder.
3  *
4  * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com>
5  * Copyright (C) 2004-2007 Eric Lasota
6  *    Based on RoQ specs (C) 2001 Tim Ferguson
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file
27  * id RoQ encoder by Vitor. Based on the Switchblade3 library and the
28  * Switchblade3 FFmpeg glue by Eric Lasota.
29  */
30
31 /*
32  * COSTS:
33  * Level 1:
34  *  SKIP - 2 bits
35  *  MOTION - 2 + 8 bits
36  *  CODEBOOK - 2 + 8 bits
37  *  SUBDIVIDE - 2 + combined subcel cost
38  *
39  * Level 2:
40  *  SKIP - 2 bits
41  *  MOTION - 2 + 8 bits
42  *  CODEBOOK - 2 + 8 bits
43  *  SUBDIVIDE - 2 + 4*8 bits
44  *
45  * Maximum cost: 138 bits per cel
46  *
47  * Proper evaluation requires LCD fraction comparison, which requires
48  * Squared Error (SE) loss * savings increase
49  *
50  * Maximum savings increase: 136 bits
51  * Maximum SE loss without overflow: 31580641
52  * Components in 8x8 supercel: 192
53  * Maximum SE precision per component: 164482
54  *    >65025, so no truncation is needed (phew)
55  */
56
57 #include <string.h>
58
59 #include "libavutil/attributes.h"
60 #include "libavutil/lfg.h"
61 #include "libavutil/opt.h"
62 #include "roqvideo.h"
63 #include "bytestream.h"
64 #include "elbg.h"
65 #include "internal.h"
66 #include "mathops.h"
67
68 #define CHROMA_BIAS 1
69
70 /**
71  * Maximum number of generated 4x4 codebooks. Can't be 256 to workaround a
72  * Quake 3 bug.
73  */
74 #define MAX_CBS_4x4 256
75
76 #define MAX_CBS_2x2 256 ///< Maximum number of 2x2 codebooks.
77
78 /* The cast is useful when multiplying it by INT_MAX */
79 #define ROQ_LAMBDA_SCALE ((uint64_t) FF_LAMBDA_SCALE)
80
81 typedef struct RoqEncContext {
82     RoqContext common;
83     AVLFG randctx;
84     uint64_t lambda;
85
86     motion_vect *this_motion4;
87     motion_vect *last_motion4;
88
89     motion_vect *this_motion8;
90     motion_vect *last_motion8;
91
92     unsigned int framesSinceKeyframe;
93
94     const AVFrame *frame_to_enc;
95     uint8_t *out_buf;
96     struct RoqTempData *tmpData;
97
98     int first_frame;
99     int quake3_compat; // Quake 3 compatibility option
100 } RoqEncContext;
101
102 /* Macroblock support functions */
103 static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
104 {
105     memcpy(u  , cell->y, 4);
106     memset(u+4, cell->u, 4);
107     memset(u+8, cell->v, 4);
108 }
109
110 static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
111 {
112     int i,cp;
113     static const int offsets[4] = {0, 2, 8, 10};
114
115     for (cp=0; cp<3; cp++)
116         for (i=0; i<4; i++) {
117             u[4*4*cp + offsets[i]  ] = cb2[qcell->idx[i]*2*2*3 + 4*cp  ];
118             u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
119             u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
120             u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
121         }
122 }
123
124
125 static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
126 {
127     int x,y,cp;
128
129     for(cp=0; cp<3; cp++)
130         for(y=0; y<8; y++)
131             for(x=0; x<8; x++)
132                 *u++ = base[(y/2)*4 + (x/2) + 16*cp];
133 }
134
135 static inline int square(int x)
136 {
137     return x*x;
138 }
139
140 static inline int eval_sse(const uint8_t *a, const uint8_t *b, int count)
141 {
142     int diff=0;
143
144     while(count--)
145         diff += square(*b++ - *a++);
146
147     return diff;
148 }
149
150 // FIXME Could use DSPContext.sse, but it is not so speed critical (used
151 // just for motion estimation).
152 static int block_sse(uint8_t * const *buf1, uint8_t * const *buf2, int x1, int y1,
153                      int x2, int y2, const int *stride1, const int *stride2, int size)
154 {
155     int i, k;
156     int sse=0;
157
158     for (k=0; k<3; k++) {
159         int bias = (k ? CHROMA_BIAS : 4);
160         for (i=0; i<size; i++)
161             sse += bias*eval_sse(buf1[k] + (y1+i)*stride1[k] + x1,
162                                  buf2[k] + (y2+i)*stride2[k] + x2, size);
163     }
164
165     return sse;
166 }
167
168 static int eval_motion_dist(RoqEncContext *enc, int x, int y, motion_vect vect,
169                              int size)
170 {
171     RoqContext *const roq = &enc->common;
172     int mx=vect.d[0];
173     int my=vect.d[1];
174
175     if (mx < -7 || mx > 7)
176         return INT_MAX;
177
178     if (my < -7 || my > 7)
179         return INT_MAX;
180
181     mx += x;
182     my += y;
183
184     if ((unsigned) mx > roq->width-size || (unsigned) my > roq->height-size)
185         return INT_MAX;
186
187     return block_sse(enc->frame_to_enc->data, roq->last_frame->data, x, y,
188                      mx, my,
189                      enc->frame_to_enc->linesize, roq->last_frame->linesize,
190                      size);
191 }
192
193 /**
194  * @return distortion between two macroblocks
195  */
196 static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
197 {
198     int cp, sdiff=0;
199
200     for(cp=0;cp<3;cp++) {
201         int bias = (cp ? CHROMA_BIAS : 4);
202         sdiff += bias*eval_sse(a, b, size*size);
203         a += size*size;
204         b += size*size;
205     }
206
207     return sdiff;
208 }
209
210 typedef struct SubcelEvaluation {
211     int eval_dist[4];
212     int best_bit_use;
213     int best_coding;
214
215     int subCels[4];
216     motion_vect motion;
217     int cbEntry;
218 } SubcelEvaluation;
219
220 typedef struct CelEvaluation {
221     int eval_dist[4];
222     int best_coding;
223
224     SubcelEvaluation subCels[4];
225
226     motion_vect motion;
227     int cbEntry;
228
229     int sourceX, sourceY;
230 } CelEvaluation;
231
232 typedef struct RoqCodebooks {
233     int numCB4;
234     int numCB2;
235     int usedCB2[MAX_CBS_2x2];
236     int usedCB4[MAX_CBS_4x4];
237     uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
238     uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
239     uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
240 } RoqCodebooks;
241
242 /**
243  * Temporary vars
244  */
245 typedef struct RoqTempData
246 {
247     CelEvaluation *cel_evals;
248
249     int f2i4[MAX_CBS_4x4];
250     int i2f4[MAX_CBS_4x4];
251     int f2i2[MAX_CBS_2x2];
252     int i2f2[MAX_CBS_2x2];
253
254     int mainChunkSize;
255
256     int numCB4;
257     int numCB2;
258
259     RoqCodebooks codebooks;
260
261     int *closest_cb2;
262     int used_option[4];
263 } RoqTempdata;
264
265 /**
266  * Initialize cel evaluators and set their source coordinates
267  */
268 static int create_cel_evals(RoqContext *enc, RoqTempdata *tempData)
269 {
270     int n=0, x, y, i;
271
272     tempData->cel_evals = av_malloc_array(enc->width*enc->height/64, sizeof(CelEvaluation));
273     if (!tempData->cel_evals)
274         return AVERROR(ENOMEM);
275
276     /* Map to the ROQ quadtree order */
277     for (y=0; y<enc->height; y+=16)
278         for (x=0; x<enc->width; x+=16)
279             for(i=0; i<4; i++) {
280                 tempData->cel_evals[n  ].sourceX = x + (i&1)*8;
281                 tempData->cel_evals[n++].sourceY = y + (i&2)*4;
282             }
283
284     return 0;
285 }
286
287 /**
288  * Get macroblocks from parts of the image
289  */
290 static void get_frame_mb(const AVFrame *frame, int x, int y, uint8_t mb[], int dim)
291 {
292     int i, j, cp;
293
294     for (cp=0; cp<3; cp++) {
295         int stride = frame->linesize[cp];
296         for (i=0; i<dim; i++)
297             for (j=0; j<dim; j++)
298                 *mb++ = frame->data[cp][(y+i)*stride + x + j];
299     }
300 }
301
302 /**
303  * Find the codebook with the lowest distortion from an image
304  */
305 static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
306                     int *outIndex, int dim)
307 {
308     int i, lDiff = INT_MAX, pick=0;
309
310     /* Diff against the others */
311     for (i=0; i<numCB; i++) {
312         int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
313         if (diff < lDiff) {
314             lDiff = diff;
315             pick = i;
316         }
317     }
318
319     *outIndex = pick;
320     return lDiff;
321 }
322
323 #define EVAL_MOTION(MOTION) \
324     do { \
325         diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
326             \
327         if (diff < lowestdiff) { \
328             lowestdiff = diff; \
329             bestpick = MOTION; \
330         } \
331     } while(0)
332
333 static void motion_search(RoqEncContext *enc, int blocksize)
334 {
335     static const motion_vect offsets[8] = {
336         {{ 0,-1}},
337         {{ 0, 1}},
338         {{-1, 0}},
339         {{ 1, 0}},
340         {{-1, 1}},
341         {{ 1,-1}},
342         {{-1,-1}},
343         {{ 1, 1}},
344     };
345
346     RoqContext *const roq = &enc->common;
347     int diff, lowestdiff, oldbest;
348     int off[3];
349     motion_vect bestpick = {{0,0}};
350     int i, j, k, offset;
351
352     motion_vect *last_motion;
353     motion_vect *this_motion;
354     motion_vect vect, vect2;
355     const int max = (roq->width / blocksize) * roq->height / blocksize;
356
357     if (blocksize == 4) {
358         last_motion = enc->last_motion4;
359         this_motion = enc->this_motion4;
360     } else {
361         last_motion = enc->last_motion8;
362         this_motion = enc->this_motion8;
363     }
364
365     for (i = 0; i< roq->height; i += blocksize)
366         for (j = 0; j < roq->width; j += blocksize) {
367             lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
368                                           blocksize);
369             bestpick.d[0] = 0;
370             bestpick.d[1] = 0;
371
372             if (blocksize == 4)
373                 EVAL_MOTION(enc->this_motion8[(i/8) * (roq->width/8) + j/8]);
374
375             offset = (i/blocksize) * roq->width / blocksize + j / blocksize;
376             if (offset < max && offset >= 0)
377                 EVAL_MOTION(last_motion[offset]);
378
379             offset++;
380             if (offset < max && offset >= 0)
381                 EVAL_MOTION(last_motion[offset]);
382
383             offset = (i/blocksize + 1) * roq->width / blocksize + j / blocksize;
384             if (offset < max && offset >= 0)
385                 EVAL_MOTION(last_motion[offset]);
386
387             off[0]= (i/blocksize) * roq->width / blocksize + j/blocksize - 1;
388             off[1]= off[0] - roq->width / blocksize + 1;
389             off[2]= off[1] + 1;
390
391             if (i) {
392
393                 for(k=0; k<2; k++)
394                     vect.d[k]= mid_pred(this_motion[off[0]].d[k],
395                                         this_motion[off[1]].d[k],
396                                         this_motion[off[2]].d[k]);
397
398                 EVAL_MOTION(vect);
399                 for(k=0; k<3; k++)
400                     EVAL_MOTION(this_motion[off[k]]);
401             } else if(j)
402                 EVAL_MOTION(this_motion[off[0]]);
403
404             vect = bestpick;
405
406             oldbest = -1;
407             while (oldbest != lowestdiff) {
408                 oldbest = lowestdiff;
409                 for (k=0; k<8; k++) {
410                     vect2 = vect;
411                     vect2.d[0] += offsets[k].d[0];
412                     vect2.d[1] += offsets[k].d[1];
413                     EVAL_MOTION(vect2);
414                 }
415                 vect = bestpick;
416             }
417             offset = (i/blocksize) * roq->width / blocksize + j/blocksize;
418             this_motion[offset] = bestpick;
419         }
420 }
421
422 /**
423  * Get distortion for all options available to a subcel
424  */
425 static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
426                                    int y, RoqEncContext *enc, RoqTempdata *tempData)
427 {
428     RoqContext *const roq = &enc->common;
429     uint8_t mb4[4*4*3];
430     uint8_t mb2[2*2*3];
431     int cluster_index;
432     int i, best_dist;
433
434     static const int bitsUsed[4] = {2, 10, 10, 34};
435
436     if (enc->framesSinceKeyframe >= 1) {
437         subcel->motion = enc->this_motion4[y * roq->width / 16 + x / 4];
438
439         subcel->eval_dist[RoQ_ID_FCC] =
440             eval_motion_dist(enc, x, y,
441                              enc->this_motion4[y * roq->width / 16 + x / 4], 4);
442     } else
443         subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
444
445     if (enc->framesSinceKeyframe >= 2)
446         subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
447                                                   roq->current_frame->data, x,
448                                                   y, x, y,
449                                                   enc->frame_to_enc->linesize,
450                                                   roq->current_frame->linesize,
451                                                   4);
452     else
453         subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
454
455     cluster_index = y * roq->width / 16 + x / 4;
456
457     get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
458
459     subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
460                                              tempData->codebooks.unpacked_cb4,
461                                              tempData->codebooks.numCB4,
462                                              &subcel->cbEntry, 4);
463
464     subcel->eval_dist[RoQ_ID_CCC] = 0;
465
466     for(i=0;i<4;i++) {
467         subcel->subCels[i] = tempData->closest_cb2[cluster_index*4+i];
468
469         get_frame_mb(enc->frame_to_enc, x+2*(i&1),
470                      y+(i&2), mb2, 2);
471
472         subcel->eval_dist[RoQ_ID_CCC] +=
473             squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
474     }
475
476     best_dist = INT_MAX;
477     for (i=0; i<4; i++)
478         if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
479             best_dist) {
480             subcel->best_coding = i;
481             subcel->best_bit_use = bitsUsed[i];
482             best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
483                 enc->lambda*bitsUsed[i];
484         }
485 }
486
487 /**
488  * Get distortion for all options available to a cel
489  */
490 static void gather_data_for_cel(CelEvaluation *cel, RoqEncContext *enc,
491                                 RoqTempdata *tempData)
492 {
493     RoqContext *const roq = &enc->common;
494     uint8_t mb8[8*8*3];
495     int index = cel->sourceY * roq->width / 64 + cel->sourceX/8;
496     int i, j, best_dist, divide_bit_use;
497
498     int bitsUsed[4] = {2, 10, 10, 0};
499
500     if (enc->framesSinceKeyframe >= 1) {
501         cel->motion = enc->this_motion8[index];
502
503         cel->eval_dist[RoQ_ID_FCC] =
504             eval_motion_dist(enc, cel->sourceX, cel->sourceY,
505                              enc->this_motion8[index], 8);
506     } else
507         cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
508
509     if (enc->framesSinceKeyframe >= 2)
510         cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
511                                                roq->current_frame->data,
512                                                cel->sourceX, cel->sourceY,
513                                                cel->sourceX, cel->sourceY,
514                                                enc->frame_to_enc->linesize,
515                                                roq->current_frame->linesize,8);
516     else
517         cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
518
519     get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
520
521     cel->eval_dist[RoQ_ID_SLD] =
522         index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
523                  tempData->codebooks.numCB4, &cel->cbEntry, 8);
524
525     gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
526     gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
527     gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
528     gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
529
530     cel->eval_dist[RoQ_ID_CCC] = 0;
531     divide_bit_use = 0;
532     for (i=0; i<4; i++) {
533         cel->eval_dist[RoQ_ID_CCC] +=
534             cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
535         divide_bit_use += cel->subCels[i].best_bit_use;
536     }
537
538     best_dist = INT_MAX;
539     bitsUsed[3] = 2 + divide_bit_use;
540
541     for (i=0; i<4; i++)
542         if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
543             best_dist) {
544             cel->best_coding = i;
545             best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
546                 enc->lambda*bitsUsed[i];
547         }
548
549     tempData->used_option[cel->best_coding]++;
550     tempData->mainChunkSize += bitsUsed[cel->best_coding];
551
552     if (cel->best_coding == RoQ_ID_SLD)
553         tempData->codebooks.usedCB4[cel->cbEntry]++;
554
555     if (cel->best_coding == RoQ_ID_CCC)
556         for (i=0; i<4; i++) {
557             if (cel->subCels[i].best_coding == RoQ_ID_SLD)
558                 tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
559             else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
560                 for (j=0; j<4; j++)
561                     tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
562         }
563 }
564
565 static void remap_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
566 {
567     RoqContext *const roq = &enc->common;
568     int i, j, idx=0;
569
570     /* Make remaps for the final codebook usage */
571     for (i=0; i<(enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4); i++) {
572         if (tempData->codebooks.usedCB4[i]) {
573             tempData->i2f4[i] = idx;
574             tempData->f2i4[idx] = i;
575             for (j=0; j<4; j++)
576                 tempData->codebooks.usedCB2[roq->cb4x4[i].idx[j]]++;
577             idx++;
578         }
579     }
580
581     tempData->numCB4 = idx;
582
583     idx = 0;
584     for (i=0; i<MAX_CBS_2x2; i++) {
585         if (tempData->codebooks.usedCB2[i]) {
586             tempData->i2f2[i] = idx;
587             tempData->f2i2[idx] = i;
588             idx++;
589         }
590     }
591     tempData->numCB2 = idx;
592
593 }
594
595 /**
596  * Write codebook chunk
597  */
598 static void write_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
599 {
600     RoqContext *const roq = &enc->common;
601     int i, j;
602     uint8_t **outp= &enc->out_buf;
603
604     if (tempData->numCB2) {
605         bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
606         bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
607         bytestream_put_byte(outp, tempData->numCB4);
608         bytestream_put_byte(outp, tempData->numCB2);
609
610         for (i=0; i<tempData->numCB2; i++) {
611             bytestream_put_buffer(outp, roq->cb2x2[tempData->f2i2[i]].y, 4);
612             bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].u);
613             bytestream_put_byte(outp, roq->cb2x2[tempData->f2i2[i]].v);
614         }
615
616         for (i=0; i<tempData->numCB4; i++)
617             for (j=0; j<4; j++)
618                 bytestream_put_byte(outp, tempData->i2f2[roq->cb4x4[tempData->f2i4[i]].idx[j]]);
619
620     }
621 }
622
623 static inline uint8_t motion_arg(motion_vect mot)
624 {
625     uint8_t ax = 8 - ((uint8_t) mot.d[0]);
626     uint8_t ay = 8 - ((uint8_t) mot.d[1]);
627     return ((ax&15)<<4) | (ay&15);
628 }
629
630 typedef struct CodingSpool {
631     int typeSpool;
632     int typeSpoolLength;
633     uint8_t argumentSpool[64];
634     uint8_t *args;
635     uint8_t **pout;
636 } CodingSpool;
637
638 /* NOTE: Typecodes must be spooled AFTER arguments!! */
639 static void write_typecode(CodingSpool *s, uint8_t type)
640 {
641     s->typeSpool |= (type & 3) << (14 - s->typeSpoolLength);
642     s->typeSpoolLength += 2;
643     if (s->typeSpoolLength == 16) {
644         bytestream_put_le16(s->pout, s->typeSpool);
645         bytestream_put_buffer(s->pout, s->argumentSpool,
646                               s->args - s->argumentSpool);
647         s->typeSpoolLength = 0;
648         s->typeSpool = 0;
649         s->args = s->argumentSpool;
650     }
651 }
652
653 static void reconstruct_and_encode_image(RoqEncContext *enc,
654                                          RoqTempdata *tempData,
655                                          int w, int h, int numBlocks)
656 {
657     RoqContext *const roq = &enc->common;
658     int i, j, k;
659     int x, y;
660     int subX, subY;
661     int dist=0;
662
663     roq_qcell *qcell;
664     CelEvaluation *eval;
665
666     CodingSpool spool;
667
668     spool.typeSpool=0;
669     spool.typeSpoolLength=0;
670     spool.args = spool.argumentSpool;
671     spool.pout = &enc->out_buf;
672
673     if (tempData->used_option[RoQ_ID_CCC]%2)
674         tempData->mainChunkSize+=8; //FIXME
675
676     /* Write the video chunk header */
677     bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
678     bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
679     bytestream_put_byte(&enc->out_buf, 0x0);
680     bytestream_put_byte(&enc->out_buf, 0x0);
681
682     for (i=0; i<numBlocks; i++) {
683         eval = tempData->cel_evals + i;
684
685         x = eval->sourceX;
686         y = eval->sourceY;
687         dist += eval->eval_dist[eval->best_coding];
688
689         switch (eval->best_coding) {
690         case RoQ_ID_MOT:
691             write_typecode(&spool, RoQ_ID_MOT);
692             break;
693
694         case RoQ_ID_FCC:
695             bytestream_put_byte(&spool.args, motion_arg(eval->motion));
696
697             write_typecode(&spool, RoQ_ID_FCC);
698             ff_apply_motion_8x8(roq, x, y,
699                                 eval->motion.d[0], eval->motion.d[1]);
700             break;
701
702         case RoQ_ID_SLD:
703             bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
704             write_typecode(&spool, RoQ_ID_SLD);
705
706             qcell = roq->cb4x4 + eval->cbEntry;
707             ff_apply_vector_4x4(roq, x  , y  , roq->cb2x2 + qcell->idx[0]);
708             ff_apply_vector_4x4(roq, x+4, y  , roq->cb2x2 + qcell->idx[1]);
709             ff_apply_vector_4x4(roq, x  , y+4, roq->cb2x2 + qcell->idx[2]);
710             ff_apply_vector_4x4(roq, x+4, y+4, roq->cb2x2 + qcell->idx[3]);
711             break;
712
713         case RoQ_ID_CCC:
714             write_typecode(&spool, RoQ_ID_CCC);
715
716             for (j=0; j<4; j++) {
717                 subX = x + 4*(j&1);
718                 subY = y + 2*(j&2);
719
720                 switch(eval->subCels[j].best_coding) {
721                 case RoQ_ID_MOT:
722                     break;
723
724                 case RoQ_ID_FCC:
725                     bytestream_put_byte(&spool.args,
726                                         motion_arg(eval->subCels[j].motion));
727
728                     ff_apply_motion_4x4(roq, subX, subY,
729                                         eval->subCels[j].motion.d[0],
730                                         eval->subCels[j].motion.d[1]);
731                     break;
732
733                 case RoQ_ID_SLD:
734                     bytestream_put_byte(&spool.args,
735                                         tempData->i2f4[eval->subCels[j].cbEntry]);
736
737                     qcell = roq->cb4x4 + eval->subCels[j].cbEntry;
738
739                     ff_apply_vector_2x2(roq, subX  , subY  ,
740                                         roq->cb2x2 + qcell->idx[0]);
741                     ff_apply_vector_2x2(roq, subX+2, subY  ,
742                                         roq->cb2x2 + qcell->idx[1]);
743                     ff_apply_vector_2x2(roq, subX  , subY+2,
744                                         roq->cb2x2 + qcell->idx[2]);
745                     ff_apply_vector_2x2(roq, subX+2, subY+2,
746                                         roq->cb2x2 + qcell->idx[3]);
747                     break;
748
749                 case RoQ_ID_CCC:
750                     for (k=0; k<4; k++) {
751                         int cb_idx = eval->subCels[j].subCels[k];
752                         bytestream_put_byte(&spool.args,
753                                             tempData->i2f2[cb_idx]);
754
755                         ff_apply_vector_2x2(roq, subX + 2*(k&1), subY + (k&2),
756                                             roq->cb2x2 + cb_idx);
757                     }
758                     break;
759                 }
760                 write_typecode(&spool, eval->subCels[j].best_coding);
761             }
762             break;
763         }
764     }
765
766     /* Flush the remainder of the argument/type spool */
767     while (spool.typeSpoolLength)
768         write_typecode(&spool, 0x0);
769 }
770
771
772 /**
773  * Create a single YUV cell from a 2x2 section of the image
774  */
775 static inline void frame_block_to_cell(uint8_t *block, uint8_t * const *data,
776                                        int top, int left, const int *stride)
777 {
778     int i, j, u=0, v=0;
779
780     for (i=0; i<2; i++)
781         for (j=0; j<2; j++) {
782             int x = (top+i)*stride[0] + left + j;
783             *block++ = data[0][x];
784             x = (top+i)*stride[1] + left + j;
785             u       += data[1][x];
786             v       += data[2][x];
787         }
788
789     *block++ = (u+2)/4;
790     *block++ = (v+2)/4;
791 }
792
793 /**
794  * Create YUV clusters for the entire image
795  */
796 static void create_clusters(const AVFrame *frame, int w, int h, uint8_t *yuvClusters)
797 {
798     int i, j, k, l;
799
800     for (i=0; i<h; i+=4)
801         for (j=0; j<w; j+=4) {
802             for (k=0; k < 2; k++)
803                 for (l=0; l < 2; l++)
804                     frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
805                                         i+2*k, j+2*l, frame->linesize);
806             yuvClusters += 24;
807         }
808 }
809
810 static int generate_codebook(RoqEncContext *enc, RoqTempdata *tempdata,
811                              int *points, int inputCount, roq_cell *results,
812                              int size, int cbsize)
813 {
814     int i, j, k, ret = 0;
815     int c_size = size*size/4;
816     int *buf;
817     int *codebook = av_malloc_array(6*c_size, cbsize*sizeof(int));
818     int *closest_cb;
819
820     if (!codebook)
821         return AVERROR(ENOMEM);
822
823     if (size == 4) {
824         closest_cb = av_malloc_array(6*c_size, inputCount*sizeof(int));
825         if (!closest_cb) {
826             ret = AVERROR(ENOMEM);
827             goto out;
828         }
829     } else
830         closest_cb = tempdata->closest_cb2;
831
832     ret = avpriv_init_elbg(points, 6 * c_size, inputCount, codebook,
833                        cbsize, 1, closest_cb, &enc->randctx);
834     if (ret < 0)
835         goto out;
836     ret = avpriv_do_elbg(points, 6 * c_size, inputCount, codebook,
837                      cbsize, 1, closest_cb, &enc->randctx);
838     if (ret < 0)
839         goto out;
840
841     buf = codebook;
842     for (i=0; i<cbsize; i++)
843         for (k=0; k<c_size; k++) {
844             for(j=0; j<4; j++)
845                 results->y[j] = *buf++;
846
847             results->u =    (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
848             results->v =    (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
849             results++;
850         }
851 out:
852     if (size == 4)
853         av_free(closest_cb);
854     av_free(codebook);
855     return ret;
856 }
857
858 static int generate_new_codebooks(RoqEncContext *enc, RoqTempdata *tempData)
859 {
860     int i, j, ret = 0;
861     RoqCodebooks *codebooks = &tempData->codebooks;
862     RoqContext *const roq = &enc->common;
863     int max = roq->width * roq->height / 16;
864     uint8_t mb2[3*4];
865     roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
866     uint8_t *yuvClusters=av_malloc_array(max, sizeof(int)*6*4);
867     int *points = av_malloc_array(max, 6*4*sizeof(int));
868     int bias;
869
870     if (!results4 || !yuvClusters || !points) {
871         ret = AVERROR(ENOMEM);
872         goto out;
873     }
874
875     /* Subsample YUV data */
876     create_clusters(enc->frame_to_enc, roq->width, roq->height, yuvClusters);
877
878     /* Cast to integer and apply chroma bias */
879     for (i=0; i<max*24; i++) {
880         bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
881         points[i] = bias*yuvClusters[i];
882     }
883
884     /* Create 4x4 codebooks */
885     if ((ret = generate_codebook(enc, tempData, points, max,
886                                  results4, 4, (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4))) < 0)
887         goto out;
888
889     codebooks->numCB4 = (enc->quake3_compat ? MAX_CBS_4x4-1 : MAX_CBS_4x4);
890
891     tempData->closest_cb2 = av_malloc_array(max, 4*sizeof(int));
892     if (!tempData->closest_cb2) {
893         ret = AVERROR(ENOMEM);
894         goto out;
895     }
896
897     /* Create 2x2 codebooks */
898     if ((ret = generate_codebook(enc, tempData, points, max * 4,
899                                  roq->cb2x2, 2, MAX_CBS_2x2)) < 0)
900         goto out;
901
902     codebooks->numCB2 = MAX_CBS_2x2;
903
904     /* Unpack 2x2 codebook clusters */
905     for (i=0; i<codebooks->numCB2; i++)
906         unpack_roq_cell(roq->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
907
908     /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
909     for (i=0; i<codebooks->numCB4; i++) {
910         for (j=0; j<4; j++) {
911             unpack_roq_cell(&results4[4*i + j], mb2);
912             index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
913                      &roq->cb4x4[i].idx[j], 2);
914         }
915         unpack_roq_qcell(codebooks->unpacked_cb2, roq->cb4x4 + i,
916                          codebooks->unpacked_cb4 + i*4*4*3);
917         enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
918                         codebooks->unpacked_cb4_enlarged + i*8*8*3);
919     }
920 out:
921     av_free(yuvClusters);
922     av_free(points);
923     av_free(results4);
924     return ret;
925 }
926
927 static int roq_encode_video(RoqEncContext *enc)
928 {
929     RoqTempdata *tempData = enc->tmpData;
930     RoqContext *const roq = &enc->common;
931     int ret;
932
933     memset(tempData, 0, sizeof(*tempData));
934
935     ret = create_cel_evals(roq, tempData);
936     if (ret < 0)
937         return ret;
938
939     ret = generate_new_codebooks(enc, tempData);
940     if (ret < 0)
941         return ret;
942
943     if (enc->framesSinceKeyframe >= 1) {
944         motion_search(enc, 8);
945         motion_search(enc, 4);
946     }
947
948  retry_encode:
949     for (int i = 0; i < roq->width * roq->height / 64; i++)
950         gather_data_for_cel(tempData->cel_evals + i, enc, tempData);
951
952     /* Quake 3 can't handle chunks bigger than 65535 bytes */
953     if (tempData->mainChunkSize/8 > 65535 && enc->quake3_compat) {
954         if (enc->lambda > 100000) {
955             av_log(roq->avctx, AV_LOG_ERROR, "Cannot encode video in Quake compatible form\n");
956             return AVERROR(EINVAL);
957         }
958         av_log(roq->avctx, AV_LOG_ERROR,
959                "Warning, generated a frame too big for Quake (%d > 65535), "
960                "now switching to a bigger qscale value.\n",
961                tempData->mainChunkSize/8);
962         enc->lambda *= 1.5;
963         tempData->mainChunkSize = 0;
964         memset(tempData->used_option, 0, sizeof(tempData->used_option));
965         memset(tempData->codebooks.usedCB4, 0,
966                sizeof(tempData->codebooks.usedCB4));
967         memset(tempData->codebooks.usedCB2, 0,
968                sizeof(tempData->codebooks.usedCB2));
969
970         goto retry_encode;
971     }
972
973     remap_codebooks(enc, tempData);
974
975     write_codebooks(enc, tempData);
976
977     reconstruct_and_encode_image(enc, tempData, roq->width, roq->height,
978                                  roq->width * roq->height / 64);
979
980     /* Rotate frame history */
981     FFSWAP(AVFrame *,    roq->current_frame,   roq->last_frame);
982     FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
983     FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
984
985     av_freep(&tempData->cel_evals);
986     av_freep(&tempData->closest_cb2);
987
988     enc->framesSinceKeyframe++;
989
990     return 0;
991 }
992
993 static av_cold int roq_encode_end(AVCodecContext *avctx)
994 {
995     RoqEncContext *const enc = avctx->priv_data;
996
997     av_frame_free(&enc->common.current_frame);
998     av_frame_free(&enc->common.last_frame);
999
1000     av_freep(&enc->tmpData);
1001     av_freep(&enc->this_motion4);
1002     av_freep(&enc->last_motion4);
1003     av_freep(&enc->this_motion8);
1004     av_freep(&enc->last_motion8);
1005
1006     return 0;
1007 }
1008
1009 static av_cold int roq_encode_init(AVCodecContext *avctx)
1010 {
1011     RoqEncContext *const enc = avctx->priv_data;
1012     RoqContext    *const roq = &enc->common;
1013
1014     av_lfg_init(&enc->randctx, 1);
1015
1016     roq->avctx = avctx;
1017
1018     enc->framesSinceKeyframe = 0;
1019     if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
1020         av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
1021         return AVERROR(EINVAL);
1022     }
1023
1024     if (avctx->width > 65535 || avctx->height > 65535) {
1025         av_log(avctx, AV_LOG_ERROR, "Dimensions are max %d\n", enc->quake3_compat ? 32768 : 65535);
1026         return AVERROR(EINVAL);
1027     }
1028
1029     if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
1030         av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two, this is not supported by quake\n");
1031
1032     roq->width  = avctx->width;
1033     roq->height = avctx->height;
1034
1035     enc->framesSinceKeyframe = 0;
1036     enc->first_frame = 1;
1037
1038     roq->last_frame    = av_frame_alloc();
1039     roq->current_frame = av_frame_alloc();
1040     if (!roq->last_frame || !roq->current_frame)
1041         return AVERROR(ENOMEM);
1042
1043     enc->tmpData      = av_malloc(sizeof(RoqTempdata));
1044
1045     enc->this_motion4 =
1046         av_mallocz_array(roq->width * roq->height / 16, sizeof(motion_vect));
1047
1048     enc->last_motion4 =
1049         av_malloc_array (roq->width * roq->height / 16, sizeof(motion_vect));
1050
1051     enc->this_motion8 =
1052         av_mallocz_array(roq->width * roq->height / 64, sizeof(motion_vect));
1053
1054     enc->last_motion8 =
1055         av_malloc_array (roq->width * roq->height / 64, sizeof(motion_vect));
1056
1057     if (!enc->tmpData || !enc->this_motion4 || !enc->last_motion4 ||
1058         !enc->this_motion8 || !enc->last_motion8)
1059         return AVERROR(ENOMEM);
1060
1061     return 0;
1062 }
1063
1064 static void roq_write_video_info_chunk(RoqEncContext *enc)
1065 {
1066     /* ROQ info chunk */
1067     bytestream_put_le16(&enc->out_buf, RoQ_INFO);
1068
1069     /* Size: 8 bytes */
1070     bytestream_put_le32(&enc->out_buf, 8);
1071
1072     /* Unused argument */
1073     bytestream_put_byte(&enc->out_buf, 0x00);
1074     bytestream_put_byte(&enc->out_buf, 0x00);
1075
1076     /* Width */
1077     bytestream_put_le16(&enc->out_buf, enc->common.width);
1078
1079     /* Height */
1080     bytestream_put_le16(&enc->out_buf, enc->common.height);
1081
1082     /* Unused in Quake 3, mimics the output of the real encoder */
1083     bytestream_put_byte(&enc->out_buf, 0x08);
1084     bytestream_put_byte(&enc->out_buf, 0x00);
1085     bytestream_put_byte(&enc->out_buf, 0x04);
1086     bytestream_put_byte(&enc->out_buf, 0x00);
1087 }
1088
1089 static int roq_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1090                             const AVFrame *frame, int *got_packet)
1091 {
1092     RoqEncContext *const enc = avctx->priv_data;
1093     RoqContext    *const roq = &enc->common;
1094     int size, ret;
1095
1096     roq->avctx = avctx;
1097
1098     enc->frame_to_enc = frame;
1099
1100     if (frame->quality)
1101         enc->lambda = frame->quality - 1;
1102     else
1103         enc->lambda = 2*ROQ_LAMBDA_SCALE;
1104
1105     /* 138 bits max per 8x8 block +
1106      *     256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
1107     size = ((roq->width * roq->height / 64) * 138 + 7) / 8 + 256 * (6 + 4) + 8;
1108     if ((ret = ff_alloc_packet2(avctx, pkt, size, 0)) < 0)
1109         return ret;
1110     enc->out_buf = pkt->data;
1111
1112     /* Check for I-frame */
1113     if (enc->framesSinceKeyframe == avctx->gop_size)
1114         enc->framesSinceKeyframe = 0;
1115
1116     if (enc->first_frame) {
1117         /* Alloc memory for the reconstruction data (we must know the stride
1118          for that) */
1119         if ((ret = ff_get_buffer(avctx, roq->current_frame, 0)) < 0 ||
1120             (ret = ff_get_buffer(avctx, roq->last_frame,    0)) < 0)
1121             return ret;
1122
1123         /* Before the first video frame, write a "video info" chunk */
1124         roq_write_video_info_chunk(enc);
1125
1126         enc->first_frame = 0;
1127     }
1128
1129     /* Encode the actual frame */
1130     ret = roq_encode_video(enc);
1131     if (ret < 0)
1132         return ret;
1133
1134     pkt->size   = enc->out_buf - pkt->data;
1135     if (enc->framesSinceKeyframe == 1)
1136         pkt->flags |= AV_PKT_FLAG_KEY;
1137     *got_packet = 1;
1138
1139     return 0;
1140 }
1141
1142 #define OFFSET(x) offsetof(RoqEncContext, x)
1143 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1144 static const AVOption options[] = {
1145     { "quake3_compat", "Whether to respect known limitations in Quake 3 decoder", OFFSET(quake3_compat), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, VE },
1146     { NULL },
1147 };
1148
1149 static const AVClass roq_class = {
1150     .class_name = "RoQ",
1151     .item_name  = av_default_item_name,
1152     .option     = options,
1153     .version    = LIBAVUTIL_VERSION_INT,
1154 };
1155
1156 AVCodec ff_roq_encoder = {
1157     .name                 = "roqvideo",
1158     .long_name            = NULL_IF_CONFIG_SMALL("id RoQ video"),
1159     .type                 = AVMEDIA_TYPE_VIDEO,
1160     .id                   = AV_CODEC_ID_ROQ,
1161     .priv_data_size       = sizeof(RoqEncContext),
1162     .init                 = roq_encode_init,
1163     .encode2              = roq_encode_frame,
1164     .close                = roq_encode_end,
1165     .pix_fmts             = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUVJ444P,
1166                                                         AV_PIX_FMT_NONE },
1167     .priv_class     = &roq_class,
1168     .caps_internal        = FF_CODEC_CAP_INIT_CLEANUP,
1169 };