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.

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