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.

876 lines
30KB

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