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.

799 lines
26KB

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