roqvideoenc.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. * @file libavcodec/roqvideoenc.c
  26. * id RoQ encoder by Vitor. Based on the Switchblade3 library and the
  27. * Switchblade3 FFmpeg glue by Eric Lasota.
  28. */
  29. /*
  30. * COSTS:
  31. * Level 1:
  32. * SKIP - 2 bits
  33. * MOTION - 2 + 8 bits
  34. * CODEBOOK - 2 + 8 bits
  35. * SUBDIVIDE - 2 + combined subcel cost
  36. *
  37. * Level 2:
  38. * SKIP - 2 bits
  39. * MOTION - 2 + 8 bits
  40. * CODEBOOK - 2 + 8 bits
  41. * SUBDIVIDE - 2 + 4*8 bits
  42. *
  43. * Maximum cost: 138 bits per cel
  44. *
  45. * Proper evaluation requires LCD fraction comparison, which requires
  46. * Squared Error (SE) loss * savings increase
  47. *
  48. * Maximum savings increase: 136 bits
  49. * Maximum SE loss without overflow: 31580641
  50. * Components in 8x8 supercel: 192
  51. * Maximum SE precision per component: 164482
  52. * >65025, so no truncation is needed (phew)
  53. */
  54. #include <string.h>
  55. #include <unistd.h>
  56. #include "roqvideo.h"
  57. #include "bytestream.h"
  58. #include "elbg.h"
  59. #include "mathops.h"
  60. #define CHROMA_BIAS 1
  61. /**
  62. * Maximum number of generated 4x4 codebooks. Can't be 256 to workaround a
  63. * Quake 3 bug.
  64. */
  65. #define MAX_CBS_4x4 255
  66. #define MAX_CBS_2x2 256 ///< Maximum number of 2x2 codebooks.
  67. /* The cast is useful when multiplying it by INT_MAX */
  68. #define ROQ_LAMBDA_SCALE ((uint64_t) FF_LAMBDA_SCALE)
  69. /* Macroblock support functions */
  70. static void unpack_roq_cell(roq_cell *cell, uint8_t u[4*3])
  71. {
  72. memcpy(u , cell->y, 4);
  73. memset(u+4, cell->u, 4);
  74. memset(u+8, cell->v, 4);
  75. }
  76. static void unpack_roq_qcell(uint8_t cb2[], roq_qcell *qcell, uint8_t u[4*4*3])
  77. {
  78. int i,cp;
  79. static const int offsets[4] = {0, 2, 8, 10};
  80. for (cp=0; cp<3; cp++)
  81. for (i=0; i<4; i++) {
  82. u[4*4*cp + offsets[i] ] = cb2[qcell->idx[i]*2*2*3 + 4*cp ];
  83. u[4*4*cp + offsets[i]+1] = cb2[qcell->idx[i]*2*2*3 + 4*cp+1];
  84. u[4*4*cp + offsets[i]+4] = cb2[qcell->idx[i]*2*2*3 + 4*cp+2];
  85. u[4*4*cp + offsets[i]+5] = cb2[qcell->idx[i]*2*2*3 + 4*cp+3];
  86. }
  87. }
  88. static void enlarge_roq_mb4(uint8_t base[3*16], uint8_t u[3*64])
  89. {
  90. int x,y,cp;
  91. for(cp=0; cp<3; cp++)
  92. for(y=0; y<8; y++)
  93. for(x=0; x<8; x++)
  94. *u++ = base[(y/2)*4 + (x/2) + 16*cp];
  95. }
  96. static inline int square(int x)
  97. {
  98. return x*x;
  99. }
  100. static inline int eval_sse(uint8_t *a, uint8_t *b, int count)
  101. {
  102. int diff=0;
  103. while(count--)
  104. diff += square(*b++ - *a++);
  105. return diff;
  106. }
  107. // FIXME Could use DSPContext.sse, but it is not so speed critical (used
  108. // just for motion estimation).
  109. static int block_sse(uint8_t **buf1, uint8_t **buf2, int x1, int y1, int x2,
  110. int y2, int *stride1, int *stride2, int size)
  111. {
  112. int i, k;
  113. int sse=0;
  114. for (k=0; k<3; k++) {
  115. int bias = (k ? CHROMA_BIAS : 4);
  116. for (i=0; i<size; i++)
  117. sse += bias*eval_sse(buf1[k] + (y1+i)*stride1[k] + x1,
  118. buf2[k] + (y2+i)*stride2[k] + x2, size);
  119. }
  120. return sse;
  121. }
  122. static int eval_motion_dist(RoqContext *enc, int x, int y, motion_vect vect,
  123. int size)
  124. {
  125. int mx=vect.d[0];
  126. int my=vect.d[1];
  127. if (mx < -7 || mx > 7)
  128. return INT_MAX;
  129. if (my < -7 || my > 7)
  130. return INT_MAX;
  131. mx += x;
  132. my += y;
  133. if ((unsigned) mx > enc->width-size || (unsigned) my > enc->height-size)
  134. return INT_MAX;
  135. return block_sse(enc->frame_to_enc->data, enc->last_frame->data, x, y,
  136. mx, my,
  137. enc->frame_to_enc->linesize, enc->last_frame->linesize,
  138. size);
  139. }
  140. /**
  141. * Returns distortion between two macroblocks
  142. */
  143. static inline int squared_diff_macroblock(uint8_t a[], uint8_t b[], int size)
  144. {
  145. int cp, sdiff=0;
  146. for(cp=0;cp<3;cp++) {
  147. int bias = (cp ? CHROMA_BIAS : 4);
  148. sdiff += bias*eval_sse(a, b, size*size);
  149. a += size*size;
  150. b += size*size;
  151. }
  152. return sdiff;
  153. }
  154. typedef struct
  155. {
  156. int eval_dist[4];
  157. int best_bit_use;
  158. int best_coding;
  159. int subCels[4];
  160. motion_vect motion;
  161. int cbEntry;
  162. } SubcelEvaluation;
  163. typedef struct
  164. {
  165. int eval_dist[4];
  166. int best_coding;
  167. SubcelEvaluation subCels[4];
  168. motion_vect motion;
  169. int cbEntry;
  170. int sourceX, sourceY;
  171. } CelEvaluation;
  172. typedef struct
  173. {
  174. int numCB4;
  175. int numCB2;
  176. int usedCB2[MAX_CBS_2x2];
  177. int usedCB4[MAX_CBS_4x4];
  178. uint8_t unpacked_cb2[MAX_CBS_2x2*2*2*3];
  179. uint8_t unpacked_cb4[MAX_CBS_4x4*4*4*3];
  180. uint8_t unpacked_cb4_enlarged[MAX_CBS_4x4*8*8*3];
  181. } RoqCodebooks;
  182. /**
  183. * Temporary vars
  184. */
  185. typedef struct RoqTempData
  186. {
  187. CelEvaluation *cel_evals;
  188. int f2i4[MAX_CBS_4x4];
  189. int i2f4[MAX_CBS_4x4];
  190. int f2i2[MAX_CBS_2x2];
  191. int i2f2[MAX_CBS_2x2];
  192. int mainChunkSize;
  193. int numCB4;
  194. int numCB2;
  195. RoqCodebooks codebooks;
  196. int *closest_cb2;
  197. int used_option[4];
  198. } RoqTempdata;
  199. /**
  200. * Initializes cel evaluators and sets their source coordinates
  201. */
  202. static void create_cel_evals(RoqContext *enc, RoqTempdata *tempData)
  203. {
  204. int n=0, x, y, i;
  205. tempData->cel_evals = av_malloc(enc->width*enc->height/64 * sizeof(CelEvaluation));
  206. /* Map to the ROQ quadtree order */
  207. for (y=0; y<enc->height; y+=16)
  208. for (x=0; x<enc->width; x+=16)
  209. for(i=0; i<4; i++) {
  210. tempData->cel_evals[n ].sourceX = x + (i&1)*8;
  211. tempData->cel_evals[n++].sourceY = y + (i&2)*4;
  212. }
  213. }
  214. /**
  215. * Get macroblocks from parts of the image
  216. */
  217. static void get_frame_mb(AVFrame *frame, int x, int y, uint8_t mb[], int dim)
  218. {
  219. int i, j, cp;
  220. for (cp=0; cp<3; cp++) {
  221. int stride = frame->linesize[cp];
  222. for (i=0; i<dim; i++)
  223. for (j=0; j<dim; j++)
  224. *mb++ = frame->data[cp][(y+i)*stride + x + j];
  225. }
  226. }
  227. /**
  228. * Find the codebook with the lowest distortion from an image
  229. */
  230. static int index_mb(uint8_t cluster[], uint8_t cb[], int numCB,
  231. int *outIndex, int dim)
  232. {
  233. int i, lDiff = INT_MAX, pick=0;
  234. /* Diff against the others */
  235. for (i=0; i<numCB; i++) {
  236. int diff = squared_diff_macroblock(cluster, cb + i*dim*dim*3, dim);
  237. if (diff < lDiff) {
  238. lDiff = diff;
  239. pick = i;
  240. }
  241. }
  242. *outIndex = pick;
  243. return lDiff;
  244. }
  245. #define EVAL_MOTION(MOTION) \
  246. do { \
  247. diff = eval_motion_dist(enc, j, i, MOTION, blocksize); \
  248. \
  249. if (diff < lowestdiff) { \
  250. lowestdiff = diff; \
  251. bestpick = MOTION; \
  252. } \
  253. } while(0)
  254. static void motion_search(RoqContext *enc, int blocksize)
  255. {
  256. static const motion_vect offsets[8] = {
  257. {{ 0,-1}},
  258. {{ 0, 1}},
  259. {{-1, 0}},
  260. {{ 1, 0}},
  261. {{-1, 1}},
  262. {{ 1,-1}},
  263. {{-1,-1}},
  264. {{ 1, 1}},
  265. };
  266. int diff, lowestdiff, oldbest;
  267. int off[3];
  268. motion_vect bestpick = {{0,0}};
  269. int i, j, k, offset;
  270. motion_vect *last_motion;
  271. motion_vect *this_motion;
  272. motion_vect vect, vect2;
  273. int max=(enc->width/blocksize)*enc->height/blocksize;
  274. if (blocksize == 4) {
  275. last_motion = enc->last_motion4;
  276. this_motion = enc->this_motion4;
  277. } else {
  278. last_motion = enc->last_motion8;
  279. this_motion = enc->this_motion8;
  280. }
  281. for (i=0; i<enc->height; i+=blocksize)
  282. for (j=0; j<enc->width; j+=blocksize) {
  283. lowestdiff = eval_motion_dist(enc, j, i, (motion_vect) {{0,0}},
  284. blocksize);
  285. bestpick.d[0] = 0;
  286. bestpick.d[1] = 0;
  287. if (blocksize == 4)
  288. EVAL_MOTION(enc->this_motion8[(i/8)*(enc->width/8) + j/8]);
  289. offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
  290. if (offset < max && offset >= 0)
  291. EVAL_MOTION(last_motion[offset]);
  292. offset++;
  293. if (offset < max && offset >= 0)
  294. EVAL_MOTION(last_motion[offset]);
  295. offset = (i/blocksize + 1)*enc->width/blocksize + j/blocksize;
  296. if (offset < max && offset >= 0)
  297. EVAL_MOTION(last_motion[offset]);
  298. off[0]= (i/blocksize)*enc->width/blocksize + j/blocksize - 1;
  299. off[1]= off[0] - enc->width/blocksize + 1;
  300. off[2]= off[1] + 1;
  301. if (i) {
  302. for(k=0; k<2; k++)
  303. vect.d[k]= mid_pred(this_motion[off[0]].d[k],
  304. this_motion[off[1]].d[k],
  305. this_motion[off[2]].d[k]);
  306. EVAL_MOTION(vect);
  307. for(k=0; k<3; k++)
  308. EVAL_MOTION(this_motion[off[k]]);
  309. } else if(j)
  310. EVAL_MOTION(this_motion[off[0]]);
  311. vect = bestpick;
  312. oldbest = -1;
  313. while (oldbest != lowestdiff) {
  314. oldbest = lowestdiff;
  315. for (k=0; k<8; k++) {
  316. vect2 = vect;
  317. vect2.d[0] += offsets[k].d[0];
  318. vect2.d[1] += offsets[k].d[1];
  319. EVAL_MOTION(vect2);
  320. }
  321. vect = bestpick;
  322. }
  323. offset = (i/blocksize)*enc->width/blocksize + j/blocksize;
  324. this_motion[offset] = bestpick;
  325. }
  326. }
  327. /**
  328. * Gets distortion for all options available to a subcel
  329. */
  330. static void gather_data_for_subcel(SubcelEvaluation *subcel, int x,
  331. int y, RoqContext *enc, RoqTempdata *tempData)
  332. {
  333. uint8_t mb4[4*4*3];
  334. uint8_t mb2[2*2*3];
  335. int cluster_index;
  336. int i, best_dist;
  337. static const int bitsUsed[4] = {2, 10, 10, 34};
  338. if (enc->framesSinceKeyframe >= 1) {
  339. subcel->motion = enc->this_motion4[y*enc->width/16 + x/4];
  340. subcel->eval_dist[RoQ_ID_FCC] =
  341. eval_motion_dist(enc, x, y,
  342. enc->this_motion4[y*enc->width/16 + x/4], 4);
  343. } else
  344. subcel->eval_dist[RoQ_ID_FCC] = INT_MAX;
  345. if (enc->framesSinceKeyframe >= 2)
  346. subcel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
  347. enc->current_frame->data, x,
  348. y, x, y,
  349. enc->frame_to_enc->linesize,
  350. enc->current_frame->linesize,
  351. 4);
  352. else
  353. subcel->eval_dist[RoQ_ID_MOT] = INT_MAX;
  354. cluster_index = y*enc->width/16 + x/4;
  355. get_frame_mb(enc->frame_to_enc, x, y, mb4, 4);
  356. subcel->eval_dist[RoQ_ID_SLD] = index_mb(mb4,
  357. tempData->codebooks.unpacked_cb4,
  358. tempData->codebooks.numCB4,
  359. &subcel->cbEntry, 4);
  360. subcel->eval_dist[RoQ_ID_CCC] = 0;
  361. for(i=0;i<4;i++) {
  362. subcel->subCels[i] = tempData->closest_cb2[cluster_index*4+i];
  363. get_frame_mb(enc->frame_to_enc, x+2*(i&1),
  364. y+(i&2), mb2, 2);
  365. subcel->eval_dist[RoQ_ID_CCC] +=
  366. squared_diff_macroblock(tempData->codebooks.unpacked_cb2 + subcel->subCels[i]*2*2*3, mb2, 2);
  367. }
  368. best_dist = INT_MAX;
  369. for (i=0; i<4; i++)
  370. if (ROQ_LAMBDA_SCALE*subcel->eval_dist[i] + enc->lambda*bitsUsed[i] <
  371. best_dist) {
  372. subcel->best_coding = i;
  373. subcel->best_bit_use = bitsUsed[i];
  374. best_dist = ROQ_LAMBDA_SCALE*subcel->eval_dist[i] +
  375. enc->lambda*bitsUsed[i];
  376. }
  377. }
  378. /**
  379. * Gets distortion for all options available to a cel
  380. */
  381. static void gather_data_for_cel(CelEvaluation *cel, RoqContext *enc,
  382. RoqTempdata *tempData)
  383. {
  384. uint8_t mb8[8*8*3];
  385. int index = cel->sourceY*enc->width/64 + cel->sourceX/8;
  386. int i, j, best_dist, divide_bit_use;
  387. int bitsUsed[4] = {2, 10, 10, 0};
  388. if (enc->framesSinceKeyframe >= 1) {
  389. cel->motion = enc->this_motion8[index];
  390. cel->eval_dist[RoQ_ID_FCC] =
  391. eval_motion_dist(enc, cel->sourceX, cel->sourceY,
  392. enc->this_motion8[index], 8);
  393. } else
  394. cel->eval_dist[RoQ_ID_FCC] = INT_MAX;
  395. if (enc->framesSinceKeyframe >= 2)
  396. cel->eval_dist[RoQ_ID_MOT] = block_sse(enc->frame_to_enc->data,
  397. enc->current_frame->data,
  398. cel->sourceX, cel->sourceY,
  399. cel->sourceX, cel->sourceY,
  400. enc->frame_to_enc->linesize,
  401. enc->current_frame->linesize,8);
  402. else
  403. cel->eval_dist[RoQ_ID_MOT] = INT_MAX;
  404. get_frame_mb(enc->frame_to_enc, cel->sourceX, cel->sourceY, mb8, 8);
  405. cel->eval_dist[RoQ_ID_SLD] =
  406. index_mb(mb8, tempData->codebooks.unpacked_cb4_enlarged,
  407. tempData->codebooks.numCB4, &cel->cbEntry, 8);
  408. gather_data_for_subcel(cel->subCels + 0, cel->sourceX+0, cel->sourceY+0, enc, tempData);
  409. gather_data_for_subcel(cel->subCels + 1, cel->sourceX+4, cel->sourceY+0, enc, tempData);
  410. gather_data_for_subcel(cel->subCels + 2, cel->sourceX+0, cel->sourceY+4, enc, tempData);
  411. gather_data_for_subcel(cel->subCels + 3, cel->sourceX+4, cel->sourceY+4, enc, tempData);
  412. cel->eval_dist[RoQ_ID_CCC] = 0;
  413. divide_bit_use = 0;
  414. for (i=0; i<4; i++) {
  415. cel->eval_dist[RoQ_ID_CCC] +=
  416. cel->subCels[i].eval_dist[cel->subCels[i].best_coding];
  417. divide_bit_use += cel->subCels[i].best_bit_use;
  418. }
  419. best_dist = INT_MAX;
  420. bitsUsed[3] = 2 + divide_bit_use;
  421. for (i=0; i<4; i++)
  422. if (ROQ_LAMBDA_SCALE*cel->eval_dist[i] + enc->lambda*bitsUsed[i] <
  423. best_dist) {
  424. cel->best_coding = i;
  425. best_dist = ROQ_LAMBDA_SCALE*cel->eval_dist[i] +
  426. enc->lambda*bitsUsed[i];
  427. }
  428. tempData->used_option[cel->best_coding]++;
  429. tempData->mainChunkSize += bitsUsed[cel->best_coding];
  430. if (cel->best_coding == RoQ_ID_SLD)
  431. tempData->codebooks.usedCB4[cel->cbEntry]++;
  432. if (cel->best_coding == RoQ_ID_CCC)
  433. for (i=0; i<4; i++) {
  434. if (cel->subCels[i].best_coding == RoQ_ID_SLD)
  435. tempData->codebooks.usedCB4[cel->subCels[i].cbEntry]++;
  436. else if (cel->subCels[i].best_coding == RoQ_ID_CCC)
  437. for (j=0; j<4; j++)
  438. tempData->codebooks.usedCB2[cel->subCels[i].subCels[j]]++;
  439. }
  440. }
  441. static void remap_codebooks(RoqContext *enc, RoqTempdata *tempData)
  442. {
  443. int i, j, idx=0;
  444. /* Make remaps for the final codebook usage */
  445. for (i=0; i<MAX_CBS_4x4; i++) {
  446. if (tempData->codebooks.usedCB4[i]) {
  447. tempData->i2f4[i] = idx;
  448. tempData->f2i4[idx] = i;
  449. for (j=0; j<4; j++)
  450. tempData->codebooks.usedCB2[enc->cb4x4[i].idx[j]]++;
  451. idx++;
  452. }
  453. }
  454. tempData->numCB4 = idx;
  455. idx = 0;
  456. for (i=0; i<MAX_CBS_2x2; i++) {
  457. if (tempData->codebooks.usedCB2[i]) {
  458. tempData->i2f2[i] = idx;
  459. tempData->f2i2[idx] = i;
  460. idx++;
  461. }
  462. }
  463. tempData->numCB2 = idx;
  464. }
  465. /**
  466. * Write codebook chunk
  467. */
  468. static void write_codebooks(RoqContext *enc, RoqTempdata *tempData)
  469. {
  470. int i, j;
  471. uint8_t **outp= &enc->out_buf;
  472. if (tempData->numCB2) {
  473. bytestream_put_le16(outp, RoQ_QUAD_CODEBOOK);
  474. bytestream_put_le32(outp, tempData->numCB2*6 + tempData->numCB4*4);
  475. bytestream_put_byte(outp, tempData->numCB4);
  476. bytestream_put_byte(outp, tempData->numCB2);
  477. for (i=0; i<tempData->numCB2; i++) {
  478. bytestream_put_buffer(outp, enc->cb2x2[tempData->f2i2[i]].y, 4);
  479. bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].u);
  480. bytestream_put_byte(outp, enc->cb2x2[tempData->f2i2[i]].v);
  481. }
  482. for (i=0; i<tempData->numCB4; i++)
  483. for (j=0; j<4; j++)
  484. bytestream_put_byte(outp, tempData->i2f2[enc->cb4x4[tempData->f2i4[i]].idx[j]]);
  485. }
  486. }
  487. static inline uint8_t motion_arg(motion_vect mot)
  488. {
  489. uint8_t ax = 8 - ((uint8_t) mot.d[0]);
  490. uint8_t ay = 8 - ((uint8_t) mot.d[1]);
  491. return ((ax&15)<<4) | (ay&15);
  492. }
  493. typedef struct
  494. {
  495. int typeSpool;
  496. int typeSpoolLength;
  497. uint8_t argumentSpool[64];
  498. uint8_t *args;
  499. uint8_t **pout;
  500. } CodingSpool;
  501. /* NOTE: Typecodes must be spooled AFTER arguments!! */
  502. static void write_typecode(CodingSpool *s, uint8_t type)
  503. {
  504. s->typeSpool |= (type & 3) << (14 - s->typeSpoolLength);
  505. s->typeSpoolLength += 2;
  506. if (s->typeSpoolLength == 16) {
  507. bytestream_put_le16(s->pout, s->typeSpool);
  508. bytestream_put_buffer(s->pout, s->argumentSpool,
  509. s->args - s->argumentSpool);
  510. s->typeSpoolLength = 0;
  511. s->typeSpool = 0;
  512. s->args = s->argumentSpool;
  513. }
  514. }
  515. static void reconstruct_and_encode_image(RoqContext *enc, RoqTempdata *tempData, int w, int h, int numBlocks)
  516. {
  517. int i, j, k;
  518. int x, y;
  519. int subX, subY;
  520. int dist=0;
  521. roq_qcell *qcell;
  522. CelEvaluation *eval;
  523. CodingSpool spool;
  524. spool.typeSpool=0;
  525. spool.typeSpoolLength=0;
  526. spool.args = spool.argumentSpool;
  527. spool.pout = &enc->out_buf;
  528. if (tempData->used_option[RoQ_ID_CCC]%2)
  529. tempData->mainChunkSize+=8; //FIXME
  530. /* Write the video chunk header */
  531. bytestream_put_le16(&enc->out_buf, RoQ_QUAD_VQ);
  532. bytestream_put_le32(&enc->out_buf, tempData->mainChunkSize/8);
  533. bytestream_put_byte(&enc->out_buf, 0x0);
  534. bytestream_put_byte(&enc->out_buf, 0x0);
  535. for (i=0; i<numBlocks; i++) {
  536. eval = tempData->cel_evals + i;
  537. x = eval->sourceX;
  538. y = eval->sourceY;
  539. dist += eval->eval_dist[eval->best_coding];
  540. switch (eval->best_coding) {
  541. case RoQ_ID_MOT:
  542. write_typecode(&spool, RoQ_ID_MOT);
  543. break;
  544. case RoQ_ID_FCC:
  545. bytestream_put_byte(&spool.args, motion_arg(eval->motion));
  546. write_typecode(&spool, RoQ_ID_FCC);
  547. ff_apply_motion_8x8(enc, x, y,
  548. eval->motion.d[0], eval->motion.d[1]);
  549. break;
  550. case RoQ_ID_SLD:
  551. bytestream_put_byte(&spool.args, tempData->i2f4[eval->cbEntry]);
  552. write_typecode(&spool, RoQ_ID_SLD);
  553. qcell = enc->cb4x4 + eval->cbEntry;
  554. ff_apply_vector_4x4(enc, x , y , enc->cb2x2 + qcell->idx[0]);
  555. ff_apply_vector_4x4(enc, x+4, y , enc->cb2x2 + qcell->idx[1]);
  556. ff_apply_vector_4x4(enc, x , y+4, enc->cb2x2 + qcell->idx[2]);
  557. ff_apply_vector_4x4(enc, x+4, y+4, enc->cb2x2 + qcell->idx[3]);
  558. break;
  559. case RoQ_ID_CCC:
  560. write_typecode(&spool, RoQ_ID_CCC);
  561. for (j=0; j<4; j++) {
  562. subX = x + 4*(j&1);
  563. subY = y + 2*(j&2);
  564. switch(eval->subCels[j].best_coding) {
  565. case RoQ_ID_MOT:
  566. break;
  567. case RoQ_ID_FCC:
  568. bytestream_put_byte(&spool.args,
  569. motion_arg(eval->subCels[j].motion));
  570. ff_apply_motion_4x4(enc, subX, subY,
  571. eval->subCels[j].motion.d[0],
  572. eval->subCels[j].motion.d[1]);
  573. break;
  574. case RoQ_ID_SLD:
  575. bytestream_put_byte(&spool.args,
  576. tempData->i2f4[eval->subCels[j].cbEntry]);
  577. qcell = enc->cb4x4 + eval->subCels[j].cbEntry;
  578. ff_apply_vector_2x2(enc, subX , subY ,
  579. enc->cb2x2 + qcell->idx[0]);
  580. ff_apply_vector_2x2(enc, subX+2, subY ,
  581. enc->cb2x2 + qcell->idx[1]);
  582. ff_apply_vector_2x2(enc, subX , subY+2,
  583. enc->cb2x2 + qcell->idx[2]);
  584. ff_apply_vector_2x2(enc, subX+2, subY+2,
  585. enc->cb2x2 + qcell->idx[3]);
  586. break;
  587. case RoQ_ID_CCC:
  588. for (k=0; k<4; k++) {
  589. int cb_idx = eval->subCels[j].subCels[k];
  590. bytestream_put_byte(&spool.args,
  591. tempData->i2f2[cb_idx]);
  592. ff_apply_vector_2x2(enc, subX + 2*(k&1), subY + (k&2),
  593. enc->cb2x2 + cb_idx);
  594. }
  595. break;
  596. }
  597. write_typecode(&spool, eval->subCels[j].best_coding);
  598. }
  599. break;
  600. }
  601. }
  602. /* Flush the remainder of the argument/type spool */
  603. while (spool.typeSpoolLength)
  604. write_typecode(&spool, 0x0);
  605. #if 0
  606. uint8_t *fdata[3] = {enc->frame_to_enc->data[0],
  607. enc->frame_to_enc->data[1],
  608. enc->frame_to_enc->data[2]};
  609. uint8_t *cdata[3] = {enc->current_frame->data[0],
  610. enc->current_frame->data[1],
  611. enc->current_frame->data[2]};
  612. av_log(enc->avctx, AV_LOG_ERROR, "Expected distortion: %i Actual: %i\n",
  613. dist,
  614. block_sse(fdata, cdata, 0, 0, 0, 0,
  615. enc->frame_to_enc->linesize,
  616. enc->current_frame->linesize,
  617. enc->width)); //WARNING: Square dimensions implied...
  618. #endif
  619. }
  620. /**
  621. * Create a single YUV cell from a 2x2 section of the image
  622. */
  623. static inline void frame_block_to_cell(uint8_t *block, uint8_t **data,
  624. int top, int left, int *stride)
  625. {
  626. int i, j, u=0, v=0;
  627. for (i=0; i<2; i++)
  628. for (j=0; j<2; j++) {
  629. int x = (top+i)*stride[0] + left + j;
  630. *block++ = data[0][x];
  631. x = (top+i)*stride[1] + left + j;
  632. u += data[1][x];
  633. v += data[2][x];
  634. }
  635. *block++ = (u+2)/4;
  636. *block++ = (v+2)/4;
  637. }
  638. /**
  639. * Creates YUV clusters for the entire image
  640. */
  641. static void create_clusters(AVFrame *frame, int w, int h, uint8_t *yuvClusters)
  642. {
  643. int i, j, k, l;
  644. for (i=0; i<h; i+=4)
  645. for (j=0; j<w; j+=4) {
  646. for (k=0; k < 2; k++)
  647. for (l=0; l < 2; l++)
  648. frame_block_to_cell(yuvClusters + (l + 2*k)*6, frame->data,
  649. i+2*k, j+2*l, frame->linesize);
  650. yuvClusters += 24;
  651. }
  652. }
  653. static void generate_codebook(RoqContext *enc, RoqTempdata *tempdata,
  654. int *points, int inputCount, roq_cell *results,
  655. int size, int cbsize)
  656. {
  657. int i, j, k;
  658. int c_size = size*size/4;
  659. int *buf = points;
  660. int *codebook = av_malloc(6*c_size*cbsize*sizeof(int));
  661. int *closest_cb;
  662. if (size == 4)
  663. closest_cb = av_malloc(6*c_size*inputCount*sizeof(int));
  664. else
  665. closest_cb = tempdata->closest_cb2;
  666. ff_init_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
  667. ff_do_elbg(points, 6*c_size, inputCount, codebook, cbsize, 1, closest_cb, &enc->randctx);
  668. if (size == 4)
  669. av_free(closest_cb);
  670. buf = codebook;
  671. for (i=0; i<cbsize; i++)
  672. for (k=0; k<c_size; k++) {
  673. for(j=0; j<4; j++)
  674. results->y[j] = *buf++;
  675. results->u = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
  676. results->v = (*buf++ + CHROMA_BIAS/2)/CHROMA_BIAS;
  677. results++;
  678. }
  679. av_free(codebook);
  680. }
  681. static void generate_new_codebooks(RoqContext *enc, RoqTempdata *tempData)
  682. {
  683. int i,j;
  684. RoqCodebooks *codebooks = &tempData->codebooks;
  685. int max = enc->width*enc->height/16;
  686. uint8_t mb2[3*4];
  687. roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);
  688. uint8_t *yuvClusters=av_malloc(sizeof(int)*max*6*4);
  689. int *points = av_malloc(max*6*4*sizeof(int));
  690. int bias;
  691. /* Subsample YUV data */
  692. create_clusters(enc->frame_to_enc, enc->width, enc->height, yuvClusters);
  693. /* Cast to integer and apply chroma bias */
  694. for (i=0; i<max*24; i++) {
  695. bias = ((i%6)<4) ? 1 : CHROMA_BIAS;
  696. points[i] = bias*yuvClusters[i];
  697. }
  698. /* Create 4x4 codebooks */
  699. generate_codebook(enc, tempData, points, max, results4, 4, MAX_CBS_4x4);
  700. codebooks->numCB4 = MAX_CBS_4x4;
  701. tempData->closest_cb2 = av_malloc(max*4*sizeof(int));
  702. /* Create 2x2 codebooks */
  703. generate_codebook(enc, tempData, points, max*4, enc->cb2x2, 2, MAX_CBS_2x2);
  704. codebooks->numCB2 = MAX_CBS_2x2;
  705. /* Unpack 2x2 codebook clusters */
  706. for (i=0; i<codebooks->numCB2; i++)
  707. unpack_roq_cell(enc->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);
  708. /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */
  709. for (i=0; i<codebooks->numCB4; i++) {
  710. for (j=0; j<4; j++) {
  711. unpack_roq_cell(&results4[4*i + j], mb2);
  712. index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,
  713. &enc->cb4x4[i].idx[j], 2);
  714. }
  715. unpack_roq_qcell(codebooks->unpacked_cb2, enc->cb4x4 + i,
  716. codebooks->unpacked_cb4 + i*4*4*3);
  717. enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,
  718. codebooks->unpacked_cb4_enlarged + i*8*8*3);
  719. }
  720. av_free(yuvClusters);
  721. av_free(points);
  722. av_free(results4);
  723. }
  724. static void roq_encode_video(RoqContext *enc)
  725. {
  726. RoqTempdata *tempData = enc->tmpData;
  727. int i;
  728. memset(tempData, 0, sizeof(*tempData));
  729. create_cel_evals(enc, tempData);
  730. generate_new_codebooks(enc, tempData);
  731. if (enc->framesSinceKeyframe >= 1) {
  732. motion_search(enc, 8);
  733. motion_search(enc, 4);
  734. }
  735. retry_encode:
  736. for (i=0; i<enc->width*enc->height/64; i++)
  737. gather_data_for_cel(tempData->cel_evals + i, enc, tempData);
  738. /* Quake 3 can't handle chunks bigger than 65536 bytes */
  739. if (tempData->mainChunkSize/8 > 65536) {
  740. enc->lambda *= .8;
  741. goto retry_encode;
  742. }
  743. remap_codebooks(enc, tempData);
  744. write_codebooks(enc, tempData);
  745. reconstruct_and_encode_image(enc, tempData, enc->width, enc->height,
  746. enc->width*enc->height/64);
  747. enc->avctx->coded_frame = enc->current_frame;
  748. /* Rotate frame history */
  749. FFSWAP(AVFrame *, enc->current_frame, enc->last_frame);
  750. FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);
  751. FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);
  752. av_free(tempData->cel_evals);
  753. av_free(tempData->closest_cb2);
  754. enc->framesSinceKeyframe++;
  755. }
  756. static int roq_encode_init(AVCodecContext *avctx)
  757. {
  758. RoqContext *enc = avctx->priv_data;
  759. av_random_init(&enc->randctx, 1);
  760. enc->framesSinceKeyframe = 0;
  761. if ((avctx->width & 0xf) || (avctx->height & 0xf)) {
  762. av_log(avctx, AV_LOG_ERROR, "Dimensions must be divisible by 16\n");
  763. return -1;
  764. }
  765. if (((avctx->width)&(avctx->width-1))||((avctx->height)&(avctx->height-1)))
  766. av_log(avctx, AV_LOG_ERROR, "Warning: dimensions not power of two\n");
  767. if (avcodec_check_dimensions(avctx, avctx->width, avctx->height)) {
  768. av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n",
  769. avctx->width, avctx->height);
  770. return -1;
  771. }
  772. enc->width = avctx->width;
  773. enc->height = avctx->height;
  774. enc->framesSinceKeyframe = 0;
  775. enc->first_frame = 1;
  776. enc->last_frame = &enc->frames[0];
  777. enc->current_frame = &enc->frames[1];
  778. enc->tmpData = av_malloc(sizeof(RoqTempdata));
  779. enc->this_motion4 =
  780. av_mallocz((enc->width*enc->height/16)*sizeof(motion_vect));
  781. enc->last_motion4 =
  782. av_malloc ((enc->width*enc->height/16)*sizeof(motion_vect));
  783. enc->this_motion8 =
  784. av_mallocz((enc->width*enc->height/64)*sizeof(motion_vect));
  785. enc->last_motion8 =
  786. av_malloc ((enc->width*enc->height/64)*sizeof(motion_vect));
  787. return 0;
  788. }
  789. static void roq_write_video_info_chunk(RoqContext *enc)
  790. {
  791. /* ROQ info chunk */
  792. bytestream_put_le16(&enc->out_buf, RoQ_INFO);
  793. /* Size: 8 bytes */
  794. bytestream_put_le32(&enc->out_buf, 8);
  795. /* Unused argument */
  796. bytestream_put_byte(&enc->out_buf, 0x00);
  797. bytestream_put_byte(&enc->out_buf, 0x00);
  798. /* Width */
  799. bytestream_put_le16(&enc->out_buf, enc->width);
  800. /* Height */
  801. bytestream_put_le16(&enc->out_buf, enc->height);
  802. /* Unused in Quake 3, mimics the output of the real encoder */
  803. bytestream_put_byte(&enc->out_buf, 0x08);
  804. bytestream_put_byte(&enc->out_buf, 0x00);
  805. bytestream_put_byte(&enc->out_buf, 0x04);
  806. bytestream_put_byte(&enc->out_buf, 0x00);
  807. }
  808. static int roq_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data)
  809. {
  810. RoqContext *enc = avctx->priv_data;
  811. AVFrame *frame= data;
  812. uint8_t *buf_start = buf;
  813. enc->out_buf = buf;
  814. enc->avctx = avctx;
  815. enc->frame_to_enc = frame;
  816. if (frame->quality)
  817. enc->lambda = frame->quality - 1;
  818. else
  819. enc->lambda = 2*ROQ_LAMBDA_SCALE;
  820. /* 138 bits max per 8x8 block +
  821. * 256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */
  822. if (((enc->width*enc->height/64)*138+7)/8 + 256*(6+4) + 8 > buf_size) {
  823. av_log(avctx, AV_LOG_ERROR, " RoQ: Output buffer too small!\n");
  824. return -1;
  825. }
  826. /* Check for I frame */
  827. if (enc->framesSinceKeyframe == avctx->gop_size)
  828. enc->framesSinceKeyframe = 0;
  829. if (enc->first_frame) {
  830. /* Alloc memory for the reconstruction data (we must know the stride
  831. for that) */
  832. if (avctx->get_buffer(avctx, enc->current_frame) ||
  833. avctx->get_buffer(avctx, enc->last_frame)) {
  834. av_log(avctx, AV_LOG_ERROR, " RoQ: get_buffer() failed\n");
  835. return -1;
  836. }
  837. /* Before the first video frame, write a "video info" chunk */
  838. roq_write_video_info_chunk(enc);
  839. enc->first_frame = 0;
  840. }
  841. /* Encode the actual frame */
  842. roq_encode_video(enc);
  843. return enc->out_buf - buf_start;
  844. }
  845. static int roq_encode_end(AVCodecContext *avctx)
  846. {
  847. RoqContext *enc = avctx->priv_data;
  848. avctx->release_buffer(avctx, enc->last_frame);
  849. avctx->release_buffer(avctx, enc->current_frame);
  850. av_free(enc->tmpData);
  851. av_free(enc->this_motion4);
  852. av_free(enc->last_motion4);
  853. av_free(enc->this_motion8);
  854. av_free(enc->last_motion8);
  855. return 0;
  856. }
  857. AVCodec roq_encoder =
  858. {
  859. "roqvideo",
  860. CODEC_TYPE_VIDEO,
  861. CODEC_ID_ROQ,
  862. sizeof(RoqContext),
  863. roq_encode_init,
  864. roq_encode_frame,
  865. roq_encode_end,
  866. .supported_framerates = (AVRational[]){{30,1}, {0,0}},
  867. .pix_fmts = (enum PixelFormat[]){PIX_FMT_YUV444P, PIX_FMT_NONE},
  868. .long_name = NULL_IF_CONFIG_SMALL("id RoQ video"),
  869. };