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.

796 lines
26KB

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