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.

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