xvidff.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 xvidmpeg4.c
  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 "common.h"
  29. #include "avcodec.h"
  30. #include "xvid_internal.h"
  31. /**
  32. * Buffer management macros.
  33. */
  34. #define BUFFER_SIZE 1024
  35. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  36. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  37. /* For PPC Use */
  38. #if HAVE_ALTIVEC==1
  39. extern int has_altivec(void);
  40. #endif
  41. /**
  42. * Structure for the private XviD context.
  43. * This stores all the private context for the codec.
  44. */
  45. typedef struct xvid_context {
  46. void *encoder_handle; /** Handle for XviD Encoder */
  47. int xsize, ysize; /** Frame size */
  48. int vop_flags; /** VOP flags for XviD Encoder */
  49. int vol_flags; /** VOL flags for XviD Encoder */
  50. int me_flags; /** Motion Estimation flags */
  51. int qscale; /** Do we use constant scale? */
  52. int quicktime_format; /** Are we in a QT-based format? */
  53. AVFrame encoded_picture; /** Encoded frame information */
  54. char *twopassbuffer; /** Character buffer for two-pass */
  55. char *old_twopassbuffer; /** Old character buffer (two-pass) */
  56. char *twopassfile; /** second pass temp file name */
  57. unsigned char *intra_matrix; /** P-Frame Quant Matrix */
  58. unsigned char *inter_matrix; /** I-Frame Quant Matrix */
  59. } xvid_context_t;
  60. /**
  61. * Structure for the private first-pass plugin.
  62. */
  63. typedef struct xvid_ff_pass1 {
  64. int version; /** XviD version */
  65. xvid_context_t *context; /** Pointer to private context */
  66. } xvid_ff_pass1_t;
  67. /* Prototypes - See function implementation for details */
  68. int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned int header_len, unsigned int frame_len);
  69. int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
  70. void xvid_correct_framerate(AVCodecContext *avctx);
  71. /**
  72. * Creates the private context for the encoder.
  73. * All buffers are allocated, settings are loaded from the user,
  74. * and the encoder context created.
  75. *
  76. * @param avctx AVCodecContext pointer to context
  77. * @return Returns 0 on success, -1 on failure
  78. */
  79. int ff_xvid_encode_init(AVCodecContext *avctx) {
  80. int xerr, i;
  81. int xvid_flags = avctx->flags;
  82. xvid_context_t *x = avctx->priv_data;
  83. uint16_t *intra, *inter;
  84. int fd;
  85. xvid_plugin_single_t single;
  86. xvid_ff_pass1_t rc2pass1;
  87. xvid_plugin_2pass2_t rc2pass2;
  88. xvid_gbl_init_t xvid_gbl_init;
  89. xvid_enc_create_t xvid_enc_create;
  90. xvid_enc_plugin_t plugins[7];
  91. /* Bring in VOP flags from ffmpeg command-line */
  92. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  93. if( xvid_flags & CODEC_FLAG_4MV )
  94. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  95. if( xvid_flags & CODEC_FLAG_TRELLIS_QUANT)
  96. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  97. if( xvid_flags & CODEC_FLAG_AC_PRED )
  98. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  99. if( xvid_flags & CODEC_FLAG_GRAY )
  100. x->vop_flags |= XVID_VOP_GREYSCALE;
  101. /* Decide which ME quality setting to use */
  102. x->me_flags = 0;
  103. switch( avctx->me_method ) {
  104. case ME_FULL: /* Quality 6 */
  105. x->me_flags |= XVID_ME_EXTSEARCH16
  106. | XVID_ME_EXTSEARCH8;
  107. case ME_EPZS: /* Quality 4 */
  108. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8
  109. | XVID_ME_HALFPELREFINE8
  110. | XVID_ME_CHROMA_PVOP
  111. | XVID_ME_CHROMA_BVOP;
  112. case ME_LOG: /* Quality 2 */
  113. case ME_PHODS:
  114. case ME_X1:
  115. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16
  116. | XVID_ME_HALFPELREFINE16;
  117. case ME_ZERO: /* Quality 0 */
  118. default:
  119. break;
  120. }
  121. /* Decide how we should decide blocks */
  122. switch( avctx->mb_decision ) {
  123. case 2:
  124. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  125. x->me_flags |= XVID_ME_HALFPELREFINE8_RD
  126. | XVID_ME_QUARTERPELREFINE8_RD
  127. | XVID_ME_EXTSEARCH_RD
  128. | XVID_ME_CHECKPREDICTION_RD;
  129. case 1:
  130. if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
  131. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  132. x->me_flags |= XVID_ME_HALFPELREFINE16_RD
  133. | XVID_ME_QUARTERPELREFINE16_RD;
  134. default:
  135. break;
  136. }
  137. /* Bring in VOL flags from ffmpeg command-line */
  138. x->vol_flags = 0;
  139. if( xvid_flags & CODEC_FLAG_GMC ) {
  140. x->vol_flags |= XVID_VOL_GMC;
  141. x->me_flags |= XVID_ME_GME_REFINE;
  142. }
  143. if( xvid_flags & CODEC_FLAG_QPEL ) {
  144. x->vol_flags |= XVID_VOL_QUARTERPEL;
  145. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  146. if( x->vop_flags & XVID_VOP_INTER4V )
  147. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  148. }
  149. memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
  150. xvid_gbl_init.version = XVID_VERSION;
  151. xvid_gbl_init.debug = 0;
  152. #ifdef ARCH_POWERPC
  153. /* XviD's PPC support is borked, use libavcodec to detect */
  154. #if HAVE_ALTIVEC==1
  155. if( has_altivec() ) {
  156. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
  157. } else
  158. #endif
  159. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
  160. #else
  161. /* XviD can detect on x86 */
  162. xvid_gbl_init.cpu_flags = 0;
  163. #endif
  164. /* Initialize */
  165. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  166. /* Create the encoder reference */
  167. memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
  168. xvid_enc_create.version = XVID_VERSION;
  169. /* Store the desired frame size */
  170. xvid_enc_create.width = x->xsize = avctx->width;
  171. xvid_enc_create.height = x->ysize = avctx->height;
  172. /* XviD can determine the proper profile to use */
  173. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  174. /* We don't use zones or threads */
  175. xvid_enc_create.zones = NULL;
  176. xvid_enc_create.num_zones = 0;
  177. xvid_enc_create.num_threads = 0;
  178. xvid_enc_create.plugins = plugins;
  179. xvid_enc_create.num_plugins = 0;
  180. /* Initialize Buffers */
  181. x->twopassbuffer = NULL;
  182. x->old_twopassbuffer = NULL;
  183. x->twopassfile = NULL;
  184. if( xvid_flags & CODEC_FLAG_PASS1 ) {
  185. memset(&rc2pass1, 0, sizeof(xvid_ff_pass1_t));
  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. memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
  201. rc2pass2.version = XVID_VERSION;
  202. rc2pass2.bitrate = avctx->bit_rate;
  203. fd = av_tempfile("xvidff.", &(x->twopassfile));
  204. if( fd == -1 ) {
  205. av_log(avctx, AV_LOG_ERROR,
  206. "XviD: Cannot write 2-pass pipe\n");
  207. return -1;
  208. }
  209. if( avctx->stats_in == NULL ) {
  210. av_log(avctx, AV_LOG_ERROR,
  211. "XviD: No 2-pass information loaded for second pass\n");
  212. return -1;
  213. }
  214. if( strlen(avctx->stats_in) >
  215. write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
  216. close(fd);
  217. av_log(avctx, AV_LOG_ERROR,
  218. "XviD: Cannot write to 2-pass pipe\n");
  219. return -1;
  220. }
  221. close(fd);
  222. rc2pass2.filename = x->twopassfile;
  223. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  224. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  225. xvid_enc_create.num_plugins++;
  226. } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
  227. /* Single Pass Bitrate Control! */
  228. memset(&single, 0, sizeof(xvid_plugin_single_t));
  229. single.version = XVID_VERSION;
  230. single.bitrate = avctx->bit_rate;
  231. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  232. plugins[xvid_enc_create.num_plugins].param = &single;
  233. xvid_enc_create.num_plugins++;
  234. }
  235. /* Luminance Masking */
  236. if( 0.0 != avctx->lumi_masking ) {
  237. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  238. plugins[xvid_enc_create.num_plugins].param = NULL;
  239. xvid_enc_create.num_plugins++;
  240. }
  241. /* Frame Rate and Key Frames */
  242. xvid_correct_framerate(avctx);
  243. xvid_enc_create.fincr = avctx->time_base.num;
  244. xvid_enc_create.fbase = avctx->time_base.den;
  245. if( avctx->gop_size > 0 )
  246. xvid_enc_create.max_key_interval = avctx->gop_size;
  247. else
  248. xvid_enc_create.max_key_interval = 240; /* XviD's best default */
  249. /* Quants */
  250. if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
  251. else x->qscale = 0;
  252. xvid_enc_create.min_quant[0] = avctx->qmin;
  253. xvid_enc_create.min_quant[1] = avctx->qmin;
  254. xvid_enc_create.min_quant[2] = avctx->qmin;
  255. xvid_enc_create.max_quant[0] = avctx->qmax;
  256. xvid_enc_create.max_quant[1] = avctx->qmax;
  257. xvid_enc_create.max_quant[2] = avctx->qmax;
  258. /* Quant Matrices */
  259. x->intra_matrix = x->inter_matrix = NULL;
  260. if( avctx->mpeg_quant )
  261. x->vol_flags |= XVID_VOL_MPEGQUANT;
  262. if( (avctx->intra_matrix || avctx->inter_matrix) ) {
  263. x->vol_flags |= XVID_VOL_MPEGQUANT;
  264. if( avctx->intra_matrix ) {
  265. intra = avctx->intra_matrix;
  266. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  267. } else
  268. intra = NULL;
  269. if( avctx->inter_matrix ) {
  270. inter = avctx->inter_matrix;
  271. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  272. } else
  273. inter = NULL;
  274. for( i = 0; i < 64; i++ ) {
  275. if( intra )
  276. x->intra_matrix[i] = (unsigned char)intra[i];
  277. if( inter )
  278. x->inter_matrix[i] = (unsigned char)inter[i];
  279. }
  280. }
  281. /* Misc Settings */
  282. xvid_enc_create.frame_drop_ratio = 0;
  283. xvid_enc_create.global = 0;
  284. if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
  285. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  286. /* Determines which codec mode we are operating in */
  287. avctx->extradata = NULL;
  288. avctx->extradata_size = 0;
  289. if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
  290. /* In this case, we are claiming to be MPEG4 */
  291. x->quicktime_format = 1;
  292. avctx->codec_id = CODEC_ID_MPEG4;
  293. } else {
  294. /* We are claiming to be XviD */
  295. x->quicktime_format = 0;
  296. if(!avctx->codec_tag)
  297. avctx->codec_tag = ff_get_fourcc("xvid");
  298. }
  299. /* Bframes */
  300. xvid_enc_create.max_bframes = avctx->max_b_frames;
  301. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  302. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  303. if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  304. /* Create encoder context */
  305. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  306. if( xerr ) {
  307. av_log(avctx, AV_LOG_ERROR, "XviD: Could not create encoder reference\n");
  308. return -1;
  309. }
  310. x->encoder_handle = xvid_enc_create.handle;
  311. avctx->coded_frame = &x->encoded_picture;
  312. return 0;
  313. }
  314. /**
  315. * Encodes a single frame.
  316. *
  317. * @param avctx AVCodecContext pointer to context
  318. * @param frame Pointer to encoded frame buffer
  319. * @param buf_size Size of encoded frame buffer
  320. * @param data Pointer to AVFrame of unencoded frame
  321. * @return Returns 0 on success, -1 on failure
  322. */
  323. int ff_xvid_encode_frame(AVCodecContext *avctx,
  324. unsigned char *frame, int buf_size, void *data) {
  325. int xerr, i;
  326. char *tmp;
  327. xvid_context_t *x = avctx->priv_data;
  328. AVFrame *picture = data;
  329. AVFrame *p = &(x->encoded_picture);
  330. xvid_enc_frame_t xvid_enc_frame;
  331. xvid_enc_stats_t xvid_enc_stats;
  332. /* Start setting up the frame */
  333. memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
  334. xvid_enc_frame.version = XVID_VERSION;
  335. memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
  336. xvid_enc_stats.version = XVID_VERSION;
  337. *p = *picture;
  338. /* Let XviD know where to put the frame. */
  339. xvid_enc_frame.bitstream = frame;
  340. xvid_enc_frame.length = buf_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 = XVID_TYPE_AUTO;
  356. /* Quant Setting */
  357. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  358. else xvid_enc_frame.quant = 0;
  359. /* Matrices */
  360. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  361. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  362. /* Encode */
  363. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  364. &xvid_enc_frame, &xvid_enc_stats);
  365. /* Two-pass log buffer swapping */
  366. avctx->stats_out = NULL;
  367. if( x->twopassbuffer ) {
  368. tmp = x->old_twopassbuffer;
  369. x->old_twopassbuffer = x->twopassbuffer;
  370. x->twopassbuffer = tmp;
  371. x->twopassbuffer[0] = 0;
  372. if( x->old_twopassbuffer[0] != 0 ) {
  373. avctx->stats_out = x->old_twopassbuffer;
  374. }
  375. }
  376. if( 0 <= xerr ) {
  377. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  378. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  379. p->pict_type = FF_P_TYPE;
  380. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  381. p->pict_type = FF_B_TYPE;
  382. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  383. p->pict_type = FF_S_TYPE;
  384. else
  385. p->pict_type = FF_I_TYPE;
  386. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  387. p->key_frame = 1;
  388. if( x->quicktime_format )
  389. return xvid_strip_vol_header(avctx, frame,
  390. xvid_enc_stats.hlength, xerr);
  391. } else
  392. p->key_frame = 0;
  393. return xerr;
  394. } else {
  395. av_log(avctx, AV_LOG_ERROR, "XviD: Encoding Error Occurred: %i\n", xerr);
  396. return -1;
  397. }
  398. }
  399. /**
  400. * Destroys the private context for the encoder.
  401. * All buffers are freed, and the XviD encoder context is destroyed.
  402. *
  403. * @param avctx AVCodecContext pointer to context
  404. * @return Returns 0, success guaranteed
  405. */
  406. int ff_xvid_encode_close(AVCodecContext *avctx) {
  407. xvid_context_t *x = avctx->priv_data;
  408. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  409. if( avctx->extradata != NULL )
  410. av_free(avctx->extradata);
  411. if( x->twopassbuffer != NULL ) {
  412. av_free(x->twopassbuffer);
  413. av_free(x->old_twopassbuffer);
  414. }
  415. if( x->twopassfile != NULL )
  416. av_free(x->twopassfile);
  417. if( x->intra_matrix != NULL )
  418. av_free(x->intra_matrix);
  419. if( x->inter_matrix != NULL )
  420. av_free(x->inter_matrix);
  421. return 0;
  422. }
  423. /**
  424. * Routine to create a global VO/VOL header for MP4 container.
  425. * What we do here is extract the header from the XviD bitstream
  426. * as it is encoded. We also strip the repeated headers from the
  427. * bitstream when a global header is requested for MPEG-4 ISO
  428. * compliance.
  429. *
  430. * @param avctx AVCodecContext pointer to context
  431. * @param frame Pointer to encoded frame data
  432. * @param header_len Length of header to search
  433. * @param frame_len Length of encoded frame data
  434. * @return Returns new length of frame data
  435. */
  436. int xvid_strip_vol_header(AVCodecContext *avctx,
  437. unsigned char *frame,
  438. unsigned int header_len,
  439. unsigned int frame_len) {
  440. int vo_len = 0, i;
  441. for( i = 0; i < header_len - 3; i++ ) {
  442. if( frame[i] == 0x00 &&
  443. frame[i+1] == 0x00 &&
  444. frame[i+2] == 0x01 &&
  445. frame[i+3] == 0xB6 ) {
  446. vo_len = i;
  447. break;
  448. }
  449. }
  450. if( vo_len > 0 ) {
  451. /* We need to store the header, so extract it */
  452. if( avctx->extradata == NULL ) {
  453. avctx->extradata = av_malloc(vo_len);
  454. memcpy(avctx->extradata, frame, vo_len);
  455. avctx->extradata_size = vo_len;
  456. }
  457. /* Less dangerous now, memmove properly copies the two
  458. chunks of overlapping data */
  459. memmove(frame, &(frame[vo_len]), frame_len - vo_len);
  460. return frame_len - vo_len;
  461. } else
  462. return frame_len;
  463. }
  464. /**
  465. * Routine to correct a possibly erroneous framerate being fed to us.
  466. * XviD currently chokes on framerates where the ticks per frame is
  467. * extremely large. This function works to correct problems in this area
  468. * by estimating a new framerate and taking the simpler fraction of
  469. * the two presented.
  470. *
  471. * @param avctx Context that contains the framerate to correct.
  472. */
  473. void xvid_correct_framerate(AVCodecContext *avctx) {
  474. int frate, fbase;
  475. int est_frate, est_fbase;
  476. int gcd;
  477. float est_fps, fps;
  478. frate = avctx->time_base.den;
  479. fbase = avctx->time_base.num;
  480. gcd = ff_gcd(frate, fbase);
  481. if( gcd > 1 ) {
  482. frate /= gcd;
  483. fbase /= gcd;
  484. }
  485. if( frate <= 65000 && fbase <= 65000 ) {
  486. avctx->time_base.den = frate;
  487. avctx->time_base.num = fbase;
  488. return;
  489. }
  490. fps = (float)frate / (float)fbase;
  491. est_fps = roundf(fps * 1000.0) / 1000.0;
  492. est_frate = (int)est_fps;
  493. if( est_fps > (int)est_fps ) {
  494. est_frate = (est_frate + 1) * 1000;
  495. est_fbase = (int)roundf((float)est_frate / est_fps);
  496. } else
  497. est_fbase = 1;
  498. gcd = ff_gcd(est_frate, est_fbase);
  499. if( gcd > 1 ) {
  500. est_frate /= gcd;
  501. est_fbase /= gcd;
  502. }
  503. if( fbase > est_fbase ) {
  504. avctx->time_base.den = est_frate;
  505. avctx->time_base.num = est_fbase;
  506. av_log(avctx, AV_LOG_DEBUG,
  507. "XviD: framerate re-estimated: %.2f, %.3f%% correction\n",
  508. est_fps, (((est_fps - fps)/fps) * 100.0));
  509. } else {
  510. avctx->time_base.den = frate;
  511. avctx->time_base.num = fbase;
  512. }
  513. }
  514. /*
  515. * XviD 2-Pass Kludge Section
  516. *
  517. * XviD's default 2-pass doesn't allow us to create data as we need to, so
  518. * this section spends time replacing the first pass plugin so we can write
  519. * statistic information as libavcodec requests in. We have another kludge
  520. * that allows us to pass data to the second pass in XviD without a custom
  521. * rate-control plugin.
  522. */
  523. /**
  524. * Initializes the two-pass plugin and context.
  525. *
  526. * @param param Input construction parameter structure
  527. * @param handle Private context handle
  528. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  529. */
  530. static int xvid_ff_2pass_create(xvid_plg_create_t * param,
  531. void ** handle) {
  532. xvid_ff_pass1_t *x = (xvid_ff_pass1_t *)param->param;
  533. char *log = x->context->twopassbuffer;
  534. /* Do a quick bounds check */
  535. if( log == NULL )
  536. return XVID_ERR_FAIL;
  537. /* We use snprintf() */
  538. /* This is because we can safely prevent a buffer overflow */
  539. log[0] = 0;
  540. snprintf(log, BUFFER_REMAINING(log),
  541. "# ffmpeg 2-pass log file, using xvid codec\n");
  542. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  543. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  544. XVID_VERSION_MAJOR(XVID_VERSION),
  545. XVID_VERSION_MINOR(XVID_VERSION),
  546. XVID_VERSION_PATCH(XVID_VERSION));
  547. *handle = x->context;
  548. return 0;
  549. }
  550. /**
  551. * Destroys the two-pass plugin context.
  552. *
  553. * @param ref Context pointer for the plugin
  554. * @param param Destrooy context
  555. * @return Returns 0, success guaranteed
  556. */
  557. static int xvid_ff_2pass_destroy(xvid_context_t *ref,
  558. xvid_plg_destroy_t *param) {
  559. /* Currently cannot think of anything to do on destruction */
  560. /* Still, the framework should be here for reference/use */
  561. if( ref->twopassbuffer != NULL )
  562. ref->twopassbuffer[0] = 0;
  563. return 0;
  564. }
  565. /**
  566. * Enables fast encode mode during the first pass.
  567. *
  568. * @param ref Context pointer for the plugin
  569. * @param param Frame data
  570. * @return Returns 0, success guaranteed
  571. */
  572. static int xvid_ff_2pass_before(xvid_context_t *ref,
  573. xvid_plg_data_t *param) {
  574. int motion_remove;
  575. int motion_replacements;
  576. int vop_remove;
  577. /* Nothing to do here, result is changed too much */
  578. if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
  579. return 0;
  580. /* We can implement a 'turbo' first pass mode here */
  581. param->quant = 2;
  582. /* Init values */
  583. motion_remove = ~XVID_ME_CHROMA_PVOP &
  584. ~XVID_ME_CHROMA_BVOP &
  585. ~XVID_ME_EXTSEARCH16 &
  586. ~XVID_ME_ADVANCEDDIAMOND16;
  587. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  588. XVID_ME_SKIP_DELTASEARCH |
  589. XVID_ME_FASTREFINE16 |
  590. XVID_ME_BFRAME_EARLYSTOP;
  591. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  592. ~XVID_VOP_FAST_MODEDECISION_RD &
  593. ~XVID_VOP_TRELLISQUANT &
  594. ~XVID_VOP_INTER4V &
  595. ~XVID_VOP_HQACPRED;
  596. param->vol_flags &= ~XVID_VOL_GMC;
  597. param->vop_flags &= vop_remove;
  598. param->motion_flags &= motion_remove;
  599. param->motion_flags |= motion_replacements;
  600. return 0;
  601. }
  602. /**
  603. * Captures statistic data and writes it during first pass.
  604. *
  605. * @param ref Context pointer for the plugin
  606. * @param param Statistic data
  607. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  608. */
  609. static int xvid_ff_2pass_after(xvid_context_t *ref,
  610. xvid_plg_data_t *param) {
  611. char *log = ref->twopassbuffer;
  612. char *frame_types = " ipbs";
  613. char frame_type;
  614. /* Quick bounds check */
  615. if( log == NULL )
  616. return XVID_ERR_FAIL;
  617. /* Convert the type given to us into a character */
  618. if( param->type < 5 && param->type > 0 ) {
  619. frame_type = frame_types[param->type];
  620. } else {
  621. return XVID_ERR_FAIL;
  622. }
  623. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  624. "%c %d %d %d %d %d %d\n",
  625. frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
  626. param->stats.ublks, param->stats.length, param->stats.hlength);
  627. return 0;
  628. }
  629. /**
  630. * Dispatch function for our custom plugin.
  631. * This handles the dispatch for the XviD plugin. It passes data
  632. * on to other functions for actual processing.
  633. *
  634. * @param ref Context pointer for the plugin
  635. * @param cmd The task given for us to complete
  636. * @param p1 First parameter (varies)
  637. * @param p2 Second parameter (varies)
  638. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  639. */
  640. int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
  641. switch( cmd ) {
  642. case XVID_PLG_INFO:
  643. case XVID_PLG_FRAME:
  644. return 0;
  645. case XVID_PLG_BEFORE:
  646. return xvid_ff_2pass_before(ref, p1);
  647. case XVID_PLG_CREATE:
  648. return xvid_ff_2pass_create(p1, p2);
  649. case XVID_PLG_AFTER:
  650. return xvid_ff_2pass_after(ref, p1);
  651. case XVID_PLG_DESTROY:
  652. return xvid_ff_2pass_destroy(ref, p1);
  653. default:
  654. return XVID_ERR_FAIL;
  655. }
  656. }
  657. /**
  658. * XviD codec definition for libavcodec.
  659. */
  660. AVCodec xvid_encoder = {
  661. "xvid",
  662. CODEC_TYPE_VIDEO,
  663. CODEC_ID_XVID,
  664. sizeof(xvid_context_t),
  665. ff_xvid_encode_init,
  666. ff_xvid_encode_frame,
  667. ff_xvid_encode_close,
  668. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, -1},
  669. };