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.

852 lines
29KB

  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. 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[4];
  336. x->twopassfd = -1;
  337. /* Bring in VOP flags from ffmpeg command-line */
  338. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  339. if (xvid_flags & 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 & CODEC_FLAG_AC_PRED)
  344. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  345. if (xvid_flags & 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 (avctx->me_method) {
  350. case ME_FULL: /* Quality 6 */
  351. x->me_flags |= XVID_ME_EXTSEARCH16 |
  352. XVID_ME_EXTSEARCH8;
  353. case ME_EPZS: /* Quality 4 */
  354. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  355. XVID_ME_HALFPELREFINE8 |
  356. XVID_ME_CHROMA_PVOP |
  357. XVID_ME_CHROMA_BVOP;
  358. case ME_LOG: /* Quality 2 */
  359. case ME_PHODS:
  360. case ME_X1:
  361. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  362. XVID_ME_HALFPELREFINE16;
  363. case ME_ZERO: /* Quality 0 */
  364. default:
  365. break;
  366. }
  367. /* Decide how we should decide blocks */
  368. switch (avctx->mb_decision) {
  369. case 2:
  370. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  371. x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
  372. XVID_ME_QUARTERPELREFINE8_RD |
  373. XVID_ME_EXTSEARCH_RD |
  374. XVID_ME_CHECKPREDICTION_RD;
  375. case 1:
  376. if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
  377. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  378. x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
  379. XVID_ME_QUARTERPELREFINE16_RD;
  380. default:
  381. break;
  382. }
  383. /* Bring in VOL flags from ffmpeg command-line */
  384. #if FF_API_GMC
  385. if (avctx->flags & CODEC_FLAG_GMC)
  386. x->gmc = 1;
  387. #endif
  388. x->vol_flags = 0;
  389. if (x->gmc) {
  390. x->vol_flags |= XVID_VOL_GMC;
  391. x->me_flags |= XVID_ME_GME_REFINE;
  392. }
  393. if (xvid_flags & CODEC_FLAG_QPEL) {
  394. x->vol_flags |= XVID_VOL_QUARTERPEL;
  395. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  396. if (x->vop_flags & XVID_VOP_INTER4V)
  397. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  398. }
  399. xvid_gbl_init.version = XVID_VERSION;
  400. xvid_gbl_init.debug = 0;
  401. xvid_gbl_init.cpu_flags = 0;
  402. /* Initialize */
  403. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  404. /* Create the encoder reference */
  405. xvid_enc_create.version = XVID_VERSION;
  406. /* Store the desired frame size */
  407. xvid_enc_create.width =
  408. x->xsize = avctx->width;
  409. xvid_enc_create.height =
  410. x->ysize = avctx->height;
  411. /* Xvid can determine the proper profile to use */
  412. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  413. /* We don't use zones */
  414. xvid_enc_create.zones = NULL;
  415. xvid_enc_create.num_zones = 0;
  416. xvid_enc_create.num_threads = avctx->thread_count;
  417. xvid_enc_create.plugins = plugins;
  418. xvid_enc_create.num_plugins = 0;
  419. /* Initialize Buffers */
  420. x->twopassbuffer = NULL;
  421. x->old_twopassbuffer = NULL;
  422. x->twopassfile = NULL;
  423. if (xvid_flags & CODEC_FLAG_PASS1) {
  424. rc2pass1.version = XVID_VERSION;
  425. rc2pass1.context = x;
  426. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  427. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  428. if (!x->twopassbuffer || !x->old_twopassbuffer) {
  429. av_log(avctx, AV_LOG_ERROR,
  430. "Xvid: Cannot allocate 2-pass log buffers\n");
  431. goto fail;
  432. }
  433. x->twopassbuffer[0] =
  434. x->old_twopassbuffer[0] = 0;
  435. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  436. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  437. xvid_enc_create.num_plugins++;
  438. } else if (xvid_flags & CODEC_FLAG_PASS2) {
  439. rc2pass2.version = XVID_VERSION;
  440. rc2pass2.bitrate = avctx->bit_rate;
  441. fd = av_tempfile("xvidff.", &x->twopassfile, 0, avctx);
  442. if (fd == -1) {
  443. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
  444. goto fail;
  445. }
  446. x->twopassfd = fd;
  447. if (!avctx->stats_in) {
  448. av_log(avctx, AV_LOG_ERROR,
  449. "Xvid: No 2-pass information loaded for second pass\n");
  450. goto fail;
  451. }
  452. if (strlen(avctx->stats_in) >
  453. write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
  454. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
  455. goto fail;
  456. }
  457. rc2pass2.filename = x->twopassfile;
  458. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  459. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  460. xvid_enc_create.num_plugins++;
  461. } else if (!(xvid_flags & CODEC_FLAG_QSCALE)) {
  462. /* Single Pass Bitrate Control! */
  463. single.version = XVID_VERSION;
  464. single.bitrate = avctx->bit_rate;
  465. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  466. plugins[xvid_enc_create.num_plugins].param = &single;
  467. xvid_enc_create.num_plugins++;
  468. }
  469. if (avctx->lumi_masking != 0.0)
  470. x->lumi_aq = 1;
  471. /* Luminance Masking */
  472. if (x->lumi_aq) {
  473. masking_l.method = 0;
  474. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  475. /* The old behavior is that when avctx->lumi_masking is specified,
  476. * plugins[...].param = NULL. Trying to keep the old behavior here. */
  477. plugins[xvid_enc_create.num_plugins].param =
  478. avctx->lumi_masking ? NULL : &masking_l;
  479. xvid_enc_create.num_plugins++;
  480. }
  481. /* Variance AQ */
  482. if (x->variance_aq) {
  483. masking_v.method = 1;
  484. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  485. plugins[xvid_enc_create.num_plugins].param = &masking_v;
  486. xvid_enc_create.num_plugins++;
  487. }
  488. if (x->lumi_aq && x->variance_aq )
  489. av_log(avctx, AV_LOG_INFO,
  490. "Both lumi_aq and variance_aq are enabled. The resulting quality"
  491. "will be the worse one of the two effects made by the AQ.\n");
  492. /* SSIM */
  493. if (x->ssim) {
  494. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
  495. ssim.b_printstat = x->ssim == 2;
  496. ssim.acc = x->ssim_acc;
  497. ssim.cpu_flags = xvid_gbl_init.cpu_flags;
  498. ssim.b_visualize = 0;
  499. plugins[xvid_enc_create.num_plugins].param = &ssim;
  500. xvid_enc_create.num_plugins++;
  501. }
  502. /* Frame Rate and Key Frames */
  503. xvid_correct_framerate(avctx);
  504. xvid_enc_create.fincr = avctx->time_base.num;
  505. xvid_enc_create.fbase = avctx->time_base.den;
  506. if (avctx->gop_size > 0)
  507. xvid_enc_create.max_key_interval = avctx->gop_size;
  508. else
  509. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  510. /* Quants */
  511. if (xvid_flags & CODEC_FLAG_QSCALE)
  512. x->qscale = 1;
  513. else
  514. x->qscale = 0;
  515. xvid_enc_create.min_quant[0] = avctx->qmin;
  516. xvid_enc_create.min_quant[1] = avctx->qmin;
  517. xvid_enc_create.min_quant[2] = avctx->qmin;
  518. xvid_enc_create.max_quant[0] = avctx->qmax;
  519. xvid_enc_create.max_quant[1] = avctx->qmax;
  520. xvid_enc_create.max_quant[2] = avctx->qmax;
  521. /* Quant Matrices */
  522. x->intra_matrix =
  523. x->inter_matrix = NULL;
  524. if (avctx->mpeg_quant)
  525. x->vol_flags |= XVID_VOL_MPEGQUANT;
  526. if ((avctx->intra_matrix || avctx->inter_matrix)) {
  527. x->vol_flags |= XVID_VOL_MPEGQUANT;
  528. if (avctx->intra_matrix) {
  529. intra = avctx->intra_matrix;
  530. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  531. } else
  532. intra = NULL;
  533. if (avctx->inter_matrix) {
  534. inter = avctx->inter_matrix;
  535. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  536. } else
  537. inter = NULL;
  538. for (i = 0; i < 64; i++) {
  539. if (intra)
  540. x->intra_matrix[i] = (unsigned char) intra[i];
  541. if (inter)
  542. x->inter_matrix[i] = (unsigned char) inter[i];
  543. }
  544. }
  545. /* Misc Settings */
  546. xvid_enc_create.frame_drop_ratio = 0;
  547. xvid_enc_create.global = 0;
  548. if (xvid_flags & CODEC_FLAG_CLOSED_GOP)
  549. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  550. /* Determines which codec mode we are operating in */
  551. avctx->extradata = NULL;
  552. avctx->extradata_size = 0;
  553. if (xvid_flags & CODEC_FLAG_GLOBAL_HEADER) {
  554. /* In this case, we are claiming to be MPEG4 */
  555. x->quicktime_format = 1;
  556. avctx->codec_id = AV_CODEC_ID_MPEG4;
  557. } else {
  558. /* We are claiming to be Xvid */
  559. x->quicktime_format = 0;
  560. if (!avctx->codec_tag)
  561. avctx->codec_tag = AV_RL32("xvid");
  562. }
  563. /* Bframes */
  564. xvid_enc_create.max_bframes = avctx->max_b_frames;
  565. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  566. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  567. if (avctx->max_b_frames > 0 && !x->quicktime_format)
  568. xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  569. av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));
  570. /* Create encoder context */
  571. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  572. if (xerr) {
  573. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  574. goto fail;
  575. }
  576. x->encoder_handle = xvid_enc_create.handle;
  577. avctx->coded_frame = av_frame_alloc();
  578. if (!avctx->coded_frame)
  579. return AVERROR(ENOMEM);
  580. return 0;
  581. fail:
  582. xvid_encode_close(avctx);
  583. return -1;
  584. }
  585. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  586. const AVFrame *picture, int *got_packet)
  587. {
  588. int xerr, i, ret, user_packet = !!pkt->data;
  589. struct xvid_context *x = avctx->priv_data;
  590. AVFrame *p = avctx->coded_frame;
  591. int mb_width = (avctx->width + 15) / 16;
  592. int mb_height = (avctx->height + 15) / 16;
  593. char *tmp;
  594. xvid_enc_frame_t xvid_enc_frame = { 0 };
  595. xvid_enc_stats_t xvid_enc_stats = { 0 };
  596. if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0)
  597. return ret;
  598. /* Start setting up the frame */
  599. xvid_enc_frame.version = XVID_VERSION;
  600. xvid_enc_stats.version = XVID_VERSION;
  601. /* Let Xvid know where to put the frame. */
  602. xvid_enc_frame.bitstream = pkt->data;
  603. xvid_enc_frame.length = pkt->size;
  604. /* Initialize input image fields */
  605. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  606. av_log(avctx, AV_LOG_ERROR,
  607. "Xvid: Color spaces other than 420P not supported\n");
  608. return AVERROR(EINVAL);
  609. }
  610. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  611. for (i = 0; i < 4; i++) {
  612. xvid_enc_frame.input.plane[i] = picture->data[i];
  613. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  614. }
  615. /* Encoder Flags */
  616. xvid_enc_frame.vop_flags = x->vop_flags;
  617. xvid_enc_frame.vol_flags = x->vol_flags;
  618. xvid_enc_frame.motion = x->me_flags;
  619. xvid_enc_frame.type =
  620. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  621. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  622. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  623. XVID_TYPE_AUTO;
  624. /* Pixel aspect ratio setting */
  625. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
  626. avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
  627. av_log(avctx, AV_LOG_WARNING,
  628. "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
  629. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  630. av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
  631. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 255);
  632. }
  633. xvid_enc_frame.par = XVID_PAR_EXT;
  634. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  635. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  636. /* Quant Setting */
  637. if (x->qscale)
  638. xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  639. else
  640. xvid_enc_frame.quant = 0;
  641. /* Matrices */
  642. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  643. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  644. /* Encode */
  645. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  646. &xvid_enc_frame, &xvid_enc_stats);
  647. /* Two-pass log buffer swapping */
  648. avctx->stats_out = NULL;
  649. if (x->twopassbuffer) {
  650. tmp = x->old_twopassbuffer;
  651. x->old_twopassbuffer = x->twopassbuffer;
  652. x->twopassbuffer = tmp;
  653. x->twopassbuffer[0] = 0;
  654. if (x->old_twopassbuffer[0] != 0) {
  655. avctx->stats_out = x->old_twopassbuffer;
  656. }
  657. }
  658. if (xerr > 0) {
  659. *got_packet = 1;
  660. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  661. if (xvid_enc_stats.type == XVID_TYPE_PVOP)
  662. p->pict_type = AV_PICTURE_TYPE_P;
  663. else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
  664. p->pict_type = AV_PICTURE_TYPE_B;
  665. else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
  666. p->pict_type = AV_PICTURE_TYPE_S;
  667. else
  668. p->pict_type = AV_PICTURE_TYPE_I;
  669. if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
  670. p->key_frame = 1;
  671. pkt->flags |= AV_PKT_FLAG_KEY;
  672. if (x->quicktime_format)
  673. return xvid_strip_vol_header(avctx, pkt,
  674. xvid_enc_stats.hlength, xerr);
  675. } else
  676. p->key_frame = 0;
  677. pkt->size = xerr;
  678. return 0;
  679. } else {
  680. if (!user_packet)
  681. av_free_packet(pkt);
  682. if (!xerr)
  683. return 0;
  684. av_log(avctx, AV_LOG_ERROR,
  685. "Xvid: Encoding Error Occurred: %i\n", xerr);
  686. return AVERROR_EXTERNAL;
  687. }
  688. }
  689. static av_cold int xvid_encode_close(AVCodecContext *avctx)
  690. {
  691. struct xvid_context *x = avctx->priv_data;
  692. if(x->encoder_handle)
  693. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  694. x->encoder_handle = NULL;
  695. av_freep(&avctx->extradata);
  696. if (x->twopassbuffer) {
  697. av_freep(&x->twopassbuffer);
  698. av_freep(&x->old_twopassbuffer);
  699. avctx->stats_out = NULL;
  700. }
  701. if (x->twopassfd>=0) {
  702. unlink(x->twopassfile);
  703. close(x->twopassfd);
  704. x->twopassfd = -1;
  705. }
  706. av_freep(&x->twopassfile);
  707. av_freep(&x->intra_matrix);
  708. av_freep(&x->inter_matrix);
  709. return 0;
  710. }
  711. #define OFFSET(x) offsetof(struct xvid_context, x)
  712. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  713. static const AVOption options[] = {
  714. { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  715. { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  716. { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
  717. { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
  718. { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
  719. { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
  720. { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
  721. { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  722. { NULL },
  723. };
  724. static const AVClass xvid_class = {
  725. .class_name = "libxvid",
  726. .item_name = av_default_item_name,
  727. .option = options,
  728. .version = LIBAVUTIL_VERSION_INT,
  729. };
  730. AVCodec ff_libxvid_encoder = {
  731. .name = "libxvid",
  732. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  733. .type = AVMEDIA_TYPE_VIDEO,
  734. .id = AV_CODEC_ID_MPEG4,
  735. .priv_data_size = sizeof(struct xvid_context),
  736. .init = xvid_encode_init,
  737. .encode2 = xvid_encode_frame,
  738. .close = xvid_encode_close,
  739. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  740. .priv_class = &xvid_class,
  741. };