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.

803 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. /* Start setting up the frame */
  341. memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
  342. xvid_enc_frame.version = XVID_VERSION;
  343. memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
  344. xvid_enc_stats.version = XVID_VERSION;
  345. *p = *picture;
  346. /* Let Xvid know where to put the frame. */
  347. xvid_enc_frame.bitstream = pkt->data;
  348. xvid_enc_frame.length = pkt->size;
  349. /* Initialize input image fields */
  350. if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
  351. av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
  352. return -1;
  353. }
  354. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  355. for( i = 0; i < 4; i++ ) {
  356. xvid_enc_frame.input.plane[i] = picture->data[i];
  357. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  358. }
  359. /* Encoder Flags */
  360. xvid_enc_frame.vop_flags = x->vop_flags;
  361. xvid_enc_frame.vol_flags = x->vol_flags;
  362. xvid_enc_frame.motion = x->me_flags;
  363. xvid_enc_frame.type =
  364. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  365. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  366. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  367. XVID_TYPE_AUTO;
  368. /* Pixel aspect ratio setting */
  369. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
  370. avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
  371. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  372. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  373. return -1;
  374. }
  375. xvid_enc_frame.par = XVID_PAR_EXT;
  376. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  377. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  378. /* Quant Setting */
  379. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  380. else xvid_enc_frame.quant = 0;
  381. /* Matrices */
  382. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  383. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  384. /* Encode */
  385. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  386. &xvid_enc_frame, &xvid_enc_stats);
  387. /* Two-pass log buffer swapping */
  388. avctx->stats_out = NULL;
  389. if( x->twopassbuffer ) {
  390. tmp = x->old_twopassbuffer;
  391. x->old_twopassbuffer = x->twopassbuffer;
  392. x->twopassbuffer = tmp;
  393. x->twopassbuffer[0] = 0;
  394. if( x->old_twopassbuffer[0] != 0 ) {
  395. avctx->stats_out = x->old_twopassbuffer;
  396. }
  397. }
  398. if (xerr > 0) {
  399. *got_packet = 1;
  400. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  401. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  402. p->pict_type = AV_PICTURE_TYPE_P;
  403. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  404. p->pict_type = AV_PICTURE_TYPE_B;
  405. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  406. p->pict_type = AV_PICTURE_TYPE_S;
  407. else
  408. p->pict_type = AV_PICTURE_TYPE_I;
  409. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  410. p->key_frame = 1;
  411. pkt->flags |= AV_PKT_FLAG_KEY;
  412. if( x->quicktime_format )
  413. return xvid_strip_vol_header(avctx, pkt,
  414. xvid_enc_stats.hlength, xerr);
  415. } else
  416. p->key_frame = 0;
  417. pkt->size = xerr;
  418. return 0;
  419. } else {
  420. if (!user_packet)
  421. av_free_packet(pkt);
  422. if (!xerr)
  423. return 0;
  424. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  425. return -1;
  426. }
  427. }
  428. /**
  429. * Destroy the private context for the encoder.
  430. * All buffers are freed, and the Xvid encoder context is destroyed.
  431. *
  432. * @param avctx AVCodecContext pointer to context
  433. * @return Returns 0, success guaranteed
  434. */
  435. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  436. struct xvid_context *x = avctx->priv_data;
  437. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  438. av_freep(&avctx->extradata);
  439. if( x->twopassbuffer != NULL ) {
  440. av_free(x->twopassbuffer);
  441. av_free(x->old_twopassbuffer);
  442. avctx->stats_out = NULL;
  443. }
  444. av_free(x->twopassfile);
  445. av_free(x->intra_matrix);
  446. av_free(x->inter_matrix);
  447. return 0;
  448. }
  449. /**
  450. * Routine to create a global VO/VOL header for MP4 container.
  451. * What we do here is extract the header from the Xvid bitstream
  452. * as it is encoded. We also strip the repeated headers from the
  453. * bitstream when a global header is requested for MPEG-4 ISO
  454. * compliance.
  455. *
  456. * @param avctx AVCodecContext pointer to context
  457. * @param frame Pointer to encoded frame data
  458. * @param header_len Length of header to search
  459. * @param frame_len Length of encoded frame data
  460. * @return Returns new length of frame data
  461. */
  462. int xvid_strip_vol_header(AVCodecContext *avctx,
  463. AVPacket *pkt,
  464. unsigned int header_len,
  465. unsigned int frame_len) {
  466. int vo_len = 0, i;
  467. for( i = 0; i < header_len - 3; i++ ) {
  468. if( pkt->data[i] == 0x00 &&
  469. pkt->data[i+1] == 0x00 &&
  470. pkt->data[i+2] == 0x01 &&
  471. pkt->data[i+3] == 0xB6 ) {
  472. vo_len = i;
  473. break;
  474. }
  475. }
  476. if( vo_len > 0 ) {
  477. /* We need to store the header, so extract it */
  478. if( avctx->extradata == NULL ) {
  479. avctx->extradata = av_malloc(vo_len);
  480. memcpy(avctx->extradata, pkt->data, vo_len);
  481. avctx->extradata_size = vo_len;
  482. }
  483. /* Less dangerous now, memmove properly copies the two
  484. chunks of overlapping data */
  485. memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
  486. pkt->size = frame_len - vo_len;
  487. }
  488. return 0;
  489. }
  490. /**
  491. * Routine to correct a possibly erroneous framerate being fed to us.
  492. * Xvid currently chokes on framerates where the ticks per frame is
  493. * extremely large. This function works to correct problems in this area
  494. * by estimating a new framerate and taking the simpler fraction of
  495. * the two presented.
  496. *
  497. * @param avctx Context that contains the framerate to correct.
  498. */
  499. void xvid_correct_framerate(AVCodecContext *avctx) {
  500. int frate, fbase;
  501. int est_frate, est_fbase;
  502. int gcd;
  503. float est_fps, fps;
  504. frate = avctx->time_base.den;
  505. fbase = avctx->time_base.num;
  506. gcd = av_gcd(frate, fbase);
  507. if( gcd > 1 ) {
  508. frate /= gcd;
  509. fbase /= gcd;
  510. }
  511. if( frate <= 65000 && fbase <= 65000 ) {
  512. avctx->time_base.den = frate;
  513. avctx->time_base.num = fbase;
  514. return;
  515. }
  516. fps = (float)frate / (float)fbase;
  517. est_fps = roundf(fps * 1000.0) / 1000.0;
  518. est_frate = (int)est_fps;
  519. if( est_fps > (int)est_fps ) {
  520. est_frate = (est_frate + 1) * 1000;
  521. est_fbase = (int)roundf((float)est_frate / est_fps);
  522. } else
  523. est_fbase = 1;
  524. gcd = av_gcd(est_frate, est_fbase);
  525. if( gcd > 1 ) {
  526. est_frate /= gcd;
  527. est_fbase /= gcd;
  528. }
  529. if( fbase > est_fbase ) {
  530. avctx->time_base.den = est_frate;
  531. avctx->time_base.num = est_fbase;
  532. av_log(avctx, AV_LOG_DEBUG,
  533. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  534. est_fps, (((est_fps - fps)/fps) * 100.0));
  535. } else {
  536. avctx->time_base.den = frate;
  537. avctx->time_base.num = fbase;
  538. }
  539. }
  540. /*
  541. * Xvid 2-Pass Kludge Section
  542. *
  543. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  544. * this section spends time replacing the first pass plugin so we can write
  545. * statistic information as libavcodec requests in. We have another kludge
  546. * that allows us to pass data to the second pass in Xvid without a custom
  547. * rate-control plugin.
  548. */
  549. /**
  550. * Initialize the two-pass plugin and context.
  551. *
  552. * @param param Input construction parameter structure
  553. * @param handle Private context handle
  554. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  555. */
  556. static int xvid_ff_2pass_create(xvid_plg_create_t * param,
  557. void ** handle) {
  558. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
  559. char *log = x->context->twopassbuffer;
  560. /* Do a quick bounds check */
  561. if( log == NULL )
  562. return XVID_ERR_FAIL;
  563. /* We use snprintf() */
  564. /* This is because we can safely prevent a buffer overflow */
  565. log[0] = 0;
  566. snprintf(log, BUFFER_REMAINING(log),
  567. "# ffmpeg 2-pass log file, using xvid codec\n");
  568. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  569. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  570. XVID_VERSION_MAJOR(XVID_VERSION),
  571. XVID_VERSION_MINOR(XVID_VERSION),
  572. XVID_VERSION_PATCH(XVID_VERSION));
  573. *handle = x->context;
  574. return 0;
  575. }
  576. /**
  577. * Destroy the two-pass plugin context.
  578. *
  579. * @param ref Context pointer for the plugin
  580. * @param param Destrooy context
  581. * @return Returns 0, success guaranteed
  582. */
  583. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  584. xvid_plg_destroy_t *param) {
  585. /* Currently cannot think of anything to do on destruction */
  586. /* Still, the framework should be here for reference/use */
  587. if( ref->twopassbuffer != NULL )
  588. ref->twopassbuffer[0] = 0;
  589. return 0;
  590. }
  591. /**
  592. * Enable fast encode mode during the first pass.
  593. *
  594. * @param ref Context pointer for the plugin
  595. * @param param Frame data
  596. * @return Returns 0, success guaranteed
  597. */
  598. static int xvid_ff_2pass_before(struct xvid_context *ref,
  599. xvid_plg_data_t *param) {
  600. int motion_remove;
  601. int motion_replacements;
  602. int vop_remove;
  603. /* Nothing to do here, result is changed too much */
  604. if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
  605. return 0;
  606. /* We can implement a 'turbo' first pass mode here */
  607. param->quant = 2;
  608. /* Init values */
  609. motion_remove = ~XVID_ME_CHROMA_PVOP &
  610. ~XVID_ME_CHROMA_BVOP &
  611. ~XVID_ME_EXTSEARCH16 &
  612. ~XVID_ME_ADVANCEDDIAMOND16;
  613. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  614. XVID_ME_SKIP_DELTASEARCH |
  615. XVID_ME_FASTREFINE16 |
  616. XVID_ME_BFRAME_EARLYSTOP;
  617. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  618. ~XVID_VOP_FAST_MODEDECISION_RD &
  619. ~XVID_VOP_TRELLISQUANT &
  620. ~XVID_VOP_INTER4V &
  621. ~XVID_VOP_HQACPRED;
  622. param->vol_flags &= ~XVID_VOL_GMC;
  623. param->vop_flags &= vop_remove;
  624. param->motion_flags &= motion_remove;
  625. param->motion_flags |= motion_replacements;
  626. return 0;
  627. }
  628. /**
  629. * Capture statistic data and write it during first pass.
  630. *
  631. * @param ref Context pointer for the plugin
  632. * @param param Statistic data
  633. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  634. */
  635. static int xvid_ff_2pass_after(struct xvid_context *ref,
  636. xvid_plg_data_t *param) {
  637. char *log = ref->twopassbuffer;
  638. const char *frame_types = " ipbs";
  639. char frame_type;
  640. /* Quick bounds check */
  641. if( log == NULL )
  642. return XVID_ERR_FAIL;
  643. /* Convert the type given to us into a character */
  644. if( param->type < 5 && param->type > 0 ) {
  645. frame_type = frame_types[param->type];
  646. } else {
  647. return XVID_ERR_FAIL;
  648. }
  649. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  650. "%c %d %d %d %d %d %d\n",
  651. frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
  652. param->stats.ublks, param->stats.length, param->stats.hlength);
  653. return 0;
  654. }
  655. /**
  656. * Dispatch function for our custom plugin.
  657. * This handles the dispatch for the Xvid plugin. It passes data
  658. * on to other functions for actual processing.
  659. *
  660. * @param ref Context pointer for the plugin
  661. * @param cmd The task given for us to complete
  662. * @param p1 First parameter (varies)
  663. * @param p2 Second parameter (varies)
  664. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  665. */
  666. int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
  667. switch( cmd ) {
  668. case XVID_PLG_INFO:
  669. case XVID_PLG_FRAME:
  670. return 0;
  671. case XVID_PLG_BEFORE:
  672. return xvid_ff_2pass_before(ref, p1);
  673. case XVID_PLG_CREATE:
  674. return xvid_ff_2pass_create(p1, p2);
  675. case XVID_PLG_AFTER:
  676. return xvid_ff_2pass_after(ref, p1);
  677. case XVID_PLG_DESTROY:
  678. return xvid_ff_2pass_destroy(ref, p1);
  679. default:
  680. return XVID_ERR_FAIL;
  681. }
  682. }
  683. /**
  684. * Xvid codec definition for libavcodec.
  685. */
  686. AVCodec ff_libxvid_encoder = {
  687. .name = "libxvid",
  688. .type = AVMEDIA_TYPE_VIDEO,
  689. .id = CODEC_ID_MPEG4,
  690. .priv_data_size = sizeof(struct xvid_context),
  691. .init = xvid_encode_init,
  692. .encode2 = xvid_encode_frame,
  693. .close = xvid_encode_close,
  694. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  695. .long_name= NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  696. };
  697. #endif /* CONFIG_LIBXVID_ENCODER */