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