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.

828 lines
28KB

  1. /*
  2. * Interface to xvidcore for mpeg4 encoding
  3. * Copyright (c) 2004 Adam Thayer <krevnik@comcast.net>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Interface to xvidcore for MPEG-4 compliant encoding.
  24. * @author Adam Thayer (krevnik@comcast.net)
  25. */
  26. #include <unistd.h>
  27. #include <xvid.h>
  28. #include "libavutil/cpu.h"
  29. #include "libavutil/intreadwrite.h"
  30. #include "libavutil/mathematics.h"
  31. #include "avcodec.h"
  32. #include "libxvid.h"
  33. #include "mpegvideo.h"
  34. /**
  35. * Buffer management macros.
  36. */
  37. #define BUFFER_SIZE 1024
  38. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  39. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  40. /**
  41. * Structure for the private Xvid context.
  42. * This stores all the private context for the codec.
  43. */
  44. struct xvid_context {
  45. AVClass *class; /**< Handle for Xvid encoder */
  46. void *encoder_handle; /**< Handle for Xvid encoder */
  47. int xsize; /**< Frame x size */
  48. int ysize; /**< Frame y size */
  49. int vop_flags; /**< VOP flags for Xvid encoder */
  50. int vol_flags; /**< VOL flags for Xvid encoder */
  51. int me_flags; /**< Motion Estimation flags */
  52. int qscale; /**< Do we use constant scale? */
  53. int quicktime_format; /**< Are we in a QT-based format? */
  54. char *twopassbuffer; /**< Character buffer for two-pass */
  55. char *old_twopassbuffer; /**< Old character buffer (two-pass) */
  56. char *twopassfile; /**< second pass temp file name */
  57. unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
  58. unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
  59. int lumi_aq; /**< Lumi masking as an aq method */
  60. int variance_aq; /**< Variance adaptive quantization */
  61. int ssim; /**< SSIM information display mode */
  62. int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
  63. int gmc;
  64. };
  65. /**
  66. * Structure for the private first-pass plugin.
  67. */
  68. struct xvid_ff_pass1 {
  69. int version; /**< Xvid version */
  70. struct xvid_context *context; /**< Pointer to private context */
  71. };
  72. /*
  73. * Xvid 2-Pass Kludge Section
  74. *
  75. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  76. * this section spends time replacing the first pass plugin so we can write
  77. * statistic information as libavcodec requests in. We have another kludge
  78. * that allows us to pass data to the second pass in Xvid without a custom
  79. * rate-control plugin.
  80. */
  81. /**
  82. * Initialize the two-pass plugin and context.
  83. *
  84. * @param param Input construction parameter structure
  85. * @param handle Private context handle
  86. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  87. */
  88. static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
  89. {
  90. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
  91. char *log = x->context->twopassbuffer;
  92. /* Do a quick bounds check */
  93. if (!log)
  94. return XVID_ERR_FAIL;
  95. /* We use snprintf() */
  96. /* This is because we can safely prevent a buffer overflow */
  97. log[0] = 0;
  98. snprintf(log, BUFFER_REMAINING(log),
  99. "# avconv 2-pass log file, using xvid codec\n");
  100. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  101. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  102. XVID_VERSION_MAJOR(XVID_VERSION),
  103. XVID_VERSION_MINOR(XVID_VERSION),
  104. XVID_VERSION_PATCH(XVID_VERSION));
  105. *handle = x->context;
  106. return 0;
  107. }
  108. /**
  109. * Destroy the two-pass plugin context.
  110. *
  111. * @param ref Context pointer for the plugin
  112. * @param param Destrooy context
  113. * @return Returns 0, success guaranteed
  114. */
  115. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  116. xvid_plg_destroy_t *param)
  117. {
  118. /* Currently cannot think of anything to do on destruction */
  119. /* Still, the framework should be here for reference/use */
  120. if (ref->twopassbuffer)
  121. ref->twopassbuffer[0] = 0;
  122. return 0;
  123. }
  124. /**
  125. * Enable fast encode mode during the first pass.
  126. *
  127. * @param ref Context pointer for the plugin
  128. * @param param Frame data
  129. * @return Returns 0, success guaranteed
  130. */
  131. static int xvid_ff_2pass_before(struct xvid_context *ref,
  132. xvid_plg_data_t *param)
  133. {
  134. int motion_remove;
  135. int motion_replacements;
  136. int vop_remove;
  137. /* Nothing to do here, result is changed too much */
  138. if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
  139. return 0;
  140. /* We can implement a 'turbo' first pass mode here */
  141. param->quant = 2;
  142. /* Init values */
  143. motion_remove = ~XVID_ME_CHROMA_PVOP &
  144. ~XVID_ME_CHROMA_BVOP &
  145. ~XVID_ME_EXTSEARCH16 &
  146. ~XVID_ME_ADVANCEDDIAMOND16;
  147. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  148. XVID_ME_SKIP_DELTASEARCH |
  149. XVID_ME_FASTREFINE16 |
  150. XVID_ME_BFRAME_EARLYSTOP;
  151. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  152. ~XVID_VOP_FAST_MODEDECISION_RD &
  153. ~XVID_VOP_TRELLISQUANT &
  154. ~XVID_VOP_INTER4V &
  155. ~XVID_VOP_HQACPRED;
  156. param->vol_flags &= ~XVID_VOL_GMC;
  157. param->vop_flags &= vop_remove;
  158. param->motion_flags &= motion_remove;
  159. param->motion_flags |= motion_replacements;
  160. return 0;
  161. }
  162. /**
  163. * Capture statistic data and write it during first pass.
  164. *
  165. * @param ref Context pointer for the plugin
  166. * @param param Statistic data
  167. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  168. */
  169. static int xvid_ff_2pass_after(struct xvid_context *ref,
  170. xvid_plg_data_t *param)
  171. {
  172. char *log = ref->twopassbuffer;
  173. const char *frame_types = " ipbs";
  174. char frame_type;
  175. /* Quick bounds check */
  176. if (!log)
  177. return XVID_ERR_FAIL;
  178. /* Convert the type given to us into a character */
  179. if (param->type < 5 && param->type > 0)
  180. frame_type = frame_types[param->type];
  181. else
  182. return XVID_ERR_FAIL;
  183. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  184. "%c %d %d %d %d %d %d\n",
  185. frame_type, param->stats.quant, param->stats.kblks,
  186. param->stats.mblks, param->stats.ublks,
  187. param->stats.length, param->stats.hlength);
  188. return 0;
  189. }
  190. /**
  191. * Dispatch function for our custom plugin.
  192. * This handles the dispatch for the Xvid plugin. It passes data
  193. * on to other functions for actual processing.
  194. *
  195. * @param ref Context pointer for the plugin
  196. * @param cmd The task given for us to complete
  197. * @param p1 First parameter (varies)
  198. * @param p2 Second parameter (varies)
  199. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  200. */
  201. static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
  202. {
  203. switch (cmd) {
  204. case XVID_PLG_INFO:
  205. case XVID_PLG_FRAME:
  206. return 0;
  207. case XVID_PLG_BEFORE:
  208. return xvid_ff_2pass_before(ref, p1);
  209. case XVID_PLG_CREATE:
  210. return xvid_ff_2pass_create(p1, p2);
  211. case XVID_PLG_AFTER:
  212. return xvid_ff_2pass_after(ref, p1);
  213. case XVID_PLG_DESTROY:
  214. return xvid_ff_2pass_destroy(ref, p1);
  215. default:
  216. return XVID_ERR_FAIL;
  217. }
  218. }
  219. /**
  220. * Routine to create a global VO/VOL header for MP4 container.
  221. * What we do here is extract the header from the Xvid bitstream
  222. * as it is encoded. We also strip the repeated headers from the
  223. * bitstream when a global header is requested for MPEG-4 ISO
  224. * compliance.
  225. *
  226. * @param avctx AVCodecContext pointer to context
  227. * @param frame Pointer to encoded frame data
  228. * @param header_len Length of header to search
  229. * @param frame_len Length of encoded frame data
  230. * @return Returns new length of frame data
  231. */
  232. static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
  233. unsigned int header_len,
  234. unsigned int frame_len)
  235. {
  236. int vo_len = 0, i;
  237. for (i = 0; i < header_len - 3; i++) {
  238. if (pkt->data[i] == 0x00 &&
  239. pkt->data[i + 1] == 0x00 &&
  240. pkt->data[i + 2] == 0x01 &&
  241. pkt->data[i + 3] == 0xB6) {
  242. vo_len = i;
  243. break;
  244. }
  245. }
  246. if (vo_len > 0) {
  247. /* We need to store the header, so extract it */
  248. if (!avctx->extradata) {
  249. avctx->extradata = av_malloc(vo_len);
  250. memcpy(avctx->extradata, pkt->data, vo_len);
  251. avctx->extradata_size = vo_len;
  252. }
  253. /* Less dangerous now, memmove properly copies the two
  254. * chunks of overlapping data */
  255. memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
  256. pkt->size = frame_len - vo_len;
  257. }
  258. return 0;
  259. }
  260. /**
  261. * Routine to correct a possibly erroneous framerate being fed to us.
  262. * Xvid currently chokes on framerates where the ticks per frame is
  263. * extremely large. This function works to correct problems in this area
  264. * by estimating a new framerate and taking the simpler fraction of
  265. * the two presented.
  266. *
  267. * @param avctx Context that contains the framerate to correct.
  268. */
  269. static void xvid_correct_framerate(AVCodecContext *avctx)
  270. {
  271. int frate, fbase;
  272. int est_frate, est_fbase;
  273. int gcd;
  274. float est_fps, fps;
  275. frate = avctx->time_base.den;
  276. fbase = avctx->time_base.num;
  277. gcd = av_gcd(frate, fbase);
  278. if (gcd > 1) {
  279. frate /= gcd;
  280. fbase /= gcd;
  281. }
  282. if (frate <= 65000 && fbase <= 65000) {
  283. avctx->time_base.den = frate;
  284. avctx->time_base.num = fbase;
  285. return;
  286. }
  287. fps = (float) frate / (float) fbase;
  288. est_fps = roundf(fps * 1000.0) / 1000.0;
  289. est_frate = (int) est_fps;
  290. if (est_fps > (int) est_fps) {
  291. est_frate = (est_frate + 1) * 1000;
  292. est_fbase = (int) roundf((float) est_frate / est_fps);
  293. } else
  294. est_fbase = 1;
  295. gcd = av_gcd(est_frate, est_fbase);
  296. if (gcd > 1) {
  297. est_frate /= gcd;
  298. est_fbase /= gcd;
  299. }
  300. if (fbase > est_fbase) {
  301. avctx->time_base.den = est_frate;
  302. avctx->time_base.num = est_fbase;
  303. av_log(avctx, AV_LOG_DEBUG,
  304. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  305. est_fps, (((est_fps - fps) / fps) * 100.0));
  306. } else {
  307. avctx->time_base.den = frate;
  308. avctx->time_base.num = fbase;
  309. }
  310. }
  311. static av_cold int xvid_encode_init(AVCodecContext *avctx)
  312. {
  313. int xerr, i;
  314. int xvid_flags = avctx->flags;
  315. struct xvid_context *x = avctx->priv_data;
  316. uint16_t *intra, *inter;
  317. int fd;
  318. xvid_plugin_single_t single = { 0 };
  319. struct xvid_ff_pass1 rc2pass1 = { 0 };
  320. xvid_plugin_2pass2_t rc2pass2 = { 0 };
  321. xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */
  322. xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */
  323. xvid_plugin_ssim_t ssim = { 0 };
  324. xvid_gbl_init_t xvid_gbl_init = { 0 };
  325. xvid_enc_create_t xvid_enc_create = { 0 };
  326. xvid_enc_plugin_t plugins[7];
  327. /* Bring in VOP flags from avconv command-line */
  328. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  329. if (xvid_flags & CODEC_FLAG_4MV)
  330. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  331. if (avctx->trellis)
  332. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  333. if (xvid_flags & CODEC_FLAG_AC_PRED)
  334. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  335. if (xvid_flags & CODEC_FLAG_GRAY)
  336. x->vop_flags |= XVID_VOP_GREYSCALE;
  337. /* Decide which ME quality setting to use */
  338. x->me_flags = 0;
  339. switch (avctx->me_method) {
  340. case ME_FULL: /* Quality 6 */
  341. x->me_flags |= XVID_ME_EXTSEARCH16 |
  342. XVID_ME_EXTSEARCH8;
  343. case ME_EPZS: /* Quality 4 */
  344. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  345. XVID_ME_HALFPELREFINE8 |
  346. XVID_ME_CHROMA_PVOP |
  347. XVID_ME_CHROMA_BVOP;
  348. case ME_LOG: /* Quality 2 */
  349. case ME_PHODS:
  350. case ME_X1:
  351. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  352. XVID_ME_HALFPELREFINE16;
  353. case ME_ZERO: /* Quality 0 */
  354. default:
  355. break;
  356. }
  357. /* Decide how we should decide blocks */
  358. switch (avctx->mb_decision) {
  359. case 2:
  360. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  361. x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
  362. XVID_ME_QUARTERPELREFINE8_RD |
  363. XVID_ME_EXTSEARCH_RD |
  364. XVID_ME_CHECKPREDICTION_RD;
  365. case 1:
  366. if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
  367. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  368. x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
  369. XVID_ME_QUARTERPELREFINE16_RD;
  370. default:
  371. break;
  372. }
  373. /* Bring in VOL flags from avconv command-line */
  374. #if FF_API_GMC
  375. if (avctx->flags & CODEC_FLAG_GMC)
  376. x->gmc = 1;
  377. #endif
  378. x->vol_flags = 0;
  379. if (x->gmc) {
  380. x->vol_flags |= XVID_VOL_GMC;
  381. x->me_flags |= XVID_ME_GME_REFINE;
  382. }
  383. if (xvid_flags & CODEC_FLAG_QPEL) {
  384. x->vol_flags |= XVID_VOL_QUARTERPEL;
  385. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  386. if (x->vop_flags & XVID_VOP_INTER4V)
  387. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  388. }
  389. xvid_gbl_init.version = XVID_VERSION;
  390. xvid_gbl_init.debug = 0;
  391. xvid_gbl_init.cpu_flags = 0;
  392. /* Initialize */
  393. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  394. /* Create the encoder reference */
  395. xvid_enc_create.version = XVID_VERSION;
  396. /* Store the desired frame size */
  397. xvid_enc_create.width =
  398. x->xsize = avctx->width;
  399. xvid_enc_create.height =
  400. x->ysize = avctx->height;
  401. /* Xvid can determine the proper profile to use */
  402. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  403. /* We don't use zones */
  404. xvid_enc_create.zones = NULL;
  405. xvid_enc_create.num_zones = 0;
  406. xvid_enc_create.num_threads = avctx->thread_count;
  407. xvid_enc_create.plugins = plugins;
  408. xvid_enc_create.num_plugins = 0;
  409. /* Initialize Buffers */
  410. x->twopassbuffer = NULL;
  411. x->old_twopassbuffer = NULL;
  412. x->twopassfile = NULL;
  413. if (xvid_flags & CODEC_FLAG_PASS1) {
  414. rc2pass1.version = XVID_VERSION;
  415. rc2pass1.context = x;
  416. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  417. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  418. if (!x->twopassbuffer || !x->old_twopassbuffer) {
  419. av_log(avctx, AV_LOG_ERROR,
  420. "Xvid: Cannot allocate 2-pass log buffers\n");
  421. return -1;
  422. }
  423. x->twopassbuffer[0] =
  424. x->old_twopassbuffer[0] = 0;
  425. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  426. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  427. xvid_enc_create.num_plugins++;
  428. } else if (xvid_flags & CODEC_FLAG_PASS2) {
  429. rc2pass2.version = XVID_VERSION;
  430. rc2pass2.bitrate = avctx->bit_rate;
  431. fd = ff_tempfile("xvidff.", &x->twopassfile);
  432. if (fd == -1) {
  433. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
  434. return -1;
  435. }
  436. if (!avctx->stats_in) {
  437. av_log(avctx, AV_LOG_ERROR,
  438. "Xvid: No 2-pass information loaded for second pass\n");
  439. return -1;
  440. }
  441. if (strlen(avctx->stats_in) >
  442. write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
  443. close(fd);
  444. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
  445. return -1;
  446. }
  447. close(fd);
  448. rc2pass2.filename = x->twopassfile;
  449. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  450. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  451. xvid_enc_create.num_plugins++;
  452. } else if (!(xvid_flags & CODEC_FLAG_QSCALE)) {
  453. /* Single Pass Bitrate Control! */
  454. single.version = XVID_VERSION;
  455. single.bitrate = avctx->bit_rate;
  456. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  457. plugins[xvid_enc_create.num_plugins].param = &single;
  458. xvid_enc_create.num_plugins++;
  459. }
  460. if (avctx->lumi_masking != 0.0)
  461. x->lumi_aq = 1;
  462. if (x->lumi_aq && x->variance_aq) {
  463. x->variance_aq = 0;
  464. av_log(avctx, AV_LOG_WARNING,
  465. "variance_aq is ignored when lumi_aq is set.\n");
  466. }
  467. /* Luminance Masking */
  468. if (x->lumi_aq) {
  469. masking_l.method = 0;
  470. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  471. /* The old behavior is that when avctx->lumi_masking is specified,
  472. * plugins[...].param = NULL. Trying to keep the old behavior here. */
  473. plugins[xvid_enc_create.num_plugins].param =
  474. avctx->lumi_masking ? NULL : &masking_l;
  475. xvid_enc_create.num_plugins++;
  476. }
  477. /* Variance AQ */
  478. if (x->variance_aq) {
  479. masking_v.method = 1;
  480. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  481. plugins[xvid_enc_create.num_plugins].param = &masking_v;
  482. xvid_enc_create.num_plugins++;
  483. }
  484. /* SSIM */
  485. if (x->ssim) {
  486. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
  487. ssim.b_printstat = x->ssim == 2;
  488. ssim.acc = x->ssim_acc;
  489. ssim.cpu_flags = xvid_gbl_init.cpu_flags;
  490. ssim.b_visualize = 0;
  491. plugins[xvid_enc_create.num_plugins].param = &ssim;
  492. xvid_enc_create.num_plugins++;
  493. }
  494. /* Frame Rate and Key Frames */
  495. xvid_correct_framerate(avctx);
  496. xvid_enc_create.fincr = avctx->time_base.num;
  497. xvid_enc_create.fbase = avctx->time_base.den;
  498. if (avctx->gop_size > 0)
  499. xvid_enc_create.max_key_interval = avctx->gop_size;
  500. else
  501. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  502. /* Quants */
  503. if (xvid_flags & CODEC_FLAG_QSCALE)
  504. x->qscale = 1;
  505. else
  506. x->qscale = 0;
  507. xvid_enc_create.min_quant[0] = avctx->qmin;
  508. xvid_enc_create.min_quant[1] = avctx->qmin;
  509. xvid_enc_create.min_quant[2] = avctx->qmin;
  510. xvid_enc_create.max_quant[0] = avctx->qmax;
  511. xvid_enc_create.max_quant[1] = avctx->qmax;
  512. xvid_enc_create.max_quant[2] = avctx->qmax;
  513. /* Quant Matrices */
  514. x->intra_matrix =
  515. x->inter_matrix = NULL;
  516. if (avctx->mpeg_quant)
  517. x->vol_flags |= XVID_VOL_MPEGQUANT;
  518. if ((avctx->intra_matrix || avctx->inter_matrix)) {
  519. x->vol_flags |= XVID_VOL_MPEGQUANT;
  520. if (avctx->intra_matrix) {
  521. intra = avctx->intra_matrix;
  522. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  523. } else
  524. intra = NULL;
  525. if (avctx->inter_matrix) {
  526. inter = avctx->inter_matrix;
  527. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  528. } else
  529. inter = NULL;
  530. for (i = 0; i < 64; i++) {
  531. if (intra)
  532. x->intra_matrix[i] = (unsigned char) intra[i];
  533. if (inter)
  534. x->inter_matrix[i] = (unsigned char) inter[i];
  535. }
  536. }
  537. /* Misc Settings */
  538. xvid_enc_create.frame_drop_ratio = 0;
  539. xvid_enc_create.global = 0;
  540. if (xvid_flags & CODEC_FLAG_CLOSED_GOP)
  541. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  542. /* Determines which codec mode we are operating in */
  543. avctx->extradata = NULL;
  544. avctx->extradata_size = 0;
  545. if (xvid_flags & CODEC_FLAG_GLOBAL_HEADER) {
  546. /* In this case, we are claiming to be MPEG4 */
  547. x->quicktime_format = 1;
  548. avctx->codec_id = AV_CODEC_ID_MPEG4;
  549. } else {
  550. /* We are claiming to be Xvid */
  551. x->quicktime_format = 0;
  552. if (!avctx->codec_tag)
  553. avctx->codec_tag = AV_RL32("xvid");
  554. }
  555. /* Bframes */
  556. xvid_enc_create.max_bframes = avctx->max_b_frames;
  557. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  558. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  559. if (avctx->max_b_frames > 0 && !x->quicktime_format)
  560. xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  561. /* Create encoder context */
  562. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  563. if (xerr) {
  564. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  565. return -1;
  566. }
  567. x->encoder_handle = xvid_enc_create.handle;
  568. avctx->coded_frame = av_frame_alloc();
  569. if (!avctx->coded_frame)
  570. return AVERROR(ENOMEM);
  571. return 0;
  572. }
  573. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  574. const AVFrame *picture, int *got_packet)
  575. {
  576. int xerr, i, ret, user_packet = !!pkt->data;
  577. struct xvid_context *x = avctx->priv_data;
  578. AVFrame *p = avctx->coded_frame;
  579. int mb_width = (avctx->width + 15) / 16;
  580. int mb_height = (avctx->height + 15) / 16;
  581. char *tmp;
  582. xvid_enc_frame_t xvid_enc_frame = { 0 };
  583. xvid_enc_stats_t xvid_enc_stats = { 0 };
  584. if (!user_packet &&
  585. (ret = av_new_packet(pkt, mb_width * mb_height * MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0) {
  586. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  587. return ret;
  588. }
  589. /* Start setting up the frame */
  590. xvid_enc_frame.version = XVID_VERSION;
  591. xvid_enc_stats.version = XVID_VERSION;
  592. /* Let Xvid know where to put the frame. */
  593. xvid_enc_frame.bitstream = pkt->data;
  594. xvid_enc_frame.length = pkt->size;
  595. /* Initialize input image fields */
  596. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  597. av_log(avctx, AV_LOG_ERROR,
  598. "Xvid: Color spaces other than 420P not supported\n");
  599. return -1;
  600. }
  601. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  602. for (i = 0; i < 4; i++) {
  603. xvid_enc_frame.input.plane[i] = picture->data[i];
  604. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  605. }
  606. /* Encoder Flags */
  607. xvid_enc_frame.vop_flags = x->vop_flags;
  608. xvid_enc_frame.vol_flags = x->vol_flags;
  609. xvid_enc_frame.motion = x->me_flags;
  610. xvid_enc_frame.type =
  611. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  612. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  613. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  614. XVID_TYPE_AUTO;
  615. /* Pixel aspect ratio setting */
  616. if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
  617. avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
  618. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  619. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  620. return -1;
  621. }
  622. xvid_enc_frame.par = XVID_PAR_EXT;
  623. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  624. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  625. /* Quant Setting */
  626. if (x->qscale)
  627. xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  628. else
  629. xvid_enc_frame.quant = 0;
  630. /* Matrices */
  631. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  632. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  633. /* Encode */
  634. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  635. &xvid_enc_frame, &xvid_enc_stats);
  636. /* Two-pass log buffer swapping */
  637. avctx->stats_out = NULL;
  638. if (x->twopassbuffer) {
  639. tmp = x->old_twopassbuffer;
  640. x->old_twopassbuffer = x->twopassbuffer;
  641. x->twopassbuffer = tmp;
  642. x->twopassbuffer[0] = 0;
  643. if (x->old_twopassbuffer[0] != 0) {
  644. avctx->stats_out = x->old_twopassbuffer;
  645. }
  646. }
  647. if (xerr > 0) {
  648. *got_packet = 1;
  649. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  650. if (xvid_enc_stats.type == XVID_TYPE_PVOP)
  651. p->pict_type = AV_PICTURE_TYPE_P;
  652. else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
  653. p->pict_type = AV_PICTURE_TYPE_B;
  654. else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
  655. p->pict_type = AV_PICTURE_TYPE_S;
  656. else
  657. p->pict_type = AV_PICTURE_TYPE_I;
  658. if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
  659. p->key_frame = 1;
  660. pkt->flags |= AV_PKT_FLAG_KEY;
  661. if (x->quicktime_format)
  662. return xvid_strip_vol_header(avctx, pkt,
  663. xvid_enc_stats.hlength, xerr);
  664. } else
  665. p->key_frame = 0;
  666. pkt->size = xerr;
  667. return 0;
  668. } else {
  669. if (!user_packet)
  670. av_free_packet(pkt);
  671. if (!xerr)
  672. return 0;
  673. av_log(avctx, AV_LOG_ERROR,
  674. "Xvid: Encoding Error Occurred: %i\n", xerr);
  675. return -1;
  676. }
  677. }
  678. static av_cold int xvid_encode_close(AVCodecContext *avctx)
  679. {
  680. struct xvid_context *x = avctx->priv_data;
  681. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  682. av_freep(&avctx->extradata);
  683. if (x->twopassbuffer) {
  684. av_free(x->twopassbuffer);
  685. av_free(x->old_twopassbuffer);
  686. }
  687. av_free(x->twopassfile);
  688. av_free(x->intra_matrix);
  689. av_free(x->inter_matrix);
  690. return 0;
  691. }
  692. #define OFFSET(x) offsetof(struct xvid_context, x)
  693. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  694. static const AVOption options[] = {
  695. { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  696. { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  697. { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
  698. { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
  699. { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
  700. { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
  701. { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
  702. { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  703. { NULL },
  704. };
  705. static const AVClass xvid_class = {
  706. .class_name = "libxvid",
  707. .item_name = av_default_item_name,
  708. .option = options,
  709. .version = LIBAVUTIL_VERSION_INT,
  710. };
  711. AVCodec ff_libxvid_encoder = {
  712. .name = "libxvid",
  713. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  714. .type = AVMEDIA_TYPE_VIDEO,
  715. .id = AV_CODEC_ID_MPEG4,
  716. .priv_data_size = sizeof(struct xvid_context),
  717. .init = xvid_encode_init,
  718. .encode2 = xvid_encode_frame,
  719. .close = xvid_encode_close,
  720. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  721. .priv_class = &xvid_class,
  722. };