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.

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