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.

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