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.

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