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.

783 lines
25KB

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