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.

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