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.

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