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.

819 lines
27KB

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