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.

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