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.

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