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.

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