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.

927 lines
31KB

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