You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1208 lines
47KB

  1. /*
  2. * Cinepak encoder (c) 2011 Tomas Härdin
  3. * http://titan.codemill.se/~tomhar/cinepakenc.patch
  4. *
  5. * Fixes and improvements, vintage decoders compatibility
  6. * (c) 2013, 2014 Rl, Aetey Global Technologies AB
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a
  9. * copy of this software and associated documentation files (the "Software"),
  10. * to deal in the Software without restriction, including without limitation
  11. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  12. * and/or sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included
  16. * in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  22. * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  23. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  24. * OTHER DEALINGS IN THE SOFTWARE.
  25. */
  26. /*
  27. * TODO:
  28. * - optimize: color space conversion (move conversion to libswscale), ...
  29. * MAYBE:
  30. * - "optimally" split the frame into several non-regular areas
  31. * using a separate codebook pair for each area and approximating
  32. * the area by several rectangular strips (generally not full width ones)
  33. * (use quadtree splitting? a simple fixed-granularity grid?)
  34. */
  35. #include <string.h>
  36. #include "libavutil/avassert.h"
  37. #include "libavutil/common.h"
  38. #include "libavutil/internal.h"
  39. #include "libavutil/intreadwrite.h"
  40. #include "libavutil/lfg.h"
  41. #include "libavutil/opt.h"
  42. #include "avcodec.h"
  43. #include "elbg.h"
  44. #include "internal.h"
  45. #define CVID_HEADER_SIZE 10
  46. #define STRIP_HEADER_SIZE 12
  47. #define CHUNK_HEADER_SIZE 4
  48. #define MB_SIZE 4 //4x4 MBs
  49. #define MB_AREA (MB_SIZE * MB_SIZE)
  50. #define VECTOR_MAX 6 // six or four entries per vector depending on format
  51. #define CODEBOOK_MAX 256 // size of a codebook
  52. #define MAX_STRIPS 32 // Note: having fewer choices regarding the number of strips speeds up encoding (obviously)
  53. #define MIN_STRIPS 1 // Note: having more strips speeds up encoding the frame (this is less obvious)
  54. // MAX_STRIPS limits the maximum quality you can reach
  55. // when you want high quality on high resolutions,
  56. // MIN_STRIPS limits the minimum efficiently encodable bit rate
  57. // on low resolutions
  58. // the numbers are only used for brute force optimization for the first frame,
  59. // for the following frames they are adaptively readjusted
  60. // NOTE the decoder in ffmpeg has its own arbitrary limitation on the number
  61. // of strips, currently 32
  62. typedef enum CinepakMode {
  63. MODE_V1_ONLY = 0,
  64. MODE_V1_V4,
  65. MODE_MC,
  66. MODE_COUNT,
  67. } CinepakMode;
  68. typedef enum mb_encoding {
  69. ENC_V1,
  70. ENC_V4,
  71. ENC_SKIP,
  72. ENC_UNCERTAIN
  73. } mb_encoding;
  74. typedef struct mb_info {
  75. int v1_vector; // index into v1 codebook
  76. int v1_error; // error when using V1 encoding
  77. int v4_vector[4]; // indices into v4 codebook
  78. int v4_error; // error when using V4 encoding
  79. int skip_error; // error when block is skipped (aka copied from last frame)
  80. mb_encoding best_encoding; // last result from calculate_mode_score()
  81. } mb_info;
  82. typedef struct strip_info {
  83. int v1_codebook[CODEBOOK_MAX * VECTOR_MAX];
  84. int v4_codebook[CODEBOOK_MAX * VECTOR_MAX];
  85. int v1_size;
  86. int v4_size;
  87. CinepakMode mode;
  88. } strip_info;
  89. typedef struct CinepakEncContext {
  90. AVCodecContext *avctx;
  91. unsigned char *pict_bufs[4], *strip_buf, *frame_buf;
  92. AVFrame *last_frame;
  93. AVFrame *best_frame;
  94. AVFrame *scratch_frame;
  95. AVFrame *input_frame;
  96. enum AVPixelFormat pix_fmt;
  97. int w, h;
  98. int frame_buf_size;
  99. int curframe, keyint;
  100. AVLFG randctx;
  101. uint64_t lambda;
  102. int *codebook_input;
  103. int *codebook_closest;
  104. mb_info *mb; // MB RD state
  105. int min_strips; // the current limit
  106. int max_strips; // the current limit
  107. // options
  108. int max_extra_cb_iterations;
  109. int skip_empty_cb;
  110. int min_min_strips;
  111. int max_max_strips;
  112. int strip_number_delta_range;
  113. } CinepakEncContext;
  114. #define OFFSET(x) offsetof(CinepakEncContext, x)
  115. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  116. static const AVOption options[] = {
  117. { "max_extra_cb_iterations", "Max extra codebook recalculation passes, more is better and slower",
  118. OFFSET(max_extra_cb_iterations), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, INT_MAX, VE },
  119. { "skip_empty_cb", "Avoid wasting bytes, ignore vintage MacOS decoder",
  120. OFFSET(skip_empty_cb), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  121. { "max_strips", "Limit strips/frame, vintage compatible is 1..3, otherwise the more the better",
  122. OFFSET(max_max_strips), AV_OPT_TYPE_INT, { .i64 = 3 }, MIN_STRIPS, MAX_STRIPS, VE },
  123. { "min_strips", "Enforce min strips/frame, more is worse and faster, must be <= max_strips",
  124. OFFSET(min_min_strips), AV_OPT_TYPE_INT, { .i64 = MIN_STRIPS }, MIN_STRIPS, MAX_STRIPS, VE },
  125. { "strip_number_adaptivity", "How fast the strip number adapts, more is slightly better, much slower",
  126. OFFSET(strip_number_delta_range), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_STRIPS - MIN_STRIPS, VE },
  127. { NULL },
  128. };
  129. static const AVClass cinepak_class = {
  130. .class_name = "cinepak",
  131. .item_name = av_default_item_name,
  132. .option = options,
  133. .version = LIBAVUTIL_VERSION_INT,
  134. };
  135. static av_cold int cinepak_encode_init(AVCodecContext *avctx)
  136. {
  137. CinepakEncContext *s = avctx->priv_data;
  138. int x, mb_count, strip_buf_size, frame_buf_size;
  139. if (avctx->width & 3 || avctx->height & 3) {
  140. av_log(avctx, AV_LOG_ERROR, "width and height must be multiples of four (got %ix%i)\n",
  141. avctx->width, avctx->height);
  142. return AVERROR(EINVAL);
  143. }
  144. if (s->min_min_strips > s->max_max_strips) {
  145. av_log(avctx, AV_LOG_ERROR, "minimum number of strips must not exceed maximum (got %i and %i)\n",
  146. s->min_min_strips, s->max_max_strips);
  147. return AVERROR(EINVAL);
  148. }
  149. if (!(s->last_frame = av_frame_alloc()))
  150. return AVERROR(ENOMEM);
  151. if (!(s->best_frame = av_frame_alloc()))
  152. goto enomem;
  153. if (!(s->scratch_frame = av_frame_alloc()))
  154. goto enomem;
  155. if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
  156. if (!(s->input_frame = av_frame_alloc()))
  157. goto enomem;
  158. if (!(s->codebook_input = av_malloc_array((avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2, sizeof(*s->codebook_input))))
  159. goto enomem;
  160. if (!(s->codebook_closest = av_malloc_array((avctx->width * avctx->height) >> 2, sizeof(*s->codebook_closest))))
  161. goto enomem;
  162. for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
  163. if (!(s->pict_bufs[x] = av_malloc((avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4) * (avctx->width * avctx->height) >> 2)))
  164. goto enomem;
  165. mb_count = avctx->width * avctx->height / MB_AREA;
  166. // the largest possible chunk is 0x31 with all MBs encoded in V4 mode
  167. // and full codebooks being replaced in INTER mode,
  168. // which is 34 bits per MB
  169. // and 2*256 extra flag bits per strip
  170. strip_buf_size = STRIP_HEADER_SIZE + 3 * CHUNK_HEADER_SIZE + 2 * VECTOR_MAX * CODEBOOK_MAX + 4 * (mb_count + (mb_count + 15) / 16) + (2 * CODEBOOK_MAX) / 8;
  171. frame_buf_size = CVID_HEADER_SIZE + s->max_max_strips * strip_buf_size;
  172. if (!(s->strip_buf = av_malloc(strip_buf_size)))
  173. goto enomem;
  174. if (!(s->frame_buf = av_malloc(frame_buf_size)))
  175. goto enomem;
  176. if (!(s->mb = av_malloc_array(mb_count, sizeof(mb_info))))
  177. goto enomem;
  178. av_lfg_init(&s->randctx, 1);
  179. s->avctx = avctx;
  180. s->w = avctx->width;
  181. s->h = avctx->height;
  182. s->frame_buf_size = frame_buf_size;
  183. s->curframe = 0;
  184. s->keyint = avctx->keyint_min;
  185. s->pix_fmt = avctx->pix_fmt;
  186. // set up AVFrames
  187. s->last_frame->data[0] = s->pict_bufs[0];
  188. s->last_frame->linesize[0] = s->w;
  189. s->best_frame->data[0] = s->pict_bufs[1];
  190. s->best_frame->linesize[0] = s->w;
  191. s->scratch_frame->data[0] = s->pict_bufs[2];
  192. s->scratch_frame->linesize[0] = s->w;
  193. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  194. s->last_frame->data[1] = s->last_frame->data[0] + s->w * s->h;
  195. s->last_frame->data[2] = s->last_frame->data[1] + ((s->w * s->h) >> 2);
  196. s->last_frame->linesize[1] =
  197. s->last_frame->linesize[2] = s->w >> 1;
  198. s->best_frame->data[1] = s->best_frame->data[0] + s->w * s->h;
  199. s->best_frame->data[2] = s->best_frame->data[1] + ((s->w * s->h) >> 2);
  200. s->best_frame->linesize[1] =
  201. s->best_frame->linesize[2] = s->w >> 1;
  202. s->scratch_frame->data[1] = s->scratch_frame->data[0] + s->w * s->h;
  203. s->scratch_frame->data[2] = s->scratch_frame->data[1] + ((s->w * s->h) >> 2);
  204. s->scratch_frame->linesize[1] =
  205. s->scratch_frame->linesize[2] = s->w >> 1;
  206. s->input_frame->data[0] = s->pict_bufs[3];
  207. s->input_frame->linesize[0] = s->w;
  208. s->input_frame->data[1] = s->input_frame->data[0] + s->w * s->h;
  209. s->input_frame->data[2] = s->input_frame->data[1] + ((s->w * s->h) >> 2);
  210. s->input_frame->linesize[1] =
  211. s->input_frame->linesize[2] = s->w >> 1;
  212. }
  213. s->min_strips = s->min_min_strips;
  214. s->max_strips = s->max_max_strips;
  215. return 0;
  216. enomem:
  217. av_frame_free(&s->last_frame);
  218. av_frame_free(&s->best_frame);
  219. av_frame_free(&s->scratch_frame);
  220. if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
  221. av_frame_free(&s->input_frame);
  222. av_freep(&s->codebook_input);
  223. av_freep(&s->codebook_closest);
  224. av_freep(&s->strip_buf);
  225. av_freep(&s->frame_buf);
  226. av_freep(&s->mb);
  227. for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
  228. av_freep(&s->pict_bufs[x]);
  229. return AVERROR(ENOMEM);
  230. }
  231. static int64_t calculate_mode_score(CinepakEncContext *s, int h,
  232. strip_info *info, int report,
  233. int *training_set_v1_shrunk,
  234. int *training_set_v4_shrunk)
  235. {
  236. // score = FF_LAMBDA_SCALE * error + lambda * bits
  237. int x;
  238. int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
  239. int mb_count = s->w * h / MB_AREA;
  240. mb_info *mb;
  241. int64_t score1, score2, score3;
  242. int64_t ret = s->lambda * ((info->v1_size ? CHUNK_HEADER_SIZE + info->v1_size * entry_size : 0) +
  243. (info->v4_size ? CHUNK_HEADER_SIZE + info->v4_size * entry_size : 0) +
  244. CHUNK_HEADER_SIZE) << 3;
  245. switch (info->mode) {
  246. case MODE_V1_ONLY:
  247. // one byte per MB
  248. ret += s->lambda * 8 * mb_count;
  249. // while calculating we assume all blocks are ENC_V1
  250. for (x = 0; x < mb_count; x++) {
  251. mb = &s->mb[x];
  252. ret += FF_LAMBDA_SCALE * mb->v1_error;
  253. // this function is never called for report in MODE_V1_ONLY
  254. // if (!report)
  255. mb->best_encoding = ENC_V1;
  256. }
  257. break;
  258. case MODE_V1_V4:
  259. // 9 or 33 bits per MB
  260. if (report) {
  261. // no moves between the corresponding training sets are allowed
  262. *training_set_v1_shrunk = *training_set_v4_shrunk = 0;
  263. for (x = 0; x < mb_count; x++) {
  264. int mberr;
  265. mb = &s->mb[x];
  266. if (mb->best_encoding == ENC_V1)
  267. score1 = s->lambda * 9 + FF_LAMBDA_SCALE * (mberr = mb->v1_error);
  268. else
  269. score1 = s->lambda * 33 + FF_LAMBDA_SCALE * (mberr = mb->v4_error);
  270. ret += score1;
  271. }
  272. } else { // find best mode per block
  273. for (x = 0; x < mb_count; x++) {
  274. mb = &s->mb[x];
  275. score1 = s->lambda * 9 + FF_LAMBDA_SCALE * mb->v1_error;
  276. score2 = s->lambda * 33 + FF_LAMBDA_SCALE * mb->v4_error;
  277. if (score1 <= score2) {
  278. ret += score1;
  279. mb->best_encoding = ENC_V1;
  280. } else {
  281. ret += score2;
  282. mb->best_encoding = ENC_V4;
  283. }
  284. }
  285. }
  286. break;
  287. case MODE_MC:
  288. // 1, 10 or 34 bits per MB
  289. if (report) {
  290. int v1_shrunk = 0, v4_shrunk = 0;
  291. for (x = 0; x < mb_count; x++) {
  292. mb = &s->mb[x];
  293. // it is OK to move blocks to ENC_SKIP here
  294. // but not to any codebook encoding!
  295. score1 = s->lambda * 1 + FF_LAMBDA_SCALE * mb->skip_error;
  296. if (mb->best_encoding == ENC_SKIP) {
  297. ret += score1;
  298. } else if (mb->best_encoding == ENC_V1) {
  299. if ((score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error) >= score1) {
  300. mb->best_encoding = ENC_SKIP;
  301. ++v1_shrunk;
  302. ret += score1;
  303. } else {
  304. ret += score2;
  305. }
  306. } else {
  307. if ((score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error) >= score1) {
  308. mb->best_encoding = ENC_SKIP;
  309. ++v4_shrunk;
  310. ret += score1;
  311. } else {
  312. ret += score3;
  313. }
  314. }
  315. }
  316. *training_set_v1_shrunk = v1_shrunk;
  317. *training_set_v4_shrunk = v4_shrunk;
  318. } else { // find best mode per block
  319. for (x = 0; x < mb_count; x++) {
  320. mb = &s->mb[x];
  321. score1 = s->lambda * 1 + FF_LAMBDA_SCALE * mb->skip_error;
  322. score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error;
  323. score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error;
  324. if (score1 <= score2 && score1 <= score3) {
  325. ret += score1;
  326. mb->best_encoding = ENC_SKIP;
  327. } else if (score2 <= score3) {
  328. ret += score2;
  329. mb->best_encoding = ENC_V1;
  330. } else {
  331. ret += score3;
  332. mb->best_encoding = ENC_V4;
  333. }
  334. }
  335. }
  336. break;
  337. }
  338. return ret;
  339. }
  340. static int write_chunk_header(unsigned char *buf, int chunk_type, int chunk_size)
  341. {
  342. buf[0] = chunk_type;
  343. AV_WB24(&buf[1], chunk_size + CHUNK_HEADER_SIZE);
  344. return CHUNK_HEADER_SIZE;
  345. }
  346. static int encode_codebook(CinepakEncContext *s, int *codebook, int size,
  347. int chunk_type_yuv, int chunk_type_gray,
  348. unsigned char *buf)
  349. {
  350. int x, y, ret, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
  351. int incremental_codebook_replacement_mode = 0; // hardcoded here,
  352. // the compiler should notice that this is a constant -- rl
  353. ret = write_chunk_header(buf,
  354. s->pix_fmt == AV_PIX_FMT_RGB24 ?
  355. chunk_type_yuv + (incremental_codebook_replacement_mode ? 1 : 0) :
  356. chunk_type_gray + (incremental_codebook_replacement_mode ? 1 : 0),
  357. entry_size * size +
  358. (incremental_codebook_replacement_mode ? (size + 31) / 32 * 4 : 0));
  359. // we do codebook encoding according to the "intra" mode
  360. // but we keep the "dead" code for reference in case we will want
  361. // to use incremental codebook updates (which actually would give us
  362. // "kind of" motion compensation, especially in 1 strip/frame case) -- rl
  363. // (of course, the code will be not useful as-is)
  364. if (incremental_codebook_replacement_mode) {
  365. int flags = 0;
  366. int flagsind;
  367. for (x = 0; x < size; x++) {
  368. if (flags == 0) {
  369. flagsind = ret;
  370. ret += 4;
  371. flags = 0x80000000;
  372. } else
  373. flags = ((flags >> 1) | 0x80000000);
  374. for (y = 0; y < entry_size; y++)
  375. buf[ret++] = codebook[y + x * entry_size] ^ (y >= 4 ? 0x80 : 0);
  376. if ((flags & 0xffffffff) == 0xffffffff) {
  377. AV_WB32(&buf[flagsind], flags);
  378. flags = 0;
  379. }
  380. }
  381. if (flags)
  382. AV_WB32(&buf[flagsind], flags);
  383. } else
  384. for (x = 0; x < size; x++)
  385. for (y = 0; y < entry_size; y++)
  386. buf[ret++] = codebook[y + x * entry_size] ^ (y >= 4 ? 0x80 : 0);
  387. return ret;
  388. }
  389. // sets out to the sub picture starting at (x,y) in in
  390. static void get_sub_picture(CinepakEncContext *s, int x, int y,
  391. uint8_t * in_data[4], int in_linesize[4],
  392. uint8_t *out_data[4], int out_linesize[4])
  393. {
  394. out_data[0] = in_data[0] + x + y * in_linesize[0];
  395. out_linesize[0] = in_linesize[0];
  396. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  397. out_data[1] = in_data[1] + (x >> 1) + (y >> 1) * in_linesize[1];
  398. out_linesize[1] = in_linesize[1];
  399. out_data[2] = in_data[2] + (x >> 1) + (y >> 1) * in_linesize[2];
  400. out_linesize[2] = in_linesize[2];
  401. }
  402. }
  403. // decodes the V1 vector in mb into the 4x4 MB pointed to by data
  404. static void decode_v1_vector(CinepakEncContext *s, uint8_t *data[4],
  405. int linesize[4], int v1_vector, strip_info *info)
  406. {
  407. int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
  408. data[0][0] =
  409. data[0][1] =
  410. data[0][ linesize[0]] =
  411. data[0][1 + linesize[0]] = info->v1_codebook[v1_vector * entry_size];
  412. data[0][2] =
  413. data[0][3] =
  414. data[0][2 + linesize[0]] =
  415. data[0][3 + linesize[0]] = info->v1_codebook[v1_vector * entry_size + 1];
  416. data[0][ 2 * linesize[0]] =
  417. data[0][1 + 2 * linesize[0]] =
  418. data[0][ 3 * linesize[0]] =
  419. data[0][1 + 3 * linesize[0]] = info->v1_codebook[v1_vector * entry_size + 2];
  420. data[0][2 + 2 * linesize[0]] =
  421. data[0][3 + 2 * linesize[0]] =
  422. data[0][2 + 3 * linesize[0]] =
  423. data[0][3 + 3 * linesize[0]] = info->v1_codebook[v1_vector * entry_size + 3];
  424. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  425. data[1][0] =
  426. data[1][1] =
  427. data[1][ linesize[1]] =
  428. data[1][1 + linesize[1]] = info->v1_codebook[v1_vector * entry_size + 4];
  429. data[2][0] =
  430. data[2][1] =
  431. data[2][ linesize[2]] =
  432. data[2][1 + linesize[2]] = info->v1_codebook[v1_vector * entry_size + 5];
  433. }
  434. }
  435. // decodes the V4 vectors in mb into the 4x4 MB pointed to by data
  436. static void decode_v4_vector(CinepakEncContext *s, uint8_t *data[4],
  437. int linesize[4], int *v4_vector, strip_info *info)
  438. {
  439. int i, x, y, entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
  440. for (i = y = 0; y < 4; y += 2) {
  441. for (x = 0; x < 4; x += 2, i++) {
  442. data[0][x + y * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size];
  443. data[0][x + 1 + y * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 1];
  444. data[0][x + (y + 1) * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 2];
  445. data[0][x + 1 + (y + 1) * linesize[0]] = info->v4_codebook[v4_vector[i] * entry_size + 3];
  446. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  447. data[1][(x >> 1) + (y >> 1) * linesize[1]] = info->v4_codebook[v4_vector[i] * entry_size + 4];
  448. data[2][(x >> 1) + (y >> 1) * linesize[2]] = info->v4_codebook[v4_vector[i] * entry_size + 5];
  449. }
  450. }
  451. }
  452. }
  453. static void copy_mb(CinepakEncContext *s,
  454. uint8_t *a_data[4], int a_linesize[4],
  455. uint8_t *b_data[4], int b_linesize[4])
  456. {
  457. int y, p;
  458. for (y = 0; y < MB_SIZE; y++)
  459. memcpy(a_data[0] + y * a_linesize[0], b_data[0] + y * b_linesize[0],
  460. MB_SIZE);
  461. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  462. for (p = 1; p <= 2; p++)
  463. for (y = 0; y < MB_SIZE / 2; y++)
  464. memcpy(a_data[p] + y * a_linesize[p],
  465. b_data[p] + y * b_linesize[p],
  466. MB_SIZE / 2);
  467. }
  468. }
  469. static int encode_mode(CinepakEncContext *s, int h,
  470. uint8_t *scratch_data[4], int scratch_linesize[4],
  471. uint8_t *last_data[4], int last_linesize[4],
  472. strip_info *info, unsigned char *buf)
  473. {
  474. int x, y, z, flags, bits, temp_size, header_ofs, ret = 0, mb_count = s->w * h / MB_AREA;
  475. int needs_extra_bit, should_write_temp;
  476. unsigned char temp[64]; // 32/2 = 16 V4 blocks at 4 B each -> 64 B
  477. mb_info *mb;
  478. uint8_t *sub_scratch_data[4] = { 0 }, *sub_last_data[4] = { 0 };
  479. int sub_scratch_linesize[4] = { 0 }, sub_last_linesize[4] = { 0 };
  480. // encode codebooks
  481. ////// MacOS vintage decoder compatibility dictates the presence of
  482. ////// the codebook chunk even when the codebook is empty - pretty dumb...
  483. ////// and also the certain order of the codebook chunks -- rl
  484. if (info->v4_size || !s->skip_empty_cb)
  485. ret += encode_codebook(s, info->v4_codebook, info->v4_size, 0x20, 0x24, buf + ret);
  486. if (info->v1_size || !s->skip_empty_cb)
  487. ret += encode_codebook(s, info->v1_codebook, info->v1_size, 0x22, 0x26, buf + ret);
  488. // update scratch picture
  489. for (z = y = 0; y < h; y += MB_SIZE)
  490. for (x = 0; x < s->w; x += MB_SIZE, z++) {
  491. mb = &s->mb[z];
  492. get_sub_picture(s, x, y, scratch_data, scratch_linesize,
  493. sub_scratch_data, sub_scratch_linesize);
  494. if (info->mode == MODE_MC && mb->best_encoding == ENC_SKIP) {
  495. get_sub_picture(s, x, y, last_data, last_linesize,
  496. sub_last_data, sub_last_linesize);
  497. copy_mb(s, sub_scratch_data, sub_scratch_linesize,
  498. sub_last_data, sub_last_linesize);
  499. } else if (info->mode == MODE_V1_ONLY || mb->best_encoding == ENC_V1)
  500. decode_v1_vector(s, sub_scratch_data, sub_scratch_linesize,
  501. mb->v1_vector, info);
  502. else
  503. decode_v4_vector(s, sub_scratch_data, sub_scratch_linesize,
  504. mb->v4_vector, info);
  505. }
  506. switch (info->mode) {
  507. case MODE_V1_ONLY:
  508. ret += write_chunk_header(buf + ret, 0x32, mb_count);
  509. for (x = 0; x < mb_count; x++)
  510. buf[ret++] = s->mb[x].v1_vector;
  511. break;
  512. case MODE_V1_V4:
  513. // remember header position
  514. header_ofs = ret;
  515. ret += CHUNK_HEADER_SIZE;
  516. for (x = 0; x < mb_count; x += 32) {
  517. flags = 0;
  518. for (y = x; y < FFMIN(x + 32, mb_count); y++)
  519. if (s->mb[y].best_encoding == ENC_V4)
  520. flags |= 1 << (31 - y + x);
  521. AV_WB32(&buf[ret], flags);
  522. ret += 4;
  523. for (y = x; y < FFMIN(x + 32, mb_count); y++) {
  524. mb = &s->mb[y];
  525. if (mb->best_encoding == ENC_V1)
  526. buf[ret++] = mb->v1_vector;
  527. else
  528. for (z = 0; z < 4; z++)
  529. buf[ret++] = mb->v4_vector[z];
  530. }
  531. }
  532. write_chunk_header(buf + header_ofs, 0x30, ret - header_ofs - CHUNK_HEADER_SIZE);
  533. break;
  534. case MODE_MC:
  535. // remember header position
  536. header_ofs = ret;
  537. ret += CHUNK_HEADER_SIZE;
  538. flags = bits = temp_size = 0;
  539. for (x = 0; x < mb_count; x++) {
  540. mb = &s->mb[x];
  541. flags |= (mb->best_encoding != ENC_SKIP) << (31 - bits++);
  542. needs_extra_bit = 0;
  543. should_write_temp = 0;
  544. if (mb->best_encoding != ENC_SKIP) {
  545. if (bits < 32)
  546. flags |= (mb->best_encoding == ENC_V4) << (31 - bits++);
  547. else
  548. needs_extra_bit = 1;
  549. }
  550. if (bits == 32) {
  551. AV_WB32(&buf[ret], flags);
  552. ret += 4;
  553. flags = bits = 0;
  554. if (mb->best_encoding == ENC_SKIP || needs_extra_bit) {
  555. memcpy(&buf[ret], temp, temp_size);
  556. ret += temp_size;
  557. temp_size = 0;
  558. } else
  559. should_write_temp = 1;
  560. }
  561. if (needs_extra_bit) {
  562. flags = (mb->best_encoding == ENC_V4) << 31;
  563. bits = 1;
  564. }
  565. if (mb->best_encoding == ENC_V1)
  566. temp[temp_size++] = mb->v1_vector;
  567. else if (mb->best_encoding == ENC_V4)
  568. for (z = 0; z < 4; z++)
  569. temp[temp_size++] = mb->v4_vector[z];
  570. if (should_write_temp) {
  571. memcpy(&buf[ret], temp, temp_size);
  572. ret += temp_size;
  573. temp_size = 0;
  574. }
  575. }
  576. if (bits > 0) {
  577. AV_WB32(&buf[ret], flags);
  578. ret += 4;
  579. memcpy(&buf[ret], temp, temp_size);
  580. ret += temp_size;
  581. }
  582. write_chunk_header(buf + header_ofs, 0x31, ret - header_ofs - CHUNK_HEADER_SIZE);
  583. break;
  584. }
  585. return ret;
  586. }
  587. // computes distortion of 4x4 MB in b compared to a
  588. static int compute_mb_distortion(CinepakEncContext *s,
  589. uint8_t *a_data[4], int a_linesize[4],
  590. uint8_t *b_data[4], int b_linesize[4])
  591. {
  592. int x, y, p, d, ret = 0;
  593. for (y = 0; y < MB_SIZE; y++)
  594. for (x = 0; x < MB_SIZE; x++) {
  595. d = a_data[0][x + y * a_linesize[0]] - b_data[0][x + y * b_linesize[0]];
  596. ret += d * d;
  597. }
  598. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  599. for (p = 1; p <= 2; p++) {
  600. for (y = 0; y < MB_SIZE / 2; y++)
  601. for (x = 0; x < MB_SIZE / 2; x++) {
  602. d = a_data[p][x + y * a_linesize[p]] - b_data[p][x + y * b_linesize[p]];
  603. ret += d * d;
  604. }
  605. }
  606. }
  607. return ret;
  608. }
  609. // return the possibly adjusted size of the codebook
  610. #define CERTAIN(x) ((x) != ENC_UNCERTAIN)
  611. static int quantize(CinepakEncContext *s, int h, uint8_t *data[4],
  612. int linesize[4], int v1mode, strip_info *info,
  613. mb_encoding encoding)
  614. {
  615. int x, y, i, j, k, x2, y2, x3, y3, plane, shift, mbn;
  616. int entry_size = s->pix_fmt == AV_PIX_FMT_RGB24 ? 6 : 4;
  617. int *codebook = v1mode ? info->v1_codebook : info->v4_codebook;
  618. int size = v1mode ? info->v1_size : info->v4_size;
  619. int64_t total_error = 0;
  620. uint8_t vq_pict_buf[(MB_AREA * 3) / 2];
  621. uint8_t *sub_data[4], *vq_data[4];
  622. int sub_linesize[4], vq_linesize[4];
  623. for (mbn = i = y = 0; y < h; y += MB_SIZE) {
  624. for (x = 0; x < s->w; x += MB_SIZE, ++mbn) {
  625. int *base;
  626. if (CERTAIN(encoding)) {
  627. // use for the training only the blocks known to be to be encoded [sic:-]
  628. if (s->mb[mbn].best_encoding != encoding)
  629. continue;
  630. }
  631. base = s->codebook_input + i * entry_size;
  632. if (v1mode) {
  633. // subsample
  634. for (j = y2 = 0; y2 < entry_size; y2 += 2)
  635. for (x2 = 0; x2 < 4; x2 += 2, j++) {
  636. plane = y2 < 4 ? 0 : 1 + (x2 >> 1);
  637. shift = y2 < 4 ? 0 : 1;
  638. x3 = shift ? 0 : x2;
  639. y3 = shift ? 0 : y2;
  640. base[j] = (data[plane][((x + x3) >> shift) + ((y + y3) >> shift) * linesize[plane]] +
  641. data[plane][((x + x3) >> shift) + 1 + ((y + y3) >> shift) * linesize[plane]] +
  642. data[plane][((x + x3) >> shift) + (((y + y3) >> shift) + 1) * linesize[plane]] +
  643. data[plane][((x + x3) >> shift) + 1 + (((y + y3) >> shift) + 1) * linesize[plane]]) >> 2;
  644. }
  645. } else {
  646. // copy
  647. for (j = y2 = 0; y2 < MB_SIZE; y2 += 2) {
  648. for (x2 = 0; x2 < MB_SIZE; x2 += 2)
  649. for (k = 0; k < entry_size; k++, j++) {
  650. plane = k >= 4 ? k - 3 : 0;
  651. if (k >= 4) {
  652. x3 = (x + x2) >> 1;
  653. y3 = (y + y2) >> 1;
  654. } else {
  655. x3 = x + x2 + (k & 1);
  656. y3 = y + y2 + (k >> 1);
  657. }
  658. base[j] = data[plane][x3 + y3 * linesize[plane]];
  659. }
  660. }
  661. }
  662. i += v1mode ? 1 : 4;
  663. }
  664. }
  665. if (i == 0) // empty training set, nothing to do
  666. return 0;
  667. if (i < size)
  668. size = i;
  669. ff_init_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
  670. ff_do_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);
  671. // set up vq_data, which contains a single MB
  672. vq_data[0] = vq_pict_buf;
  673. vq_linesize[0] = MB_SIZE;
  674. vq_data[1] = &vq_pict_buf[MB_AREA];
  675. vq_data[2] = vq_data[1] + (MB_AREA >> 2);
  676. vq_linesize[1] =
  677. vq_linesize[2] = MB_SIZE >> 1;
  678. // copy indices
  679. for (i = j = y = 0; y < h; y += MB_SIZE)
  680. for (x = 0; x < s->w; x += MB_SIZE, j++) {
  681. mb_info *mb = &s->mb[j];
  682. // skip uninteresting blocks if we know their preferred encoding
  683. if (CERTAIN(encoding) && mb->best_encoding != encoding)
  684. continue;
  685. // point sub_data to current MB
  686. get_sub_picture(s, x, y, data, linesize, sub_data, sub_linesize);
  687. if (v1mode) {
  688. mb->v1_vector = s->codebook_closest[i];
  689. // fill in vq_data with V1 data
  690. decode_v1_vector(s, vq_data, vq_linesize, mb->v1_vector, info);
  691. mb->v1_error = compute_mb_distortion(s, sub_data, sub_linesize,
  692. vq_data, vq_linesize);
  693. total_error += mb->v1_error;
  694. } else {
  695. for (k = 0; k < 4; k++)
  696. mb->v4_vector[k] = s->codebook_closest[i + k];
  697. // fill in vq_data with V4 data
  698. decode_v4_vector(s, vq_data, vq_linesize, mb->v4_vector, info);
  699. mb->v4_error = compute_mb_distortion(s, sub_data, sub_linesize,
  700. vq_data, vq_linesize);
  701. total_error += mb->v4_error;
  702. }
  703. i += v1mode ? 1 : 4;
  704. }
  705. // check that we did it right in the beginning of the function
  706. av_assert0(i >= size); // training set is no smaller than the codebook
  707. return size;
  708. }
  709. static void calculate_skip_errors(CinepakEncContext *s, int h,
  710. uint8_t *last_data[4], int last_linesize[4],
  711. uint8_t *data[4], int linesize[4],
  712. strip_info *info)
  713. {
  714. int x, y, i;
  715. uint8_t *sub_last_data [4], *sub_pict_data [4];
  716. int sub_last_linesize[4], sub_pict_linesize[4];
  717. for (i = y = 0; y < h; y += MB_SIZE)
  718. for (x = 0; x < s->w; x += MB_SIZE, i++) {
  719. get_sub_picture(s, x, y, last_data, last_linesize,
  720. sub_last_data, sub_last_linesize);
  721. get_sub_picture(s, x, y, data, linesize,
  722. sub_pict_data, sub_pict_linesize);
  723. s->mb[i].skip_error =
  724. compute_mb_distortion(s,
  725. sub_last_data, sub_last_linesize,
  726. sub_pict_data, sub_pict_linesize);
  727. }
  728. }
  729. static void write_strip_header(CinepakEncContext *s, int y, int h, int keyframe,
  730. unsigned char *buf, int strip_size)
  731. {
  732. // actually we are exclusively using intra strip coding (how much can we win
  733. // otherwise? how to choose which part of a codebook to update?),
  734. // keyframes are different only because we disallow ENC_SKIP on them -- rl
  735. // (besides, the logic here used to be inverted: )
  736. // buf[0] = keyframe ? 0x11: 0x10;
  737. buf[0] = keyframe ? 0x10 : 0x11;
  738. AV_WB24(&buf[1], strip_size + STRIP_HEADER_SIZE);
  739. // AV_WB16(&buf[4], y); /* using absolute y values works -- rl */
  740. AV_WB16(&buf[4], 0); /* using relative values works as well -- rl */
  741. AV_WB16(&buf[6], 0);
  742. // AV_WB16(&buf[8], y + h); /* using absolute y values works -- rl */
  743. AV_WB16(&buf[8], h); /* using relative values works as well -- rl */
  744. AV_WB16(&buf[10], s->w);
  745. }
  746. static int rd_strip(CinepakEncContext *s, int y, int h, int keyframe,
  747. uint8_t *last_data[4], int last_linesize[4],
  748. uint8_t *data[4], int linesize[4],
  749. uint8_t *scratch_data[4], int scratch_linesize[4],
  750. unsigned char *buf, int64_t *best_score)
  751. {
  752. int64_t score = 0;
  753. int best_size = 0;
  754. strip_info info;
  755. // for codebook optimization:
  756. int v1enough, v1_size, v4enough, v4_size;
  757. int new_v1_size, new_v4_size;
  758. int v1shrunk, v4shrunk;
  759. if (!keyframe)
  760. calculate_skip_errors(s, h, last_data, last_linesize, data, linesize,
  761. &info);
  762. // try some powers of 4 for the size of the codebooks
  763. // constraint the v4 codebook to be no bigger than v1 one,
  764. // (and no less than v1_size/4)
  765. // thus making v1 preferable and possibly losing small details? should be ok
  766. #define SMALLEST_CODEBOOK 1
  767. for (v1enough = 0, v1_size = SMALLEST_CODEBOOK; v1_size <= CODEBOOK_MAX && !v1enough; v1_size <<= 2) {
  768. for (v4enough = 0, v4_size = 0; v4_size <= v1_size && !v4enough; v4_size = v4_size ? v4_size << 2 : v1_size >= SMALLEST_CODEBOOK << 2 ? v1_size >> 2 : SMALLEST_CODEBOOK) {
  769. CinepakMode mode;
  770. // try all modes
  771. for (mode = 0; mode < MODE_COUNT; mode++) {
  772. // don't allow MODE_MC in intra frames
  773. if (keyframe && mode == MODE_MC)
  774. continue;
  775. if (mode == MODE_V1_ONLY) {
  776. info.v1_size = v1_size;
  777. // the size may shrink even before optimizations if the input is short:
  778. info.v1_size = quantize(s, h, data, linesize, 1,
  779. &info, ENC_UNCERTAIN);
  780. if (info.v1_size < v1_size)
  781. // too few eligible blocks, no sense in trying bigger sizes
  782. v1enough = 1;
  783. info.v4_size = 0;
  784. } else { // mode != MODE_V1_ONLY
  785. // if v4 codebook is empty then only allow V1-only mode
  786. if (!v4_size)
  787. continue;
  788. if (mode == MODE_V1_V4) {
  789. info.v4_size = v4_size;
  790. info.v4_size = quantize(s, h, data, linesize, 0,
  791. &info, ENC_UNCERTAIN);
  792. if (info.v4_size < v4_size)
  793. // too few eligible blocks, no sense in trying bigger sizes
  794. v4enough = 1;
  795. }
  796. }
  797. info.mode = mode;
  798. // choose the best encoding per block, based on current experience
  799. score = calculate_mode_score(s, h, &info, 0,
  800. &v1shrunk, &v4shrunk);
  801. if (mode != MODE_V1_ONLY) {
  802. int extra_iterations_limit = s->max_extra_cb_iterations;
  803. // recompute the codebooks, omitting the extra blocks
  804. // we assume we _may_ come here with more blocks to encode than before
  805. info.v1_size = v1_size;
  806. new_v1_size = quantize(s, h, data, linesize, 1, &info, ENC_V1);
  807. if (new_v1_size < info.v1_size)
  808. info.v1_size = new_v1_size;
  809. // we assume we _may_ come here with more blocks to encode than before
  810. info.v4_size = v4_size;
  811. new_v4_size = quantize(s, h, data, linesize, 0, &info, ENC_V4);
  812. if (new_v4_size < info.v4_size)
  813. info.v4_size = new_v4_size;
  814. // calculate the resulting score
  815. // (do not move blocks to codebook encodings now, as some blocks may have
  816. // got bigger errors despite a smaller training set - but we do not
  817. // ever grow the training sets back)
  818. for (;;) {
  819. score = calculate_mode_score(s, h, &info, 1,
  820. &v1shrunk, &v4shrunk);
  821. // do we have a reason to reiterate? if so, have we reached the limit?
  822. if ((!v1shrunk && !v4shrunk) || !extra_iterations_limit--)
  823. break;
  824. // recompute the codebooks, omitting the extra blocks
  825. if (v1shrunk) {
  826. info.v1_size = v1_size;
  827. new_v1_size = quantize(s, h, data, linesize, 1, &info, ENC_V1);
  828. if (new_v1_size < info.v1_size)
  829. info.v1_size = new_v1_size;
  830. }
  831. if (v4shrunk) {
  832. info.v4_size = v4_size;
  833. new_v4_size = quantize(s, h, data, linesize, 0, &info, ENC_V4);
  834. if (new_v4_size < info.v4_size)
  835. info.v4_size = new_v4_size;
  836. }
  837. }
  838. }
  839. if (best_size == 0 || score < *best_score) {
  840. *best_score = score;
  841. best_size = encode_mode(s, h,
  842. scratch_data, scratch_linesize,
  843. last_data, last_linesize, &info,
  844. s->strip_buf + STRIP_HEADER_SIZE);
  845. write_strip_header(s, y, h, keyframe, s->strip_buf, best_size);
  846. }
  847. }
  848. }
  849. }
  850. best_size += STRIP_HEADER_SIZE;
  851. memcpy(buf, s->strip_buf, best_size);
  852. return best_size;
  853. }
  854. static int write_cvid_header(CinepakEncContext *s, unsigned char *buf,
  855. int num_strips, int data_size, int isakeyframe)
  856. {
  857. buf[0] = isakeyframe ? 0 : 1;
  858. AV_WB24(&buf[1], data_size + CVID_HEADER_SIZE);
  859. AV_WB16(&buf[4], s->w);
  860. AV_WB16(&buf[6], s->h);
  861. AV_WB16(&buf[8], num_strips);
  862. return CVID_HEADER_SIZE;
  863. }
  864. static int rd_frame(CinepakEncContext *s, const AVFrame *frame,
  865. int isakeyframe, unsigned char *buf, int buf_size)
  866. {
  867. int num_strips, strip, i, y, nexty, size, temp_size, best_size;
  868. uint8_t *last_data [4], *data [4], *scratch_data [4];
  869. int last_linesize[4], linesize[4], scratch_linesize[4];
  870. int64_t best_score = 0, score, score_temp;
  871. int best_nstrips;
  872. if (s->pix_fmt == AV_PIX_FMT_RGB24) {
  873. int x;
  874. // build a copy of the given frame in the correct colorspace
  875. for (y = 0; y < s->h; y += 2)
  876. for (x = 0; x < s->w; x += 2) {
  877. uint8_t *ir[2];
  878. int32_t r, g, b, rr, gg, bb;
  879. ir[0] = frame->data[0] + x * 3 + y * frame->linesize[0];
  880. ir[1] = ir[0] + frame->linesize[0];
  881. get_sub_picture(s, x, y,
  882. s->input_frame->data, s->input_frame->linesize,
  883. scratch_data, scratch_linesize);
  884. r = g = b = 0;
  885. for (i = 0; i < 4; ++i) {
  886. int i1, i2;
  887. i1 = (i & 1);
  888. i2 = (i >= 2);
  889. rr = ir[i2][i1 * 3 + 0];
  890. gg = ir[i2][i1 * 3 + 1];
  891. bb = ir[i2][i1 * 3 + 2];
  892. r += rr;
  893. g += gg;
  894. b += bb;
  895. // using fixed point arithmetic for portable repeatability, scaling by 2^23
  896. // "Y"
  897. // rr = 0.2857 * rr + 0.5714 * gg + 0.1429 * bb;
  898. rr = (2396625 * rr + 4793251 * gg + 1198732 * bb) >> 23;
  899. if (rr < 0)
  900. rr = 0;
  901. else if (rr > 255)
  902. rr = 255;
  903. scratch_data[0][i1 + i2 * scratch_linesize[0]] = rr;
  904. }
  905. // let us scale down as late as possible
  906. // r /= 4; g /= 4; b /= 4;
  907. // "U"
  908. // rr = -0.1429 * r - 0.2857 * g + 0.4286 * b;
  909. rr = (-299683 * r - 599156 * g + 898839 * b) >> 23;
  910. if (rr < -128)
  911. rr = -128;
  912. else if (rr > 127)
  913. rr = 127;
  914. scratch_data[1][0] = rr + 128; // quantize needs unsigned
  915. // "V"
  916. // rr = 0.3571 * r - 0.2857 * g - 0.0714 * b;
  917. rr = (748893 * r - 599156 * g - 149737 * b) >> 23;
  918. if (rr < -128)
  919. rr = -128;
  920. else if (rr > 127)
  921. rr = 127;
  922. scratch_data[2][0] = rr + 128; // quantize needs unsigned
  923. }
  924. }
  925. // would be nice but quite certainly incompatible with vintage players:
  926. // support encoding zero strips (meaning skip the whole frame)
  927. for (num_strips = s->min_strips; num_strips <= s->max_strips && num_strips <= s->h / MB_SIZE; num_strips++) {
  928. score = 0;
  929. size = 0;
  930. for (y = 0, strip = 1; y < s->h; strip++, y = nexty) {
  931. int strip_height;
  932. nexty = strip * s->h / num_strips; // <= s->h
  933. // make nexty the next multiple of 4 if not already there
  934. if (nexty & 3)
  935. nexty += 4 - (nexty & 3);
  936. strip_height = nexty - y;
  937. if (strip_height <= 0) { // can this ever happen?
  938. av_log(s->avctx, AV_LOG_INFO, "skipping zero height strip %i of %i\n", strip, num_strips);
  939. continue;
  940. }
  941. if (s->pix_fmt == AV_PIX_FMT_RGB24)
  942. get_sub_picture(s, 0, y,
  943. s->input_frame->data, s->input_frame->linesize,
  944. data, linesize);
  945. else
  946. get_sub_picture(s, 0, y,
  947. (uint8_t **)frame->data, (int *)frame->linesize,
  948. data, linesize);
  949. get_sub_picture(s, 0, y,
  950. s->last_frame->data, s->last_frame->linesize,
  951. last_data, last_linesize);
  952. get_sub_picture(s, 0, y,
  953. s->scratch_frame->data, s->scratch_frame->linesize,
  954. scratch_data, scratch_linesize);
  955. if ((temp_size = rd_strip(s, y, strip_height, isakeyframe,
  956. last_data, last_linesize, data, linesize,
  957. scratch_data, scratch_linesize,
  958. s->frame_buf + size + CVID_HEADER_SIZE,
  959. &score_temp)) < 0)
  960. return temp_size;
  961. score += score_temp;
  962. size += temp_size;
  963. }
  964. if (best_score == 0 || score < best_score) {
  965. best_score = score;
  966. best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size, isakeyframe);
  967. FFSWAP(AVFrame *, s->best_frame, s->scratch_frame);
  968. memcpy(buf, s->frame_buf, best_size);
  969. best_nstrips = num_strips;
  970. }
  971. // avoid trying too many strip numbers without a real reason
  972. // (this makes the processing of the very first frame faster)
  973. if (num_strips - best_nstrips > 4)
  974. break;
  975. }
  976. // let the number of strips slowly adapt to the changes in the contents,
  977. // compared to full bruteforcing every time this will occasionally lead
  978. // to some r/d performance loss but makes encoding up to several times faster
  979. if (!s->strip_number_delta_range) {
  980. if (best_nstrips == s->max_strips) { // let us try to step up
  981. s->max_strips = best_nstrips + 1;
  982. if (s->max_strips >= s->max_max_strips)
  983. s->max_strips = s->max_max_strips;
  984. } else { // try to step down
  985. s->max_strips = best_nstrips;
  986. }
  987. s->min_strips = s->max_strips - 1;
  988. if (s->min_strips < s->min_min_strips)
  989. s->min_strips = s->min_min_strips;
  990. } else {
  991. s->max_strips = best_nstrips + s->strip_number_delta_range;
  992. if (s->max_strips >= s->max_max_strips)
  993. s->max_strips = s->max_max_strips;
  994. s->min_strips = best_nstrips - s->strip_number_delta_range;
  995. if (s->min_strips < s->min_min_strips)
  996. s->min_strips = s->min_min_strips;
  997. }
  998. return best_size;
  999. }
  1000. static int cinepak_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1001. const AVFrame *frame, int *got_packet)
  1002. {
  1003. CinepakEncContext *s = avctx->priv_data;
  1004. int ret;
  1005. s->lambda = frame->quality ? frame->quality - 1 : 2 * FF_LAMBDA_SCALE;
  1006. if ((ret = ff_alloc_packet(pkt, s->frame_buf_size)) < 0)
  1007. return ret;
  1008. ret = rd_frame(s, frame, (s->curframe == 0), pkt->data, s->frame_buf_size);
  1009. pkt->size = ret;
  1010. if (s->curframe == 0)
  1011. pkt->flags |= AV_PKT_FLAG_KEY;
  1012. *got_packet = 1;
  1013. FFSWAP(AVFrame *, s->last_frame, s->best_frame);
  1014. if (++s->curframe >= s->keyint)
  1015. s->curframe = 0;
  1016. return 0;
  1017. }
  1018. static av_cold int cinepak_encode_end(AVCodecContext *avctx)
  1019. {
  1020. CinepakEncContext *s = avctx->priv_data;
  1021. int x;
  1022. av_frame_free(&s->last_frame);
  1023. av_frame_free(&s->best_frame);
  1024. av_frame_free(&s->scratch_frame);
  1025. if (avctx->pix_fmt == AV_PIX_FMT_RGB24)
  1026. av_frame_free(&s->input_frame);
  1027. av_freep(&s->codebook_input);
  1028. av_freep(&s->codebook_closest);
  1029. av_freep(&s->strip_buf);
  1030. av_freep(&s->frame_buf);
  1031. av_freep(&s->mb);
  1032. for (x = 0; x < (avctx->pix_fmt == AV_PIX_FMT_RGB24 ? 4 : 3); x++)
  1033. av_freep(&s->pict_bufs[x]);
  1034. return 0;
  1035. }
  1036. AVCodec ff_cinepak_encoder = {
  1037. .name = "cinepak",
  1038. .long_name = NULL_IF_CONFIG_SMALL("Cinepak"),
  1039. .type = AVMEDIA_TYPE_VIDEO,
  1040. .id = AV_CODEC_ID_CINEPAK,
  1041. .priv_data_size = sizeof(CinepakEncContext),
  1042. .init = cinepak_encode_init,
  1043. .encode2 = cinepak_encode_frame,
  1044. .close = cinepak_encode_end,
  1045. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_RGB24, AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE },
  1046. .priv_class = &cinepak_class,
  1047. };